messages bridge between RialtoParachain and Millau (#1218)

This commit is contained in:
Svyatoslav Nikolsky
2022-05-20 12:03:45 +03:00
committed by Bastian Köcher
parent 03c2f06a27
commit 5f2f61ced5
33 changed files with 1658 additions and 75 deletions
+125 -10
View File
@@ -26,13 +26,18 @@
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
use crate::millau_messages::{ToMillauMessagePayload, WithMillauMessageBridge};
use bridge_runtime_common::messages::{
source::estimate_message_dispatch_and_delivery_fee, MessageBridge,
};
use sp_api::impl_runtime_apis;
use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
use sp_runtime::{
create_runtime_str, generic, impl_opaque_keys,
traits::{AccountIdLookup, Block as BlockT},
transaction_validity::{TransactionSource, TransactionValidity},
ApplyExtrinsicResult,
ApplyExtrinsicResult, FixedU128,
};
use sp_std::prelude::*;
@@ -52,6 +57,7 @@ pub use frame_support::{
};
pub use frame_system::{Call as SystemCall, EnsureRoot};
pub use pallet_balances::Call as BalancesCall;
pub use pallet_sudo::Call as SudoCall;
pub use pallet_timestamp::Call as TimestampCall;
pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;
#[cfg(any(feature = "std", test))]
@@ -63,6 +69,9 @@ pub use bp_rialto_parachain::{
Index, Signature, MAXIMUM_BLOCK_WEIGHT,
};
pub use pallet_bridge_grandpa::Call as BridgeGrandpaCall;
pub use pallet_bridge_messages::Call as MessagesCall;
// Polkadot & XCM imports
use pallet_xcm::XcmPassthrough;
use polkadot_parachain::primitives::Sibling;
@@ -76,6 +85,8 @@ use xcm_builder::{
};
use xcm_executor::{Config, XcmExecutor};
mod millau_messages;
/// The address format for describing accounts.
pub type Address = MultiAddress<AccountId, ()>;
/// Block type as expected by this runtime.
@@ -88,6 +99,7 @@ pub type BlockId = generic::BlockId<Block>;
pub type SignedExtra = (
frame_system::CheckNonZeroSender<Runtime>,
frame_system::CheckSpecVersion<Runtime>,
frame_system::CheckTxVersion<Runtime>,
frame_system::CheckGenesis<Runtime>,
frame_system::CheckEra<Runtime>,
frame_system::CheckNonce<Runtime>,
@@ -342,9 +354,11 @@ pub type XcmOriginToTransactDispatchOrigin = (
XcmPassthrough<Origin>,
);
pub const BASE_XCM_WEIGHT: Weight = 1_000_000;
parameter_types! {
// One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.
pub UnitWeightCost: Weight = 1_000_000;
pub UnitWeightCost: Weight = BASE_XCM_WEIGHT;
// One UNIT buys 1 second of weight.
pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), UNIT);
pub const MaxInstructions: u32 = 100;
@@ -366,6 +380,11 @@ pub type Barrier = (
// ^^^ Parent & its unit plurality gets free execution
);
/// Outbound XCM weigher type.
pub type OutboundXcmWeigher = FixedWeightBounds<UnitWeightCost, (), MaxInstructions>;
/// XCM weigher type.
pub type XcmWeigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;
pub struct XcmConfig;
impl Config for XcmConfig {
type Call = Call;
@@ -376,7 +395,7 @@ impl Config for XcmConfig {
type IsTeleporter = NativeAsset; // <- should be enough to allow teleportation of UNIT
type UniversalLocation = UniversalLocation;
type Barrier = Barrier;
type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;
type Weigher = XcmWeigher;
type Trader = UsingComponents<IdentityFee<Balance>, RelayLocation, AccountId, Balances, ()>;
type ResponseHandler = PolkadotXcm;
type AssetTrap = PolkadotXcm;
@@ -412,7 +431,7 @@ impl pallet_xcm::Config for Runtime {
type XcmExecutor = XcmExecutor<XcmConfig>;
type XcmTeleportFilter = Everything;
type XcmReserveTransferFilter = Everything;
type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;
type Weigher = XcmWeigher;
type Origin = Origin;
type Call = Call;
const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
@@ -454,10 +473,71 @@ impl pallet_aura::Config for Runtime {
type MaxAuthorities = MaxAuthorities;
}
// /// Configure the pallet template in pallets/template.
// impl template::Config for Runtime {
// type Event = Event;
// }
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;
/// Number of headers to keep.
///
/// Assuming the worst case of every header being finalized, we will keep headers at least for a
/// week.
pub const HeadersToKeep: u32 = 7 * bp_millau::DAYS as u32;
}
pub type MillauGrandpaInstance = ();
impl pallet_bridge_grandpa::Config for Runtime {
type BridgedChain = bp_millau::Millau;
type MaxRequests = MaxRequests;
type HeadersToKeep = HeadersToKeep;
type WeightInfo = pallet_bridge_grandpa::weights::MillauWeight<Runtime>;
}
parameter_types! {
pub const MaxMessagesToPruneAtOnce: bp_messages::MessageNonce = 8;
pub const MaxUnrewardedRelayerEntriesAtInboundLane: bp_messages::MessageNonce =
bp_millau::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX;
pub const MaxUnconfirmedMessagesAtInboundLane: bp_messages::MessageNonce =
bp_millau::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX;
// `IdentityFee` is used by Rialto => we may use weight directly
pub const GetDeliveryConfirmationTransactionFee: Balance =
bp_rialto_parachain::MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT as _;
pub const RootAccountForPayments: Option<AccountId> = None;
pub const BridgedChainId: bp_runtime::ChainId = bp_runtime::MILLAU_CHAIN_ID;
}
/// Instance of the messages pallet used to relay messages to/from Millau chain.
pub type WithMillauMessagesInstance = ();
impl pallet_bridge_messages::Config<WithMillauMessagesInstance> for Runtime {
type Event = Event;
type WeightInfo = pallet_bridge_messages::weights::MillauWeight<Runtime>;
type Parameter = millau_messages::RialtoParachainToMillauMessagesParameter;
type MaxMessagesToPruneAtOnce = MaxMessagesToPruneAtOnce;
type MaxUnrewardedRelayerEntriesAtInboundLane = MaxUnrewardedRelayerEntriesAtInboundLane;
type MaxUnconfirmedMessagesAtInboundLane = MaxUnconfirmedMessagesAtInboundLane;
type OutboundPayload = crate::millau_messages::ToMillauMessagePayload;
type OutboundMessageFee = Balance;
type InboundPayload = crate::millau_messages::FromMillauMessagePayload;
type InboundMessageFee = bp_millau::Balance;
type InboundRelayer = bp_millau::AccountId;
type AccountIdConverter = bp_rialto_parachain::AccountIdConverter;
type TargetHeaderChain = crate::millau_messages::Millau;
type LaneMessageVerifier = crate::millau_messages::ToMillauMessageVerifier;
type MessageDeliveryAndDispatchPayment = ();
type OnMessageAccepted = ();
type OnDeliveryConfirmed = ();
type SourceHeaderChain = crate::millau_messages::Millau;
type MessageDispatch = crate::millau_messages::FromMillauMessageDispatch;
type BridgedChainId = BridgedChainId;
}
// Create the runtime by composing the FRAME pallets that were previously configured.
construct_runtime!(
@@ -486,8 +566,9 @@ construct_runtime!(
CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,
DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,
// //Template
// TemplatePallet: template::{Pallet, Call, Storage, Event<T>},
// Millau bridge modules.
BridgeMillauGrandpa: pallet_bridge_grandpa::{Pallet, Call, Storage},
BridgeMillauMessages: pallet_bridge_messages::{Pallet, Call, Storage, Event<T>, Config<T>},
}
);
@@ -600,6 +681,40 @@ impl_runtime_apis! {
}
}
impl bp_millau::MillauFinalityApi<Block> for Runtime {
fn best_finalized() -> (bp_millau::BlockNumber, bp_millau::Hash) {
let header = BridgeMillauGrandpa::best_finalized();
(header.number, header.hash())
}
}
impl bp_millau::ToMillauOutboundLaneApi<Block, Balance, ToMillauMessagePayload> for Runtime {
fn estimate_message_delivery_and_dispatch_fee(
_lane_id: bp_messages::LaneId,
payload: ToMillauMessagePayload,
millau_to_this_conversion_rate: Option<FixedU128>,
) -> Option<Balance> {
estimate_message_dispatch_and_delivery_fee::<WithMillauMessageBridge>(
&payload,
WithMillauMessageBridge::RELAYER_FEE_PERCENT,
millau_to_this_conversion_rate,
).ok()
}
fn message_details(
lane: bp_messages::LaneId,
begin: bp_messages::MessageNonce,
end: bp_messages::MessageNonce,
) -> Vec<bp_messages::MessageDetails<Balance>> {
bridge_runtime_common::messages_api::outbound_message_details::<
Runtime,
WithMillauMessagesInstance,
WithMillauMessageBridge,
OutboundXcmWeigher,
>(lane, begin, end)
}
}
#[cfg(feature = "runtime-benchmarks")]
impl frame_benchmarking::Benchmark<Block> for Runtime {
fn dispatch_benchmark(
@@ -0,0 +1,304 @@
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity Bridges Common is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
//! Everything required to serve Millau <-> RialtoParachain messages.
// TODO: this is almost exact copy of `millau_messages.rs` from Rialto runtime.
// Should be extracted to a separate crate and reused here.
use crate::Runtime;
use bp_messages::{
source_chain::{SenderOrigin, TargetHeaderChain},
target_chain::{ProvedMessages, SourceHeaderChain},
InboundLaneData, LaneId, Message, MessageNonce, Parameter as MessagesParameter,
};
use bp_runtime::{Chain, ChainId, MILLAU_CHAIN_ID, RIALTO_PARACHAIN_CHAIN_ID};
use bridge_runtime_common::messages::{self, MessageBridge, MessageTransaction};
use codec::{Decode, Encode};
use frame_support::{
parameter_types,
weights::{DispatchClass, Weight},
RuntimeDebug,
};
use scale_info::TypeInfo;
use sp_runtime::{traits::Saturating, FixedPointNumber, FixedU128};
use sp_std::convert::TryFrom;
/// Initial value of `MillauToRialtoParachainConversionRate` parameter.
pub const INITIAL_MILLAU_TO_RIALTO_PARACHAIN_CONVERSION_RATE: FixedU128 =
FixedU128::from_inner(FixedU128::DIV);
/// Initial value of `MillauFeeMultiplier` parameter.
pub const INITIAL_MILLAU_FEE_MULTIPLIER: FixedU128 = FixedU128::from_inner(FixedU128::DIV);
/// Weight of 2 XCM instructions is for simple `Trap(42)` program, coming through bridge
/// (it is prepended with `UniversalOrigin` instruction). It is used just for simplest manual
/// tests, confirming that we don't break encoding somewhere between.
pub const BASE_XCM_WEIGHT_TWICE: Weight = 2 * crate::BASE_XCM_WEIGHT;
parameter_types! {
/// Millau to RialtoParachain conversion rate. Initially we treat both tokens as equal.
pub storage MillauToRialtoParachainConversionRate: FixedU128 = INITIAL_MILLAU_TO_RIALTO_PARACHAIN_CONVERSION_RATE;
/// Fee multiplier value at Millau chain.
pub storage MillauFeeMultiplier: FixedU128 = INITIAL_MILLAU_FEE_MULTIPLIER;
}
/// Message payload for RialtoParachain -> Millau messages.
pub type ToMillauMessagePayload = messages::source::FromThisChainMessagePayload;
/// Message verifier for RialtoParachain -> Millau messages.
pub type ToMillauMessageVerifier =
messages::source::FromThisChainMessageVerifier<WithMillauMessageBridge>;
/// Message payload for Millau -> RialtoParachain messages.
pub type FromMillauMessagePayload = messages::target::FromBridgedChainMessagePayload<crate::Call>;
/// Call-dispatch based message dispatch for Millau -> RialtoParachain messages.
pub type FromMillauMessageDispatch = messages::target::FromBridgedChainMessageDispatch<
WithMillauMessageBridge,
xcm_executor::XcmExecutor<crate::XcmConfig>,
crate::XcmWeigher,
// 2 XCM instructions is for simple `Trap(42)` program, coming through bridge
// (it is prepended with `UniversalOrigin` instruction)
frame_support::traits::ConstU64<BASE_XCM_WEIGHT_TWICE>,
>;
/// Messages proof for Millau -> RialtoParachain messages.
pub type FromMillauMessagesProof = messages::target::FromBridgedChainMessagesProof<bp_millau::Hash>;
/// Messages delivery proof for RialtoParachain -> Millau messages.
pub type ToMillauMessagesDeliveryProof =
messages::source::FromBridgedChainMessagesDeliveryProof<bp_millau::Hash>;
/// Millau <-> RialtoParachain message bridge.
#[derive(RuntimeDebug, Clone, Copy)]
pub struct WithMillauMessageBridge;
impl MessageBridge for WithMillauMessageBridge {
const RELAYER_FEE_PERCENT: u32 = 10;
const THIS_CHAIN_ID: ChainId = RIALTO_PARACHAIN_CHAIN_ID;
const BRIDGED_CHAIN_ID: ChainId = MILLAU_CHAIN_ID;
const BRIDGED_MESSAGES_PALLET_NAME: &'static str =
bp_rialto_parachain::WITH_RIALTO_PARACHAIN_MESSAGES_PALLET_NAME;
type ThisChain = RialtoParachain;
type BridgedChain = Millau;
fn bridged_balance_to_this_balance(
bridged_balance: bp_millau::Balance,
bridged_to_this_conversion_rate_override: Option<FixedU128>,
) -> bp_rialto_parachain::Balance {
let conversion_rate = bridged_to_this_conversion_rate_override
.unwrap_or_else(|| MillauToRialtoParachainConversionRate::get());
bp_rialto_parachain::Balance::try_from(conversion_rate.saturating_mul_int(bridged_balance))
.unwrap_or(bp_rialto_parachain::Balance::MAX)
}
}
/// RialtoParachain chain from message lane point of view.
#[derive(RuntimeDebug, Clone, Copy)]
pub struct RialtoParachain;
impl messages::ChainWithMessages for RialtoParachain {
type Hash = bp_rialto_parachain::Hash;
type AccountId = bp_rialto_parachain::AccountId;
type Signer = bp_rialto_parachain::AccountSigner;
type Signature = bp_rialto_parachain::Signature;
type Weight = Weight;
type Balance = bp_rialto_parachain::Balance;
}
impl messages::ThisChainWithMessages for RialtoParachain {
type Call = crate::Call;
type Origin = crate::Origin;
fn is_message_accepted(send_origin: &Self::Origin, lane: &LaneId) -> bool {
send_origin.linked_account().is_some() && (*lane == [0, 0, 0, 0] || *lane == [0, 0, 0, 1])
}
fn maximal_pending_messages_at_outbound_lane() -> MessageNonce {
MessageNonce::MAX
}
fn estimate_delivery_confirmation_transaction() -> MessageTransaction<Weight> {
let inbound_data_size =
InboundLaneData::<bp_rialto_parachain::AccountId>::encoded_size_hint(
bp_rialto_parachain::MAXIMAL_ENCODED_ACCOUNT_ID_SIZE,
1,
1,
)
.unwrap_or(u32::MAX);
MessageTransaction {
dispatch_weight:
bp_rialto_parachain::MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT,
size: inbound_data_size
.saturating_add(bp_millau::EXTRA_STORAGE_PROOF_SIZE)
.saturating_add(bp_rialto_parachain::TX_EXTRA_BYTES),
}
}
fn transaction_payment(
transaction: MessageTransaction<Weight>,
) -> bp_rialto_parachain::Balance {
// `transaction` may represent transaction from the future, when multiplier value will
// be larger, so let's use slightly increased value
let multiplier = FixedU128::saturating_from_rational(110, 100)
.saturating_mul(pallet_transaction_payment::Pallet::<Runtime>::next_fee_multiplier());
// in our testnets, both per-byte fee and weight-to-fee are 1:1
messages::transaction_payment(
bp_rialto_parachain::BlockWeights::get()
.get(DispatchClass::Normal)
.base_extrinsic,
1,
multiplier,
|weight| weight as _,
transaction,
)
}
}
/// Millau chain from message lane point of view.
#[derive(RuntimeDebug, Clone, Copy)]
pub struct Millau;
impl messages::ChainWithMessages for Millau {
type Hash = bp_millau::Hash;
type AccountId = bp_millau::AccountId;
type Signer = bp_millau::AccountSigner;
type Signature = bp_millau::Signature;
type Weight = Weight;
type Balance = bp_millau::Balance;
}
impl messages::BridgedChainWithMessages for Millau {
fn maximal_extrinsic_size() -> u32 {
bp_millau::Millau::max_extrinsic_size()
}
fn verify_dispatch_weight(_message_payload: &[u8]) -> bool {
true
}
fn estimate_delivery_transaction(
message_payload: &[u8],
include_pay_dispatch_fee_cost: bool,
message_dispatch_weight: Weight,
) -> MessageTransaction<Weight> {
let message_payload_len = u32::try_from(message_payload.len()).unwrap_or(u32::MAX);
let extra_bytes_in_payload = Weight::from(message_payload_len)
.saturating_sub(pallet_bridge_messages::EXPECTED_DEFAULT_MESSAGE_LENGTH.into());
MessageTransaction {
dispatch_weight: extra_bytes_in_payload
.saturating_mul(bp_millau::ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT)
.saturating_add(bp_millau::DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT)
.saturating_sub(if include_pay_dispatch_fee_cost {
0
} else {
bp_millau::PAY_INBOUND_DISPATCH_FEE_WEIGHT
})
.saturating_add(message_dispatch_weight),
size: message_payload_len
.saturating_add(bp_rialto_parachain::EXTRA_STORAGE_PROOF_SIZE)
.saturating_add(bp_millau::TX_EXTRA_BYTES),
}
}
fn transaction_payment(transaction: MessageTransaction<Weight>) -> bp_millau::Balance {
// we don't have a direct access to the value of multiplier at Millau chain
// => it is a messages module parameter
let multiplier = MillauFeeMultiplier::get();
// in our testnets, both per-byte fee and weight-to-fee are 1:1
messages::transaction_payment(
bp_millau::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic,
1,
multiplier,
|weight| weight as _,
transaction,
)
}
}
impl TargetHeaderChain<ToMillauMessagePayload, bp_millau::AccountId> for Millau {
type Error = &'static str;
// The proof is:
// - hash of the header this proof has been created with;
// - the storage proof of one or several keys;
// - id of the lane we prove state of.
type MessagesDeliveryProof = ToMillauMessagesDeliveryProof;
fn verify_message(payload: &ToMillauMessagePayload) -> Result<(), Self::Error> {
messages::source::verify_chain_message::<WithMillauMessageBridge>(payload)
}
fn verify_messages_delivery_proof(
proof: Self::MessagesDeliveryProof,
) -> Result<(LaneId, InboundLaneData<bp_rialto_parachain::AccountId>), Self::Error> {
messages::source::verify_messages_delivery_proof::<
WithMillauMessageBridge,
Runtime,
crate::MillauGrandpaInstance,
>(proof)
}
}
impl SourceHeaderChain<bp_millau::Balance> for Millau {
type Error = &'static str;
// The proof is:
// - hash of the header this proof has been created with;
// - the storage proof of one or several keys;
// - id of the lane we prove messages for;
// - inclusive range of messages nonces that are proved.
type MessagesProof = FromMillauMessagesProof;
fn verify_messages_proof(
proof: Self::MessagesProof,
messages_count: u32,
) -> Result<ProvedMessages<Message<bp_millau::Balance>>, Self::Error> {
messages::target::verify_messages_proof::<
WithMillauMessageBridge,
Runtime,
crate::MillauGrandpaInstance,
>(proof, messages_count)
}
}
impl SenderOrigin<crate::AccountId> for crate::Origin {
fn linked_account(&self) -> Option<crate::AccountId> {
match self.caller {
crate::OriginCaller::system(frame_system::RawOrigin::Signed(ref submitter)) =>
Some(submitter.clone()),
_ => None,
}
}
}
/// RialtoParachain -> Millau message lane pallet parameters.
#[derive(RuntimeDebug, Clone, Encode, Decode, PartialEq, Eq, TypeInfo)]
pub enum RialtoParachainToMillauMessagesParameter {
/// The conversion formula we use is: `RialtoParachainTokens = MillauTokens * conversion_rate`.
MillauToRialtoParachainConversionRate(FixedU128),
}
impl MessagesParameter for RialtoParachainToMillauMessagesParameter {
fn save(&self) {
match *self {
RialtoParachainToMillauMessagesParameter::MillauToRialtoParachainConversionRate(
ref conversion_rate,
) => MillauToRialtoParachainConversionRate::set(conversion_rate),
}
}
}