Skip to content

Commit

Permalink
Latest cleanings pre audit (#1974)
Browse files Browse the repository at this point in the history
* move pallet-liquidity-pools-gateway to pallets

* support for events in RuntimeEnv

* fix docs

* queue traits to its own file

* add queue() name

* Message recovery follow ups (#1975)

* lp-message: Use MessageHash for recovery fns

* lp-gateway: Drop domain from message recovery extrinsics

* revert moving queue traits to its own file

* rename liquidity_pools.rs to foreign_investments.rs

* remove default and fix IT

* move axelar utility to axelar

---------

Co-authored-by: Cosmin Damian <[email protected]>
  • Loading branch information
lemunozm and cdamian authored Aug 18, 2024
1 parent a1109d8 commit f1af973
Show file tree
Hide file tree
Showing 28 changed files with 2,362 additions and 2,440 deletions.
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ members = [
"pallets/keystore",
"pallets/liquidity-pools",
"pallets/liquidity-pools-gateway",
"pallets/liquidity-pools-gateway/queue",
"pallets/liquidity-pools-gateway-queue",
"pallets/liquidity-pools-forwarder",
"pallets/liquidity-rewards",
"pallets/loans",
Expand Down Expand Up @@ -236,7 +236,7 @@ pallet-investments = { path = "pallets/investments", default-features = false }
pallet-keystore = { path = "pallets/keystore", default-features = false }
pallet-liquidity-pools = { path = "pallets/liquidity-pools", default-features = false }
pallet-liquidity-pools-gateway = { path = "pallets/liquidity-pools-gateway", default-features = false }
pallet-liquidity-pools-gateway-queue = { path = "pallets/liquidity-pools-gateway/queue", default-features = false }
pallet-liquidity-pools-gateway-queue = { path = "pallets/liquidity-pools-gateway-queue", default-features = false }
pallet-liquidity-pools-forwarder = { path = "pallets/liquidity-pools-forwarder", default-features = false }
pallet-liquidity-rewards = { path = "pallets/liquidity-rewards", default-features = false }
pallet-loans = { path = "pallets/loans", default-features = false }
Expand Down
10 changes: 4 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,11 @@ Centrifuge is the infrastructure that facilitates the decentralized financing of
On top of the [Substrate FRAME](https://docs.substrate.io/reference/frame-pallets/) framework, Centrifuge Chain is composed of custom pallets which can be found inside the `pallets` folder. The following list gives a brief overview, and links to the corresponding documentation:

- [**anchors**](https://github.com/centrifuge/centrifuge-chain/tree/main/pallets/anchors) ([docs](https://reference.centrifuge.io/pallet_anchors/index.html)): Storing hashes of documents on-chain. The documents are stored in the Private Off-chain Data (POD) node network.
-

- [**anchors-v2**](https://github.com/centrifuge/centrifuge-chain/tree/main/pallets/anchors-v2) ([docs](https://reference.centrifuge.io/pallet_anchors_v2/index.html)): Second version of the pallet used to store document hashes on-chain.

- [**axelar-routers**](https://github.com/centrifuge/centrifuge-chain/tree/main/pallets/liquidity-pools-gateway/pallet-axelar-router) ([docs](https://reference.centrifuge.io/pallet-axelar-router/index.html)): Pallet that communicates with other chains through axelar.

- [**block-rewards**](https://github.com/centrifuge/centrifuge-chain/tree/main/pallets/block-rewards) ([docs](https://reference.centrifuge.io/pallet_block_rewards/index.html)): Provides means of configuring and distributing block rewards to collators as well as the annual treasury inflation.

- [**bridge**](https://github.com/centrifuge/centrifuge-chain/tree/main/pallets/bridge) ([docs](https://reference.centrifuge.io/pallet_bridge/index.html)): Connecting [ChainBridge](https://github.com/centrifuge/chainbridge-substrate) to transfer tokens to and from Ethereum.
Expand All @@ -54,12 +56,8 @@ On top of the [Substrate FRAME](https://docs.substrate.io/reference/frame-pallet
- [**liquidity-pools**](https://github.com/centrifuge/centrifuge-chain/tree/main/pallets/liquidity-pools) ([docs](https://reference.centrifuge.io/pallet_liquidity_pools/index.html)): Provides the toolset to enable foreign investments on foreign domains.

- [**liquidity-pools-gateway**](https://github.com/centrifuge/centrifuge-chain/tree/main/pallets/liquidity-pools-gateway) ([docs](https://reference.centrifuge.io/pallet_liquidity_pools_gateway/index.html)): The main handler of incoming and outgoing Liquidity Pools messages.
-
- [**liquidity-pools-gateway-queue**](https://github.com/centrifuge/centrifuge-chain/tree/main/pallets/liquidity-pools-gateway/queue) ([docs](https://reference.centrifuge.io/pallet_liquidity_pools_gateway_queue/index.html)): The queue used by the Liquidity Pools Gateway for processing inbound/outbound messages.

- [**liquidity-pools-gateway-routers**](https://github.com/centrifuge/centrifuge-chain/tree/main/pallets/liquidity-pools-gateway/routers) ([docs](https://reference.centrifuge.io/liquidity_pools_gateway_routers/index.html)): This crate contains the `DomainRouters` used by the Liquidity Pools Gateway pallet.

- [**axelar-gateway-precompile**](https://github.com/centrifuge/centrifuge-chain/tree/main/pallets/liquidity-pools-gateway/axelar-gateway-precompile) ([docs](https://reference.centrifuge.io/axelar_gateway_precompile/index.html)): Pallet that serves as an EVM precompile for incoming Liquidity Pools messages from the Axelar network.
- [**liquidity-pools-gateway-queue**](https://github.com/centrifuge/centrifuge-chain/tree/main/pallets/liquidity-pools-gateway/queue) ([docs](https://reference.centrifuge.io/pallet_liquidity_pools_gateway_queue/index.html)): The queue used by the Liquidity Pools Gateway for processing inbound/outbound messages.

- [**liquidity-rewards**](https://github.com/centrifuge/centrifuge-chain/tree/main/pallets/liquidity-rewards) ([docs](https://reference.centrifuge.io/pallet_liquidity_rewards/index.html)): Epoch based reward system.

Expand Down
3 changes: 1 addition & 2 deletions libs/mocks/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ pub mod foreign_investment_hooks;
pub mod investment;
pub mod liquidity_pools;
pub mod liquidity_pools_gateway;
pub mod liquidity_pools_gateway_queue;
pub mod pay_fee;
pub mod permissions;
pub mod pools;
pub mod pre_conditions;
pub mod queue;
pub mod rewards;
pub mod router_message;
pub mod status_notification;
Expand All @@ -30,7 +30,6 @@ pub use fees::pallet as pallet_mock_fees;
pub use investment::pallet as pallet_mock_investment;
pub use liquidity_pools::pallet as pallet_mock_liquidity_pools;
pub use liquidity_pools_gateway::pallet as pallet_mock_liquidity_pools_gateway;
pub use liquidity_pools_gateway_queue::pallet as pallet_mock_liquidity_pools_gateway_queue;
pub use pay_fee::pallet as pallet_mock_pay_fee;
pub use permissions::pallet as pallet_mock_permissions;
pub use pools::pallet as pallet_mock_pools;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,15 @@ pub mod pallet {
type CallIds<T: Config> = StorageMap<_, _, String, mock_builder::CallId>;

impl<T: Config> Pallet<T> {
pub fn mock_submit(f: impl Fn(T::Message) -> DispatchResult + 'static) -> CallHandler {
pub fn mock_queue(f: impl Fn(T::Message) -> DispatchResult + 'static) -> CallHandler {
register_call!(f)
}
}

impl<T: Config> MessageQueue for Pallet<T> {
type Message = T::Message;

fn submit(msg: Self::Message) -> DispatchResult {
fn queue(msg: Self::Message) -> DispatchResult {
execute_call!(msg)
}
}
Expand Down
10 changes: 0 additions & 10 deletions libs/traits/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,25 +30,15 @@ use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
use sp_runtime::{traits::Member, DispatchError};
use sp_std::{fmt::Debug, marker::PhantomData, vec::Vec};

/// Traits related to checked changes.
pub mod changes;
/// Traits related to data registry and collection.
pub mod data;
/// Traits related to Ethereum/EVM.
pub mod ethereum;
/// Traits related to pool fees.
pub mod fee;
/// Traits related to fees payment.
pub mod fees;
/// Traits related to interest rates.
pub mod interest;
/// Traits related to investments.
pub mod investments;
/// Traits related to liquidity pools.
pub mod liquidity_pools;
/// Traits related to rewards.
pub mod rewards;
/// Traits related to swaps.
pub mod swaps;

#[cfg(feature = "runtime-benchmarks")]
Expand Down
10 changes: 5 additions & 5 deletions libs/traits/src/liquidity_pools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,13 @@ pub trait LpMessage: Sized {
///
/// Hash - hash of the message that should be recovered.
/// Router - the address of the recovery router.
fn initiate_recovery_message(hash: [u8; 32], router: [u8; 32]) -> Self;
fn initiate_recovery_message(hash: MessageHash, router: [u8; 32]) -> Self;

/// Creates a message used for disputing message recovery.
///
/// Hash - hash of the message that should be disputed.
/// Router - the address of the recovery router.
fn dispute_recovery_message(hash: [u8; 32], router: [u8; 32]) -> Self;
fn dispute_recovery_message(hash: MessageHash, router: [u8; 32]) -> Self;

/// Checks whether a message is a forwarded one.
fn is_forwarded(&self) -> bool;
Expand Down Expand Up @@ -123,18 +123,18 @@ pub trait MessageQueue {
type Message;

/// Submit a message to the queue.
fn submit(msg: Self::Message) -> DispatchResult;
fn queue(msg: Self::Message) -> DispatchResult;
}

/// The trait required for processing queued messages.
/// The trait required for processing dequeued messages.
pub trait MessageProcessor {
/// The message type.
type Message;

/// Process a message.
fn process(msg: Self::Message) -> (DispatchResult, Weight);

/// Process a message.
/// Max weight that processing a message can take
fn max_processing_weight(msg: &Self::Message) -> Weight;
}

Expand Down
6 changes: 0 additions & 6 deletions libs/types/src/domain_address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,12 +85,6 @@ impl TypeId for DomainAddress {
const TYPE_ID: [u8; 4] = crate::ids::DOMAIN_ADDRESS_ID;
}

impl Default for DomainAddress {
fn default() -> Self {
DomainAddress::Centrifuge(AccountId32::new([0; 32]))
}
}

impl From<DomainAddress> for Domain {
fn from(x: DomainAddress) -> Self {
match x {
Expand Down
58 changes: 0 additions & 58 deletions libs/utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,42 +70,6 @@ pub fn set_block_number_timestamp<T>(
pallet_timestamp::Pallet::<T>::set_timestamp(timestamp);
}

pub fn decode_var_source<const EXPECTED_SOURCE_ADDRESS_SIZE: usize>(
source_address: &[u8],
) -> Option<[u8; EXPECTED_SOURCE_ADDRESS_SIZE]> {
const HEX_PREFIX: &str = "0x";

let mut address = [0u8; EXPECTED_SOURCE_ADDRESS_SIZE];

if source_address.len() == EXPECTED_SOURCE_ADDRESS_SIZE {
address.copy_from_slice(source_address);
return Some(address);
}

let try_bytes = match sp_std::str::from_utf8(source_address) {
Ok(res) => res.as_bytes(),
Err(_) => source_address,
};

// Attempt to hex decode source address.
let bytes = match hex::decode(try_bytes) {
Ok(res) => Some(res),
Err(_) => {
// Strip 0x prefix.
let res = try_bytes.strip_prefix(HEX_PREFIX.as_bytes())?;

hex::decode(res).ok()
}
}?;

if bytes.len() == EXPECTED_SOURCE_ADDRESS_SIZE {
address.copy_from_slice(bytes.as_slice());
Some(address)
} else {
None
}
}

pub mod math {
use sp_arithmetic::{
traits::{BaseArithmetic, EnsureFixedPointNumber},
Expand Down Expand Up @@ -233,28 +197,6 @@ pub mod math {
mod tests {
use super::*;

mod get_source_address_bytes {
const EXPECTED: usize = 20;
use super::*;

#[test]
fn get_source_address_bytes_works() {
let hash = [1u8; 20];

decode_var_source::<EXPECTED>(&hash).expect("address bytes from H160 works");

let str = String::from("d47ed02acbbb66ee8a3fe0275bd98add0aa607c3");

decode_var_source::<EXPECTED>(str.as_bytes())
.expect("address bytes from un-prefixed hex works");

let str = String::from("0xd47ed02acbbb66ee8a3fe0275bd98add0aa607c3");

decode_var_source::<EXPECTED>(str.as_bytes())
.expect("address bytes from prefixed hex works");
}
}

mod vec_to_fixed_array {
use super::*;

Expand Down
72 changes: 63 additions & 9 deletions pallets/axelar-router/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,6 @@ pub enum AxelarId {
Evm(EVMChainId),
}

impl Default for AxelarId {
fn default() -> Self {
Self::Evm(1)
}
}

/// Configuration for outbound messages though axelar
#[derive(Debug, Encode, Decode, Clone, PartialEq, Eq, TypeInfo, MaxEncodedLen)]
pub struct AxelarConfig {
Expand Down Expand Up @@ -242,9 +236,8 @@ pub mod pallet {

match config.domain {
DomainConfig::Evm(EvmConfig { chain_id, .. }) => {
let source_address_bytes =
cfg_utils::decode_var_source::<EVM_ADDRESS_LEN>(source_address)
.ok_or(Error::<T>::InvalidSourceAddress)?;
let source_address_bytes = decode_var_source::<EVM_ADDRESS_LEN>(source_address)
.ok_or(Error::<T>::InvalidSourceAddress)?;

T::Receiver::receive(
AxelarId::Evm(chain_id).into(),
Expand Down Expand Up @@ -432,3 +425,64 @@ pub fn wrap_into_axelar_msg(

Ok(encoded_axelar_contract)
}

/// Decodes the source address which can be:
/// - a 20 bytes array
/// - an hexadecimal character secuence (40 characters)
/// - an hexadecimal character secuence (40 characters) with 0x prefix
pub fn decode_var_source<const EXPECTED_SOURCE_ADDRESS_SIZE: usize>(
source_address: &[u8],
) -> Option<[u8; EXPECTED_SOURCE_ADDRESS_SIZE]> {
const HEX_PREFIX: &str = "0x";

let mut address = [0u8; EXPECTED_SOURCE_ADDRESS_SIZE];

if source_address.len() == EXPECTED_SOURCE_ADDRESS_SIZE {
address.copy_from_slice(source_address);
return Some(address);
}

let try_bytes = match sp_std::str::from_utf8(source_address) {
Ok(res) => res.as_bytes(),
Err(_) => source_address,
};

// Attempt to hex decode source address.
let bytes = match hex::decode(try_bytes) {
Ok(res) => Some(res),
Err(_) => {
// Strip 0x prefix.
let res = try_bytes.strip_prefix(HEX_PREFIX.as_bytes())?;

hex::decode(res).ok()
}
}?;

if bytes.len() == EXPECTED_SOURCE_ADDRESS_SIZE {
address.copy_from_slice(bytes.as_slice());
Some(address)
} else {
None
}
}

#[cfg(test)]
mod test_decode_var_source {
const EXPECTED: usize = 20;
use super::*;

#[test]
fn success() {
assert!(decode_var_source::<EXPECTED>(&[1; 20]).is_some());

assert!(decode_var_source::<EXPECTED>(
"d47ed02acbbb66ee8a3fe0275bd98add0aa607c3".as_bytes()
)
.is_some());

assert!(decode_var_source::<EXPECTED>(
"0xd47ed02acbbb66ee8a3fe0275bd98add0aa607c3".as_bytes()
)
.is_some());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ pub mod pallet {
impl<T: Config> MessageQueueT for Pallet<T> {
type Message = T::Message;

fn submit(message: Self::Message) -> DispatchResult {
fn queue(message: Self::Message) -> DispatchResult {
let nonce = <MessageNonceStore<T>>::try_mutate(|n| {
n.ensure_add_assign(T::MessageNonce::one())?;
Ok::<T::MessageNonce, DispatchError>(*n)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,17 @@
// GNU General Public License for more details.

use cfg_mocks::pallet_mock_liquidity_pools_gateway;
use cfg_primitives::LPGatewayQueueMessageNonce;
use cfg_types::domain_address::Domain;
use frame_support::derive_impl;

use crate::{self as pallet_liquidity_pools_gateway_queue, Config};

type Nonce = u64;

frame_support::construct_runtime!(
pub enum Runtime {
System: frame_system,
LPGatewayMock: pallet_mock_liquidity_pools_gateway,
LPGatewayQueue: pallet_liquidity_pools_gateway_queue,
Processor: pallet_mock_liquidity_pools_gateway,
Queue: pallet_liquidity_pools_gateway_queue,
}
);

Expand All @@ -33,14 +33,14 @@ impl frame_system::Config for Runtime {
}

impl pallet_mock_liquidity_pools_gateway::Config for Runtime {
type Destination = Domain;
type Destination = ();
type Message = u32;
}

impl Config for Runtime {
type Message = u32;
type MessageNonce = LPGatewayQueueMessageNonce;
type MessageProcessor = LPGatewayMock;
type MessageNonce = Nonce;
type MessageProcessor = Processor;
type RuntimeEvent = RuntimeEvent;
}

Expand Down
Loading

0 comments on commit f1af973

Please sign in to comment.