Skip to content

Commit

Permalink
Adjust path style (#99)
Browse files Browse the repository at this point in the history
* Bridge related pallets

* fee market

* format

* evm

* xcm

* format

* MaxMessagesToPruneAtOnce

* move ByteArray

* move AccountToAssetId

* move UniqueSaturatedInto

* Const

* format
  • Loading branch information
jiguantong authored Dec 6, 2022
1 parent 437b769 commit 14b7e7b
Show file tree
Hide file tree
Showing 16 changed files with 414 additions and 457 deletions.
48 changes: 26 additions & 22 deletions runtime/crab/src/pallets/bridge_dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,30 +20,23 @@ pub use pallet_bridge_dispatch::Instance1 as WithDarwiniaDispatch;

// darwinia
use crate::*;
use bp_message_dispatch::{CallValidate, IntoDispatchOrigin as IntoDispatchOriginT};
use bp_messages::{LaneId, MessageNonce};
use darwinia_message_transact::{total_payment, Call as MessageTransactCall, LcmpEthOrigin};
use pallet_bridge_dispatch::Config;
// substrate
use frame_support::ensure;
use frame_system::RawOrigin;
use sp_runtime::transaction_validity::{InvalidTransaction, TransactionValidityError};

pub struct CallValidator;
impl CallValidate<AccountId, RuntimeOrigin, RuntimeCall> for CallValidator {
impl bp_message_dispatch::CallValidate<AccountId, RuntimeOrigin, RuntimeCall> for CallValidator {
fn check_receiving_before_dispatch(
relayer_account: &AccountId,
call: &RuntimeCall,
) -> Result<(), &'static str> {
match call {
RuntimeCall::MessageTransact(MessageTransactCall::message_transact {
RuntimeCall::MessageTransact(darwinia_message_transact::Call::message_transact {
transaction: tx,
}) => {
let total_payment = total_payment::<Runtime>((&**tx).into());
let total_payment =
darwinia_message_transact::total_payment::<Runtime>((&**tx).into());
let relayer =
pallet_evm::Pallet::<Runtime>::account_basic(&H160(relayer_account.0)).0;

ensure!(relayer.balance >= total_payment, "Insufficient balance");
frame_support::ensure!(relayer.balance >= total_payment, "Insufficient balance");
Ok(())
},
_ => Ok(()),
Expand All @@ -54,31 +47,42 @@ impl CallValidate<AccountId, RuntimeOrigin, RuntimeCall> for CallValidator {
relayer_account: &AccountId,
origin: &RuntimeOrigin,
call: &RuntimeCall,
) -> Result<(), TransactionValidityError> {
) -> Result<(), sp_runtime::transaction_validity::TransactionValidityError> {
match call {
RuntimeCall::MessageTransact(MessageTransactCall::message_transact {
RuntimeCall::MessageTransact(darwinia_message_transact::Call::message_transact {
transaction: tx,
}) => match origin.caller {
OriginCaller::MessageTransact(LcmpEthOrigin::MessageTransact(id)) => {
let total_payment = total_payment::<Runtime>((&**tx).into());
OriginCaller::MessageTransact(
darwinia_message_transact::LcmpEthOrigin::MessageTransact(id),
) => {
let total_payment =
darwinia_message_transact::total_payment::<Runtime>((&**tx).into());
pallet_balances::Pallet::<Runtime>::transfer(
RawOrigin::Signed(*relayer_account).into(),
frame_system::RawOrigin::Signed(*relayer_account).into(),
id.into(),
total_payment.as_u128(),
)
.map_err(|_| TransactionValidityError::Invalid(InvalidTransaction::Payment))?;
.map_err(|_| {
sp_runtime::transaction_validity::TransactionValidityError::Invalid(
sp_runtime::transaction_validity::InvalidTransaction::Payment,
)
})?;

Ok(())
},
_ => Err(TransactionValidityError::Invalid(InvalidTransaction::BadSigner)),
_ => Err(sp_runtime::transaction_validity::TransactionValidityError::Invalid(
sp_runtime::transaction_validity::InvalidTransaction::BadSigner,
)),
},
_ => Ok(()),
}
}
}

pub struct IntoDispatchOrigin;
impl IntoDispatchOriginT<AccountId, RuntimeCall, RuntimeOrigin> for IntoDispatchOrigin {
impl bp_message_dispatch::IntoDispatchOrigin<AccountId, RuntimeCall, RuntimeOrigin>
for IntoDispatchOrigin
{
fn into_dispatch_origin(id: &AccountId, call: &RuntimeCall) -> RuntimeOrigin {
match call {
RuntimeCall::MessageTransact(darwinia_message_transact::Call::message_transact {
Expand All @@ -89,9 +93,9 @@ impl IntoDispatchOriginT<AccountId, RuntimeCall, RuntimeOrigin> for IntoDispatch
}
}

impl Config<WithDarwiniaDispatch> for Runtime {
impl pallet_bridge_dispatch::Config<WithDarwiniaDispatch> for Runtime {
type AccountIdConverter = bp_crab::AccountIdConverter;
type BridgeMessageId = (LaneId, MessageNonce);
type BridgeMessageId = (bp_messages::LaneId, bp_messages::MessageNonce);
type CallValidator = CallValidator;
type EncodedCall = bm_darwinia::FromDarwiniaEncodedCall;
type IntoDispatchOrigin = IntoDispatchOrigin;
Expand Down
16 changes: 3 additions & 13 deletions runtime/crab/src/pallets/bridge_grandpa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,22 +20,12 @@ pub use pallet_bridge_grandpa::Instance1 as WithDarwiniaGrandpa;

// darwinia
use crate::*;
use pallet_bridge_grandpa::Config;

frame_support::parameter_types! {
// This is a pretty unscientific cap.
//
// Note that once this is hit the pallet will essentially throttle incoming requests down to one
// call per block.
pub const MaxRequests: u32 = 50;
pub const DarwiniaHeadersToKeep: u32 = 500;
}

impl Config<WithDarwiniaGrandpa> for Runtime {
impl pallet_bridge_grandpa::Config<WithDarwiniaGrandpa> for Runtime {
type BridgedChain = bp_darwinia::DarwiniaLike;
type HeadersToKeep = DarwiniaHeadersToKeep;
type HeadersToKeep = ConstU32<500>;
type MaxBridgedAuthorities = ();
type MaxBridgedHeaderSize = ();
type MaxRequests = MaxRequests;
type MaxRequests = ConstU32<50>;
type WeightInfo = ();
}
31 changes: 13 additions & 18 deletions runtime/crab/src/pallets/bridge_messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,9 @@
use pallet_bridge_messages::Instance1 as WithDarwiniaMessages;

// darwinia
use crate::{bm_darwinia::ToDarwiniaMaximalOutboundPayloadSize, *};
use bp_messages::{source_chain::SenderOrigin, MessageNonce};
use bp_runtime::{ChainId, DARWINIA_CHAIN_ID};
use pallet_bridge_messages::Config;
use pallet_fee_market::s2s::{
FeeMarketMessageAcceptedHandler, FeeMarketMessageConfirmedHandler, FeeMarketPayment,
};
use crate::*;

impl SenderOrigin<AccountId> for RuntimeOrigin {
impl bp_messages::source_chain::SenderOrigin<AccountId> for RuntimeOrigin {
fn linked_account(&self) -> Option<AccountId> {
match self.caller {
OriginCaller::system(frame_system::RawOrigin::Signed(ref submitter)) =>
Expand All @@ -38,31 +32,32 @@ impl SenderOrigin<AccountId> for RuntimeOrigin {
}

frame_support::parameter_types! {
pub const MaxMessagesToPruneAtOnce: MessageNonce = 8;
pub const BridgedChainId: ChainId = DARWINIA_CHAIN_ID;
pub const MaxUnconfirmedMessagesAtInboundLane: MessageNonce =
pub const BridgedChainId: bp_runtime::ChainId = bp_runtime::DARWINIA_CHAIN_ID;
pub const MaxUnconfirmedMessagesAtInboundLane: bp_messages::MessageNonce =
bp_darwinia::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX;
pub const MaxUnrewardedRelayerEntriesAtInboundLane: MessageNonce =
pub const MaxUnrewardedRelayerEntriesAtInboundLane: bp_messages::MessageNonce =
bp_darwinia::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX;
pub RootAccountForPayments: Option<AccountId> = None;
}

impl Config<WithDarwiniaMessages> for Runtime {
impl pallet_bridge_messages::Config<WithDarwiniaMessages> for Runtime {
type AccountIdConverter = bp_crab::AccountIdConverter;
type BridgedChainId = BridgedChainId;
type InboundMessageFee = bp_darwinia::Balance;
type InboundPayload = bm_darwinia::FromDarwiniaMessagePayload;
type InboundRelayer = bp_darwinia::AccountId;
type LaneMessageVerifier = bm_darwinia::ToDarwiniaMessageVerifier<Self>;
type MaxMessagesToPruneAtOnce = MaxMessagesToPruneAtOnce;
type MaxMessagesToPruneAtOnce = ConstU64<8>;
type MaxUnconfirmedMessagesAtInboundLane = MaxUnconfirmedMessagesAtInboundLane;
type MaxUnrewardedRelayerEntriesAtInboundLane = MaxUnrewardedRelayerEntriesAtInboundLane;
type MaximalOutboundPayloadSize = ToDarwiniaMaximalOutboundPayloadSize;
type MaximalOutboundPayloadSize = bm_darwinia::ToDarwiniaMaximalOutboundPayloadSize;
type MessageDeliveryAndDispatchPayment =
FeeMarketPayment<Self, WithDarwiniaFeeMarket, Balances>;
pallet_fee_market::s2s::FeeMarketPayment<Self, WithDarwiniaFeeMarket, Balances>;
type MessageDispatch = bm_darwinia::FromDarwiniaMessageDispatch;
type OnDeliveryConfirmed = FeeMarketMessageConfirmedHandler<Self, WithDarwiniaFeeMarket>;
type OnMessageAccepted = FeeMarketMessageAcceptedHandler<Self, WithDarwiniaFeeMarket>;
type OnDeliveryConfirmed =
pallet_fee_market::s2s::FeeMarketMessageConfirmedHandler<Self, WithDarwiniaFeeMarket>;
type OnMessageAccepted =
pallet_fee_market::s2s::FeeMarketMessageAcceptedHandler<Self, WithDarwiniaFeeMarket>;
type OutboundMessageFee = bp_crab::Balance;
type OutboundPayload = bm_darwinia::ToDarwiniaMessagePayload;
type Parameter = bm_darwinia::CrabToDarwiniaParameter;
Expand Down
10 changes: 3 additions & 7 deletions runtime/crab/src/pallets/collator_selection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,20 +23,16 @@ use crate::*;
pub type CollatorSelectionUpdateOrigin = EnsureRoot<AccountId>;
frame_support::parameter_types! {
pub const PotId: PalletId = PalletId(*b"PotStake");
pub const MaxCandidates: u32 = 1000;
pub const MinCandidates: u32 = 5;
pub const SessionLength: BlockNumber = 6 * HOURS;
pub const MaxInvulnerables: u32 = 100;
pub const ExecutiveBody: BodyId = BodyId::Executive;
}

impl pallet_collator_selection::Config for Runtime {
type Currency = Balances;
// should be a multiple of session or things will get inconsistent
type KickThreshold = Period;
type MaxCandidates = MaxCandidates;
type MaxInvulnerables = MaxInvulnerables;
type MinCandidates = MinCandidates;
type MaxCandidates = ConstU32<1000>;
type MaxInvulnerables = ConstU32<100>;
type MinCandidates = ConstU32<5>;
type PotId = PotId;
type RuntimeEvent = RuntimeEvent;
type UpdateOrigin = CollatorSelectionUpdateOrigin;
Expand Down
95 changes: 48 additions & 47 deletions runtime/crab/src/pallets/evm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,26 +18,8 @@

// darwinia
use crate::*;
use darwinia_precompile_assets::{AccountToAssetId, ERC20Assets};
use darwinia_precompile_bls12_381::BLS12381;
use darwinia_precompile_state_storage::{EthereumStorageFilter, StateStorage};
// frontier
use pallet_ethereum::EthereumBlockHashMapping;
use pallet_evm::{
AddressMapping, EnsureAddressNever, EnsureAddressRoot, FeeCalculator, FixedGasWeightMapping,
Precompile, PrecompileHandle, PrecompileResult, PrecompileSet,
};
use pallet_evm_precompile_blake2::Blake2F;
use pallet_evm_precompile_bn128::{Bn128Add, Bn128Mul, Bn128Pairing};
use pallet_evm_precompile_dispatch::Dispatch;
use pallet_evm_precompile_modexp::Modexp;
use pallet_evm_precompile_simple::{ECRecover, Identity, Ripemd160, Sha256};
// moonbeam
use precompile_utils::prelude::*;
// substrate
use frame_support::{traits::FindAuthor, ConsensusEngineId};
use sp_core::crypto::ByteArray;
use sp_std::marker::PhantomData;
use pallet_evm::Precompile;

const WEIGHT_PER_GAS: u64 = 40_000;

Expand All @@ -47,12 +29,17 @@ frame_support::parameter_types! {
pub WeightPerGas: Weight = Weight::from_ref_time(WEIGHT_PER_GAS);
}

pub struct FindAuthorTruncated<F>(PhantomData<F>);
impl<F: FindAuthor<u32>> FindAuthor<H160> for FindAuthorTruncated<F> {
pub struct FindAuthorTruncated<F>(sp_std::marker::PhantomData<F>);
impl<F: frame_support::traits::FindAuthor<u32>> frame_support::traits::FindAuthor<H160>
for FindAuthorTruncated<F>
{
fn find_author<'a, I>(digests: I) -> Option<H160>
where
I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,
I: 'a + IntoIterator<Item = (frame_support::ConsensusEngineId, &'a [u8])>,
{
// substrate
use sp_core::crypto::ByteArray;

F::find_author(digests).and_then(|i| {
Aura::authorities().get(i as usize).and_then(|id| {
let raw = id.to_raw_vec();
Expand All @@ -68,15 +55,15 @@ impl<F: FindAuthor<u32>> FindAuthor<H160> for FindAuthorTruncated<F> {
}

pub struct FixedGasPrice;
impl FeeCalculator for FixedGasPrice {
impl pallet_evm::FeeCalculator for FixedGasPrice {
fn min_gas_price() -> (U256, Weight) {
(U256::from(GWEI), Weight::zero())
}
}

// TODO: Integrate to the upstream repo
pub struct FromH160;
impl<T> AddressMapping<T> for FromH160
impl<T> pallet_evm::AddressMapping<T> for FromH160
where
T: From<H160>,
{
Expand All @@ -86,14 +73,14 @@ where
}

pub struct AssetIdConverter;
impl AccountToAssetId<AccountId, AssetId> for AssetIdConverter {
impl darwinia_precompile_assets::AccountToAssetId<AccountId, AssetId> for AssetIdConverter {
fn account_to_asset_id(account_id: AccountId) -> AssetId {
let addr: H160 = account_id.into();
addr.to_low_u64_be()
}
}

pub struct CrabPrecompiles<R>(PhantomData<R>);
pub struct CrabPrecompiles<R>(sp_std::marker::PhantomData<R>);
impl<R> CrabPrecompiles<R>
where
R: pallet_evm::Config,
Expand Down Expand Up @@ -121,38 +108,52 @@ where
]
}
}
impl<R> PrecompileSet for CrabPrecompiles<R>
impl<R> pallet_evm::PrecompileSet for CrabPrecompiles<R>
where
R: pallet_evm::Config,
{
fn execute(&self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {
fn execute(
&self,
handle: &mut impl pallet_evm::PrecompileHandle,
) -> Option<pallet_evm::PrecompileResult> {
// darwinia
use darwinia_precompile_assets::AccountToAssetId;

let (code_address, caller) = (handle.code_address(), handle.context().caller);
// Filter known precompile addresses except Ethereum officials
if self.is_precompile(code_address) && code_address > addr(9) && code_address != caller {
return Some(Err(revert("cannot be called with DELEGATECALL or CALLCODE")));
return Some(Err(precompile_utils::revert(
"cannot be called with DELEGATECALL or CALLCODE",
)));
};

match code_address {
// Ethereum precompiles:
a if a == addr(1) => Some(ECRecover::execute(handle)),
a if a == addr(2) => Some(Sha256::execute(handle)),
a if a == addr(3) => Some(Ripemd160::execute(handle)),
a if a == addr(4) => Some(Identity::execute(handle)),
a if a == addr(5) => Some(Modexp::execute(handle)),
a if a == addr(6) => Some(Bn128Add::execute(handle)),
a if a == addr(7) => Some(Bn128Mul::execute(handle)),
a if a == addr(8) => Some(Bn128Pairing::execute(handle)),
a if a == addr(9) => Some(Blake2F::execute(handle)),
a if a == addr(1) => Some(pallet_evm_precompile_simple::ECRecover::execute(handle)),
a if a == addr(2) => Some(pallet_evm_precompile_simple::Sha256::execute(handle)),
a if a == addr(3) => Some(pallet_evm_precompile_simple::Ripemd160::execute(handle)),
a if a == addr(4) => Some(pallet_evm_precompile_simple::Identity::execute(handle)),
a if a == addr(5) => Some(pallet_evm_precompile_modexp::Modexp::execute(handle)),
a if a == addr(6) => Some(pallet_evm_precompile_bn128::Bn128Add::execute(handle)),
a if a == addr(7) => Some(pallet_evm_precompile_bn128::Bn128Mul::execute(handle)),
a if a == addr(8) => Some(pallet_evm_precompile_bn128::Bn128Pairing::execute(handle)),
a if a == addr(9) => Some(pallet_evm_precompile_blake2::Blake2F::execute(handle)),
// Darwinia precompiles: [1024, 2048) for stable precompiles.
a if a == addr(1024) =>
Some(<StateStorage<Runtime, EthereumStorageFilter>>::execute(handle)),
a if a == addr(1025) => Some(<Dispatch<Runtime>>::execute(handle)),
a if a == addr(1024) => Some(<darwinia_precompile_state_storage::StateStorage<
Runtime,
darwinia_precompile_state_storage::EthereumStorageFilter,
>>::execute(handle)),
a if a == addr(1025) =>
Some(<pallet_evm_precompile_dispatch::Dispatch<Runtime>>::execute(handle)),
// [1026, 1536) reserved for assets precompiles.
a if (1026..1536).contains(&AssetIdConverter::account_to_asset_id(a.into())) =>
Some(<ERC20Assets<Runtime, AssetIdConverter>>::execute(handle)),
Some(<darwinia_precompile_assets::ERC20Assets<Runtime, AssetIdConverter>>::execute(
handle,
)),
// [1536, 2048) reserved for other stable precompiles.
// [2048..) reserved for the experimental precompiles.
a if a == addr(2048) => Some(<BLS12381<Runtime>>::execute(handle)),
a if a == addr(2048) =>
Some(<darwinia_precompile_bls12_381::BLS12381<Runtime>>::execute(handle)),
_ => None,
}
}
Expand All @@ -165,20 +166,20 @@ where
impl pallet_evm::Config for Runtime {
type AddressMapping = FromH160;
type BlockGasLimit = BlockGasLimit;
type BlockHashMapping = EthereumBlockHashMapping<Self>;
type CallOrigin = EnsureAddressRoot<AccountId>;
type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;
type CallOrigin = pallet_evm::EnsureAddressRoot<AccountId>;
type ChainId = ConstU64<44>;
type Currency = Balances;
type FeeCalculator = FixedGasPrice;
type FindAuthor = FindAuthorTruncated<Aura>;
type GasWeightMapping = FixedGasWeightMapping<Self>;
type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
type OnChargeTransaction = ();
type PrecompilesType = CrabPrecompiles<Self>;
type PrecompilesValue = PrecompilesValue;
type Runner = pallet_evm::runner::stack::Runner<Self>;
type RuntimeEvent = RuntimeEvent;
type WeightPerGas = WeightPerGas;
type WithdrawOrigin = EnsureAddressNever<AccountId>;
type WithdrawOrigin = pallet_evm::EnsureAddressNever<AccountId>;
}

fn addr(a: u64) -> H160 {
Expand Down
Loading

0 comments on commit 14b7e7b

Please sign in to comment.