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
+9 -3
View File
@@ -18,8 +18,8 @@ use beefy_primitives::crypto::AuthorityId as BeefyId;
use bp_millau::derive_account_from_rialto_id;
use millau_runtime::{
AccountId, AuraConfig, BalancesConfig, BeefyConfig, BridgeRialtoMessagesConfig,
BridgeWestendGrandpaConfig, GenesisConfig, GrandpaConfig, SessionConfig, SessionKeys,
Signature, SudoConfig, SystemConfig, WASM_BINARY,
BridgeRialtoParachainMessagesConfig, BridgeWestendGrandpaConfig, GenesisConfig, GrandpaConfig,
SessionConfig, SessionKeys, Signature, SudoConfig, SystemConfig, WASM_BINARY,
};
use sp_consensus_aura::sr25519::AuthorityId as AuraId;
use sp_core::{sr25519, Pair, Public};
@@ -151,7 +151,7 @@ fn endowed_accounts() -> Vec<AccountId> {
get_account_id_from_seed::<sr25519::Public>("George//stash"),
get_account_id_from_seed::<sr25519::Public>("Harry//stash"),
get_account_id_from_seed::<sr25519::Public>("RialtoMessagesOwner"),
get_account_id_from_seed::<sr25519::Public>("WithRialtoTokenSwap"),
get_account_id_from_seed::<sr25519::Public>("RialtoParachainMessagesOwner"),
pallet_bridge_messages::relayer_fund_account_id::<
bp_millau::AccountId,
bp_millau::AccountIdConverter,
@@ -217,6 +217,12 @@ fn testnet_genesis(
owner: Some(get_account_id_from_seed::<sr25519::Public>("RialtoMessagesOwner")),
..Default::default()
},
bridge_rialto_parachain_messages: BridgeRialtoParachainMessagesConfig {
owner: Some(get_account_id_from_seed::<sr25519::Public>(
"RialtoParachainMessagesOwner",
)),
..Default::default()
},
xcm_pallet: Default::default(),
}
}
+4
View File
@@ -20,7 +20,9 @@ serde = { version = "1.0", optional = true, features = ["derive"] }
bp-header-chain = { path = "../../../primitives/header-chain", default-features = false }
bp-messages = { path = "../../../primitives/messages", default-features = false }
bp-millau = { path = "../../../primitives/chain-millau", default-features = false }
bp-polkadot-core = { path = "../../../primitives/polkadot-core", default-features = false }
bp-rialto = { path = "../../../primitives/chain-rialto", default-features = false }
bp-rialto-parachain = { path = "../../../primitives/chain-rialto-parachain", default-features = false }
bp-runtime = { path = "../../../primitives/runtime", default-features = false }
bp-westend = { path = "../../../primitives/chain-westend", default-features = false }
bridge-runtime-common = { path = "../../runtime-common", default-features = false }
@@ -87,7 +89,9 @@ std = [
"bp-header-chain/std",
"bp-messages/std",
"bp-millau/std",
"bp-polkadot-core/std",
"bp-rialto/std",
"bp-rialto-parachain/std",
"bp-runtime/std",
"bp-westend/std",
"bridge-runtime-common/std",
+98 -3
View File
@@ -29,14 +29,21 @@
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
pub mod rialto_messages;
pub mod rialto_parachain_messages;
pub mod xcm_config;
use crate::rialto_messages::{ToRialtoMessagePayload, WithRialtoMessageBridge};
use crate::{
rialto_messages::{ToRialtoMessagePayload, WithRialtoMessageBridge},
rialto_parachain_messages::{
ToRialtoParachainMessagePayload, WithRialtoParachainMessageBridge,
},
};
use beefy_primitives::{crypto::AuthorityId as BeefyId, mmr::MmrLeafVersion, ValidatorSet};
use bridge_runtime_common::messages::{
source::estimate_message_dispatch_and_delivery_fee, MessageBridge,
};
use codec::Decode;
use pallet_grandpa::{
fg_primitives, AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList,
};
@@ -49,7 +56,9 @@ use sp_mmr_primitives::{
};
use sp_runtime::{
create_runtime_str, generic, impl_opaque_keys,
traits::{Block as BlockT, IdentityLookup, Keccak256, NumberFor, OpaqueKeys},
traits::{
Block as BlockT, Header as HeaderT, IdentityLookup, Keccak256, NumberFor, OpaqueKeys,
},
transaction_validity::{TransactionSource, TransactionValidity},
ApplyExtrinsicResult, FixedPointNumber, FixedU128, Perquintill,
};
@@ -416,6 +425,15 @@ impl pallet_bridge_grandpa::Config<WestendGrandpaInstance> for Runtime {
type WeightInfo = pallet_bridge_grandpa::weights::MillauWeight<Runtime>;
}
pub type RialtoParachainGrandpaInstance = pallet_bridge_grandpa::Instance2;
impl pallet_bridge_grandpa::Config<RialtoParachainGrandpaInstance> for Runtime {
type BridgedChain = bp_rialto_parachain::RialtoParachain;
type MaxRequests = MaxRequests;
type HeadersToKeep = HeadersToKeep;
type WeightInfo = pallet_bridge_grandpa::weights::MillauWeight<Runtime>;
}
impl pallet_shift_session_manager::Config for Runtime {}
parameter_types! {
@@ -429,6 +447,7 @@ parameter_types! {
bp_millau::MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT as _;
pub const RootAccountForPayments: Option<AccountId> = None;
pub const RialtoChainId: bp_runtime::ChainId = bp_runtime::RIALTO_CHAIN_ID;
pub const RialtoParachainChainId: bp_runtime::ChainId = bp_runtime::RIALTO_PARACHAIN_CHAIN_ID;
}
/// Instance of the messages pallet used to relay messages to/from Rialto chain.
@@ -462,6 +481,37 @@ impl pallet_bridge_messages::Config<WithRialtoMessagesInstance> for Runtime {
type BridgedChainId = RialtoChainId;
}
/// Instance of the messages pallet used to relay messages to/from RialtoParachain chain.
pub type WithRialtoParachainMessagesInstance = pallet_bridge_messages::Instance1;
impl pallet_bridge_messages::Config<WithRialtoParachainMessagesInstance> for Runtime {
type Event = Event;
type WeightInfo = pallet_bridge_messages::weights::MillauWeight<Runtime>;
type Parameter = rialto_parachain_messages::MillauToRialtoParachainMessagesParameter;
type MaxMessagesToPruneAtOnce = MaxMessagesToPruneAtOnce;
type MaxUnrewardedRelayerEntriesAtInboundLane = MaxUnrewardedRelayerEntriesAtInboundLane;
type MaxUnconfirmedMessagesAtInboundLane = MaxUnconfirmedMessagesAtInboundLane;
type OutboundPayload = crate::rialto_parachain_messages::ToRialtoParachainMessagePayload;
type OutboundMessageFee = Balance;
type InboundPayload = crate::rialto_parachain_messages::FromRialtoParachainMessagePayload;
type InboundMessageFee = bp_rialto_parachain::Balance;
type InboundRelayer = bp_rialto_parachain::AccountId;
type AccountIdConverter = bp_millau::AccountIdConverter;
type TargetHeaderChain = crate::rialto_parachain_messages::RialtoParachain;
type LaneMessageVerifier = crate::rialto_parachain_messages::ToRialtoParachainMessageVerifier;
type MessageDeliveryAndDispatchPayment = ();
type OnMessageAccepted = ();
type OnDeliveryConfirmed = ();
type SourceHeaderChain = crate::rialto_parachain_messages::RialtoParachain;
type MessageDispatch = crate::rialto_parachain_messages::FromRialtoParachainMessageDispatch;
type BridgedChainId = RialtoParachainChainId;
}
parameter_types! {
pub const RialtoParasPalletName: &'static str = bp_rialto::PARAS_PALLET_NAME;
}
@@ -509,8 +559,9 @@ construct_runtime!(
// Westend bridge modules.
BridgeWestendGrandpa: pallet_bridge_grandpa::<Instance1>::{Pallet, Call, Config<T>, Storage},
// Rialto parachains bridge modules.
// RialtoParachain bridge modules.
BridgeRialtoParachains: pallet_bridge_parachains::{Pallet, Call, Storage},
BridgeRialtoParachainMessages: pallet_bridge_messages::<Instance1>::{Pallet, Call, Storage, Event<T>, Config<T>},
// Pallet for sending XCM.
XcmPallet: pallet_xcm::{Pallet, Call, Storage, Event<T>, Origin, Config} = 99,
@@ -750,6 +801,23 @@ impl_runtime_apis! {
}
}
impl bp_rialto_parachain::RialtoParachainFinalityApi<Block> for Runtime {
fn best_finalized() -> (bp_rialto::BlockNumber, bp_rialto::Hash) {
// the parachains finality pallet is never decoding parachain heads, so it is
// only done in the integration code
use crate::rialto_parachain_messages::RIALTO_PARACHAIN_ID;
let best_rialto_parachain_head = pallet_bridge_parachains::Pallet::<
Runtime,
WitRialtoParachainsInstance,
>::best_parachain_head(RIALTO_PARACHAIN_ID.into())
.and_then(|encoded_header| bp_rialto_parachain::Header::decode(&mut &encoded_header.0[..]).ok());
match best_rialto_parachain_head {
Some(head) => (*head.number(), head.hash()),
None => (Default::default(), Default::default()),
}
}
}
impl bp_rialto::ToRialtoOutboundLaneApi<Block, Balance, ToRialtoMessagePayload> for Runtime {
fn estimate_message_delivery_and_dispatch_fee(
_lane_id: bp_messages::LaneId,
@@ -777,6 +845,33 @@ impl_runtime_apis! {
}
}
impl bp_rialto_parachain::ToRialtoParachainOutboundLaneApi<Block, Balance, ToRialtoParachainMessagePayload> for Runtime {
fn estimate_message_delivery_and_dispatch_fee(
_lane_id: bp_messages::LaneId,
payload: ToRialtoParachainMessagePayload,
rialto_parachain_to_this_conversion_rate: Option<FixedU128>,
) -> Option<Balance> {
estimate_message_dispatch_and_delivery_fee::<WithRialtoParachainMessageBridge>(
&payload,
WithRialtoParachainMessageBridge::RELAYER_FEE_PERCENT,
rialto_parachain_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,
WithRialtoParachainMessagesInstance,
WithRialtoParachainMessageBridge,
xcm_config::OutboundXcmWeigher,
>(lane, begin, end)
}
}
#[cfg(feature = "runtime-benchmarks")]
impl frame_benchmarking::Benchmark<Block> for Runtime {
fn benchmark_metadata(extra: bool) -> (
@@ -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.
use crate::Runtime;
use bp_messages::{
source_chain::{SenderOrigin, TargetHeaderChain},
target_chain::{ProvedMessages, SourceHeaderChain},
InboundLaneData, LaneId, Message, MessageNonce, Parameter as MessagesParameter,
};
use bp_polkadot_core::parachains::ParaId;
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;
/// Identifier of RialtoParachain in the Rialto relay chain.
///
/// This identifier is not something that is declared either by Rialto or RialtoParachain. This
/// is an identifier of registration. So in theory it may be changed. But since bridge is going
/// to be deployed after parachain registration AND since parachain de-registration is highly
/// likely impossible, it is fine to declare this constant here.
pub const RIALTO_PARACHAIN_ID: u32 = 2000;
/// 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::xcm_config::BASE_XCM_WEIGHT;
/// Initial value of `RialtoParachainToMillauConversionRate` parameter.
pub const INITIAL_RIALTO_PARACHAIN_TO_MILLAU_CONVERSION_RATE: FixedU128 =
FixedU128::from_inner(FixedU128::DIV);
/// Initial value of `RialtoParachainFeeMultiplier` parameter.
pub const INITIAL_RIALTO_PARACHAIN_FEE_MULTIPLIER: FixedU128 =
FixedU128::from_inner(FixedU128::DIV);
parameter_types! {
/// RialtoParachain to Millau conversion rate. Initially we treat both tokens as equal.
pub storage RialtoParachainToMillauConversionRate: FixedU128 = INITIAL_RIALTO_PARACHAIN_TO_MILLAU_CONVERSION_RATE;
/// Fee multiplier value at RialtoParachain chain.
pub storage RialtoParachainFeeMultiplier: FixedU128 = INITIAL_RIALTO_PARACHAIN_FEE_MULTIPLIER;
}
/// Message payload for Millau -> RialtoParachain messages.
pub type ToRialtoParachainMessagePayload = messages::source::FromThisChainMessagePayload;
/// Message verifier for Millau -> RialtoParachain messages.
pub type ToRialtoParachainMessageVerifier =
messages::source::FromThisChainMessageVerifier<WithRialtoParachainMessageBridge>;
/// Message payload for RialtoParachain -> Millau messages.
pub type FromRialtoParachainMessagePayload =
messages::target::FromBridgedChainMessagePayload<crate::Call>;
/// Messages proof for RialtoParachain -> Millau messages.
type FromRialtoParachainMessagesProof =
messages::target::FromBridgedChainMessagesProof<bp_rialto_parachain::Hash>;
/// Messages delivery proof for Millau -> RialtoParachain messages.
type ToRialtoParachainMessagesDeliveryProof =
messages::source::FromBridgedChainMessagesDeliveryProof<bp_rialto_parachain::Hash>;
/// Call-dispatch based message dispatch for RialtoParachain -> Millau messages.
pub type FromRialtoParachainMessageDispatch = messages::target::FromBridgedChainMessageDispatch<
WithRialtoParachainMessageBridge,
xcm_executor::XcmExecutor<crate::xcm_config::XcmConfig>,
crate::xcm_config::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>,
>;
/// Millau <-> RialtoParachain message bridge.
#[derive(RuntimeDebug, Clone, Copy)]
pub struct WithRialtoParachainMessageBridge;
impl MessageBridge for WithRialtoParachainMessageBridge {
const RELAYER_FEE_PERCENT: u32 = 10;
const THIS_CHAIN_ID: ChainId = MILLAU_CHAIN_ID;
const BRIDGED_CHAIN_ID: ChainId = RIALTO_PARACHAIN_CHAIN_ID;
const BRIDGED_MESSAGES_PALLET_NAME: &'static str = bp_millau::WITH_MILLAU_MESSAGES_PALLET_NAME;
type ThisChain = Millau;
type BridgedChain = RialtoParachain;
fn bridged_balance_to_this_balance(
bridged_balance: bp_rialto_parachain::Balance,
bridged_to_this_conversion_rate_override: Option<FixedU128>,
) -> bp_millau::Balance {
let conversion_rate = bridged_to_this_conversion_rate_override
.unwrap_or_else(|| RialtoParachainToMillauConversionRate::get());
bp_millau::Balance::try_from(conversion_rate.saturating_mul_int(bridged_balance))
.unwrap_or(bp_millau::Balance::MAX)
}
}
/// 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::ThisChainWithMessages for Millau {
type Call = crate::Call;
type Origin = crate::Origin;
fn is_message_accepted(send_origin: &Self::Origin, lane: &LaneId) -> bool {
(*lane == [0, 0, 0, 0] || *lane == [0, 0, 0, 1]) && send_origin.linked_account().is_some()
}
fn maximal_pending_messages_at_outbound_lane() -> MessageNonce {
MessageNonce::MAX
}
fn estimate_delivery_confirmation_transaction() -> MessageTransaction<Weight> {
let inbound_data_size = InboundLaneData::<bp_millau::AccountId>::encoded_size_hint(
bp_millau::MAXIMAL_ENCODED_ACCOUNT_ID_SIZE,
1,
1,
)
.unwrap_or(u32::MAX);
MessageTransaction {
dispatch_weight: bp_millau::MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT,
size: inbound_data_size
.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 {
// `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_millau::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic,
1,
multiplier,
|weight| weight as _,
transaction,
)
}
}
/// 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::BridgedChainWithMessages for RialtoParachain {
fn maximal_extrinsic_size() -> u32 {
bp_rialto_parachain::RialtoParachain::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_rialto_parachain::ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT)
.saturating_add(bp_rialto_parachain::DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT)
.saturating_sub(if include_pay_dispatch_fee_cost {
0
} else {
bp_rialto_parachain::PAY_INBOUND_DISPATCH_FEE_WEIGHT
})
.saturating_add(message_dispatch_weight),
size: message_payload_len
.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 {
// we don't have a direct access to the value of multiplier at RialtoParachain chain
// => it is a messages module parameter
let multiplier = RialtoParachainFeeMultiplier::get();
// 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,
)
}
}
impl TargetHeaderChain<ToRialtoParachainMessagePayload, bp_rialto_parachain::AccountId>
for RialtoParachain
{
type Error = &'static str;
// The proof is:
// - hash of the header this proof has been created with;
// - the storage proof or one or several keys;
// - id of the lane we prove state of.
type MessagesDeliveryProof = ToRialtoParachainMessagesDeliveryProof;
fn verify_message(payload: &ToRialtoParachainMessagePayload) -> Result<(), Self::Error> {
messages::source::verify_chain_message::<WithRialtoParachainMessageBridge>(payload)
}
fn verify_messages_delivery_proof(
proof: Self::MessagesDeliveryProof,
) -> Result<(LaneId, InboundLaneData<bp_millau::AccountId>), Self::Error> {
messages::source::verify_messages_delivery_proof_from_parachain::<
WithRialtoParachainMessageBridge,
bp_rialto_parachain::Header,
Runtime,
crate::WitRialtoParachainsInstance,
>(ParaId(RIALTO_PARACHAIN_ID), proof)
}
}
impl SourceHeaderChain<bp_rialto_parachain::Balance> for RialtoParachain {
type Error = &'static str;
// The proof is:
// - hash of the header this proof has been created with;
// - the storage proof or one or several keys;
// - id of the lane we prove messages for;
// - inclusive range of messages nonces that are proved.
type MessagesProof = FromRialtoParachainMessagesProof;
fn verify_messages_proof(
proof: Self::MessagesProof,
messages_count: u32,
) -> Result<ProvedMessages<Message<bp_rialto_parachain::Balance>>, Self::Error> {
messages::target::verify_messages_proof_from_parachain::<
WithRialtoParachainMessageBridge,
bp_rialto_parachain::Header,
Runtime,
crate::WitRialtoParachainsInstance,
>(ParaId(RIALTO_PARACHAIN_ID), proof, messages_count)
}
}
/// Millau -> RialtoParachain message lane pallet parameters.
#[derive(RuntimeDebug, Clone, Encode, Decode, PartialEq, Eq, TypeInfo)]
pub enum MillauToRialtoParachainMessagesParameter {
/// The conversion formula we use is: `MillauTokens = RialtoParachainTokens * conversion_rate`.
RialtoParachainToMillauConversionRate(FixedU128),
}
impl MessagesParameter for MillauToRialtoParachainMessagesParameter {
fn save(&self) {
match *self {
MillauToRialtoParachainMessagesParameter::RialtoParachainToMillauConversionRate(
ref conversion_rate,
) => RialtoParachainToMillauConversionRate::set(conversion_rate),
}
}
}