Skip to content

Commit

Permalink
fix(system-parachains/bridge-hubs): missing structures used in benchm…
Browse files Browse the repository at this point in the history
…arks
  • Loading branch information
pandres95 committed Oct 23, 2024
1 parent 358e23e commit 9bf828f
Show file tree
Hide file tree
Showing 6 changed files with 315 additions and 179 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,12 @@ use crate::{
AccountId, Balance, Balances, BlockNumber, BridgePolkadotMessages, PolkadotXcm, Runtime,
RuntimeEvent, RuntimeHoldReason, XcmOverBridgeHubPolkadot,
};
use bp_messages::LegacyLaneId;
use bp_messages::{
source_chain::FromBridgedChainMessagesDeliveryProof,
target_chain::FromBridgedChainMessagesProof, LegacyLaneId,
};
use bp_parachains::SingleParaStoredHeaderDataBuilder;
use bp_runtime::{Chain, UnderlyingChainProvider};
use bp_runtime::Chain;
use bridge_hub_common::xcm_version::XcmVersionOfDestAndRemoteBridge;
use frame_support::{parameter_types, traits::PalletInfoAccess};
use frame_system::{EnsureNever, EnsureRoot};
Expand All @@ -36,14 +39,10 @@ use pallet_bridge_relayers::extension::{
use pallet_xcm_bridge_hub::XcmAsPlainPayload;
use parachains_common::xcm_config::{AllSiblingSystemParachains, RelayOrOtherSystemParachains};
use polkadot_parachain_primitives::primitives::Sibling;
use sp_runtime::{traits::ConstU32, RuntimeDebug};
use sp_runtime::traits::ConstU32;
use xcm::latest::prelude::*;
use xcm_builder::{BridgeBlobDispatcher, ParentIsPreset, SiblingParachainConvertsVia};

/// Lane identifier, used to connect Kusama Asset Hub and Polkadot Asset Hub.
pub const XCM_LANE_FOR_ASSET_HUB_KUSAMA_TO_ASSET_HUB_POLKADOT: LegacyLaneId =
LegacyLaneId([0, 0, 0, 1]);

// Parameters that may be changed by the governance.
parameter_types! {
/// Reward that is paid (by the Kusama Asset Hub) to relayers for delivering a single
Expand Down Expand Up @@ -74,10 +73,10 @@ parameter_types! {
/// Interior location (relative to this runtime) of the with-Polkadot messages pallet.
pub BridgeKusamaToPolkadotMessagesPalletInstance: InteriorLocation = PalletInstance(<BridgePolkadotMessages as PalletInfoAccess>::index() as u8).into();

/// Identifier of the sibling Polkadot Asset Hub parachain.
pub AssetHubPolkadotParaId: cumulus_primitives_core::ParaId = polkadot_runtime_constants::system_parachain::ASSET_HUB_ID.into();
/// Identifier of the sibling Kusama Asset Hub parachain.
pub AssetHubKusamaParaId: cumulus_primitives_core::ParaId = kusama_runtime_constants::system_parachain::ASSET_HUB_ID.into();
/// Identifier of the bridged Polkadot Asset Hub parachain.
pub AssetHubPolkadotParaId: cumulus_primitives_core::ParaId = polkadot_runtime_constants::system_parachain::ASSET_HUB_ID.into();
/// Location of the bridged Polkadot Bridge Hub parachain.
pub BridgeHubPolkadotLocation: Location = Location {
parents: 2,
Expand All @@ -86,10 +85,28 @@ parameter_types! {
Parachain(<bp_bridge_hub_polkadot::BridgeHubPolkadot as bp_runtime::Parachain>::PARACHAIN_ID)
].into()
};
}

/// Lane identifier, used to connect Kusama Asset Hub and Polkadot Asset Hub.
pub const AssetHubKusamaToAssetHubPolkadotMessagesLane: LegacyLaneId
= XCM_LANE_FOR_ASSET_HUB_KUSAMA_TO_ASSET_HUB_POLKADOT;
pub type RelayersForLegacyLaneIdsMessagesInstance = ();
/// Allows collect and claim rewards for relayers.
impl pallet_bridge_relayers::Config<RelayersForLegacyLaneIdsMessagesInstance> for Runtime {
type RuntimeEvent = RuntimeEvent;
type Reward = Balance;
type PaymentProcedure = bp_relayers::PayRewardFromAccount<
pallet_balances::Pallet<Runtime>,
AccountId,
Self::LaneId,
>;
type StakeAndSlash = pallet_bridge_relayers::StakeAndSlashNamed<
AccountId,
BlockNumber,
Balances,
RelayerStakeReserveId,
RequiredStakeForStakeAndSlash,
RelayerStakeLease,
>;
type LaneId = LegacyLaneId;
type WeightInfo = weights::pallet_bridge_relayers::WeightInfo<Runtime>;
}

// Parameters, used by bridge transport code.
Expand All @@ -112,16 +129,6 @@ parameter_types! {
/// Name of the `paras` pallet at Polkadot that tracks all parachain heads.
pub const ParachainPalletNameAtPolkadot: &'static str = bp_polkadot::PARAS_PALLET_NAME;

/// Maximal number of entries in the unrewarded relayers vector at the Kusama Bridge Hub. It matches the
/// maximal number of unrewarded relayers that the single confirmation transaction at Polkadot Bridge
/// Hub may process.
pub const MaxUnrewardedRelayerEntriesAtInboundLane: bp_messages::MessageNonce =
bp_bridge_hub_polkadot::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX;
/// Maximal number of unconfirmed messages at the Kusama Bridge Hub. It matches the maximal number of
/// uncinfirmed messages that the single confirmation transaction at Polkadot Bridge Hub may process.
pub const MaxUnconfirmedMessagesAtInboundLane: bp_messages::MessageNonce =
bp_bridge_hub_polkadot::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX;

/// Reserve identifier, used by the `pallet_bridge_relayers` to hold funds of registered relayer.
pub const RelayerStakeReserveId: [u8; 8] = *b"brdgrlrs";
/// Minimal period of relayer registration. Roughly, it is the 1 hour of real time.
Expand All @@ -137,13 +144,34 @@ parameter_types! {
pub storage BridgeDeposit: Balance = constants::currency::UNITS;
}

/// Proof of messages, coming from Polkadot.
pub type FromPolkadotBridgeHubMessagesProof<MI> =
FromBridgedChainMessagesProof<bp_bridge_hub_polkadot::Hash, LaneIdOf<Runtime, MI>>;
/// Messages delivery proof for Polkadot Bridge Hub -> Kusama Bridge Hub messages.
pub type ToPolkadotBridgeHubMessagesDeliveryProof<MI> =
FromBridgedChainMessagesDeliveryProof<bp_bridge_hub_polkadot::Hash, LaneIdOf<Runtime, MI>>;

/// Dispatches received XCM messages from other bridge
pub type FromPolkadotMessageBlobDispatcher = BridgeBlobDispatcher<
XcmRouter,
UniversalLocation,
BridgeKusamaToPolkadotMessagesPalletInstance,
>;

/// Signed extension that refunds relayers that are delivering messages from the Polkadot parachain.
pub type OnBridgeHubPolkadotRefundBridgeHubKusamaMessages = BridgeRelayersSignedExtension<
Runtime,
WithMessagesExtensionConfig<
StrOnBridgeHubPolkadotRefundBridgeHubKusamaMessages,
Runtime,
WithBridgeHubPolkadotMessagesInstance,
RelayersForLegacyLaneIdsMessagesInstance,
PriorityBoostPerMessage,
>,
LaneIdOf<Runtime, WithBridgeHubPolkadotMessagesInstance>,
>;
bp_runtime::generate_static_str_provider!(OnBridgeHubPolkadotRefundBridgeHubKusamaMessages);

/// Add GRANDPA bridge pallet to track Polkadot relay chain.
pub type BridgeGrandpaPolkadotInstance = pallet_bridge_grandpa::Instance1;
impl pallet_bridge_grandpa::Config<BridgeGrandpaPolkadotInstance> for Runtime {
Expand All @@ -168,27 +196,6 @@ impl pallet_bridge_parachains::Config<BridgeParachainPolkadotInstance> for Runti
type MaxParaHeadDataSize = MaxParaHeadDataSize;
}

/// Allows collect and claim rewards for relayers.
impl pallet_bridge_relayers::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Reward = Balance;
type PaymentProcedure = bp_relayers::PayRewardFromAccount<
pallet_balances::Pallet<Runtime>,
AccountId,
Self::LaneId,
>;
type StakeAndSlash = pallet_bridge_relayers::StakeAndSlashNamed<
AccountId,
BlockNumber,
Balances,
RelayerStakeReserveId,
RequiredStakeForStakeAndSlash,
RelayerStakeLease,
>;
type LaneId = LegacyLaneId;
type WeightInfo = weights::pallet_bridge_relayers::WeightInfo<Runtime>;
}

/// Add XCM messages support for exchanging messages with BridgeHubPolkadot.
pub type WithBridgeHubPolkadotMessagesInstance = pallet_bridge_messages::Instance1;
impl pallet_bridge_messages::Config<WithBridgeHubPolkadotMessagesInstance> for Runtime {
Expand Down Expand Up @@ -252,38 +259,52 @@ impl pallet_xcm_bridge_hub::Config<XcmOverBridgeHubPolkadotInstance> for Runtime
type BlobDispatcher = FromPolkadotMessageBlobDispatcher;
}

/// BridgeHubPolkadot chain from message lane point of view.
#[derive(RuntimeDebug, Clone, Copy)]
pub struct BridgeHubPolkadot;

impl UnderlyingChainProvider for BridgeHubPolkadot {
type Chain = bp_bridge_hub_polkadot::BridgeHubPolkadot;
}

/// BridgeHubKusama chain from message lane point of view.
#[derive(RuntimeDebug, Clone, Copy)]
pub struct BridgeHubKusama;
#[cfg(feature = "runtime-benchmarks")]
pub(crate) fn open_bridge_for_benchmarks<R, XBHI, C>(
with: pallet_xcm_bridge_hub::LaneIdOf<R, XBHI>,
sibling_para_id: u32,
) -> InteriorLocation
where
R: pallet_xcm_bridge_hub::Config<XBHI>,
XBHI: 'static,
C: xcm_executor::traits::ConvertLocation<
bp_runtime::AccountIdOf<pallet_xcm_bridge_hub::ThisChainOf<R, XBHI>>,
>,
{
use pallet_xcm_bridge_hub::{Bridge, BridgeId, BridgeState};
use sp_runtime::traits::Zero;
use sp_std::boxed::Box;
use xcm::VersionedInteriorLocation;

// insert bridge metadata
let lane_id = with;
let sibling_parachain = Location::new(1, [Parachain(sibling_para_id)]);
let universal_source = [GlobalConsensus(Westend), Parachain(sibling_para_id)].into();
let universal_destination = [GlobalConsensus(Rococo), Parachain(2075)].into();
let bridge_id = BridgeId::new(&universal_source, &universal_destination);

// insert only bridge metadata, because the benchmarks create lanes
pallet_xcm_bridge_hub::Bridges::<R, XBHI>::insert(
bridge_id,
Bridge {
bridge_origin_relative_location: Box::new(sibling_parachain.clone().into()),
bridge_origin_universal_location: Box::new(VersionedInteriorLocation::from(
universal_source.clone(),
)),
bridge_destination_universal_location: Box::new(VersionedInteriorLocation::from(
universal_destination,
)),
state: BridgeState::Opened,
bridge_owner_account: C::convert_location(&sibling_parachain).expect("valid AccountId"),
deposit: Zero::zero(),
lane_id,
},
);
pallet_xcm_bridge_hub::LaneToBridge::<R, XBHI>::insert(lane_id, bridge_id);

impl UnderlyingChainProvider for BridgeHubKusama {
type Chain = bp_bridge_hub_kusama::BridgeHubKusama;
universal_source
}

pub type RelayersForLegacyLaneIdsMessagesInstance = ();

/// Signed extension that refunds relayers that are delivering messages from the Polkadot parachain.
pub type OnBridgeHubPolkadotRefundBridgeHubKusamaMessages = BridgeRelayersSignedExtension<
Runtime,
WithMessagesExtensionConfig<
StrOnBridgeHubPolkadotRefundBridgeHubKusamaMessages,
Runtime,
WithBridgeHubPolkadotMessagesInstance,
RelayersForLegacyLaneIdsMessagesInstance,
PriorityBoostPerMessage,
>,
LaneIdOf<Runtime, WithBridgeHubPolkadotMessagesInstance>,
>;
bp_runtime::generate_static_str_provider!(OnBridgeHubPolkadotRefundBridgeHubKusamaMessages);

#[cfg(test)]
mod tests {
use super::*;
Expand Down
73 changes: 59 additions & 14 deletions system-parachains/bridge-hubs/bridge-hub-kusama/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,14 @@ pub mod genesis_config_presets;
mod weights;
pub mod xcm_config;

use bp_messages::LegacyLaneId;
use bridge_hub_common::message_queue::{
AggregateMessageOrigin, NarrowOriginToSibling, ParaIdToSibling,
};
use cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases;
use cumulus_primitives_core::ParaId;

use pallet_bridge_messages::LaneIdOf;
use sp_api::impl_runtime_apis;
use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
use sp_runtime::{
Expand Down Expand Up @@ -1105,11 +1107,48 @@ impl_runtime_apis! {
);
BenchmarkError::Stop("XcmVersion was not stored!")
})?;

let sibling_parachain_id = Parachain(8765);
let remote_parachain_id = Parachain(5678);
let sibling_parachain_location = Location::new(1, [sibling_parachain_id]);

// fund SA
use frame_support::traits::fungible::Mutate;
use xcm_executor::traits::ConvertLocation;
frame_support::assert_ok!(
Balances::mint_into(
&xcm_config::LocationToAccountId::convert_location(&sibling_parachain_location).expect("valid AccountId"),
bridge_to_polkadot_config::BridgeDeposit::get()
.saturating_add(ExistentialDeposit::get())
.saturating_add(UNITS * 5)
)
);

// open bridge
let bridge_destination_universal_location: InteriorLocation = [GlobalConsensus(NetworkId::Polkadot), remote_parachain_id].into();
let locations = XcmOverBridgeHubPolkadot::bridge_locations(
sibling_parachain_location.clone(),
bridge_destination_universal_location.clone(),
)?;
XcmOverBridgeHubPolkadot::do_open_bridge(
locations,
bp_messages::LegacyLaneId([1, 2, 3, 4]),
true,
).map_err(|e| {
log::error!(
"Failed to `XcmOverBridgeHubRococo::open_bridge`({:?}, {:?})`, error: {:?}",
sibling_parachain_location,
bridge_destination_universal_location,
e
);
BenchmarkError::Stop("Bridge was not opened!")
})?;

Ok(
(
bridge_to_polkadot_config::FromAssetHubKusamaToAssetHubPolkadotRoute::get().location,
sibling_parachain_location,
NetworkId::Polkadot,
Parachain(bridge_to_polkadot_config::AssetHubPolkadotParaId::get().into()).into()
[remote_parachain_id].into()
)
)
}
Expand All @@ -1133,12 +1172,13 @@ impl_runtime_apis! {

impl BridgeRelayersConfig for Runtime {
fn prepare_rewards_account(
account_params: bp_relayers::RewardsAccountParams,
account_params: bp_relayers::RewardsAccountParams<LaneIdOf<Runtime, bridge_to_polkadot_config::WithBridgeHubPolkadotMessagesInstance>>,
reward: Balance,
) {
let rewards_account = bp_relayers::PayRewardFromAccount::<
Balances,
AccountId
AccountId,
LegacyLaneId,
>::rewards_account(account_params);
Self::deposit_account(rewards_account, reward);
}
Expand All @@ -1161,17 +1201,17 @@ impl_runtime_apis! {
fn prepare_parachain_heads_proof(
parachains: &[bp_polkadot_core::parachains::ParaId],
parachain_head_size: u32,
proof_size: bp_runtime::StorageProofSize,
proof_params: bp_runtime::UnverifiedStorageProofParams,
) -> (
pallet_bridge_parachains::RelayBlockNumber,
pallet_bridge_parachains::RelayBlockHash,
bp_parachains::RelayBlockNumber,
bp_parachains::RelayBlockHash,
bp_polkadot_core::parachains::ParaHeadsProof,
Vec<(bp_polkadot_core::parachains::ParaId, bp_polkadot_core::parachains::ParaHash)>,
) {
prepare_parachain_heads_proof::<Runtime, bridge_to_polkadot_config::BridgeParachainPolkadotInstance>(
parachains,
parachain_head_size,
proof_size,
proof_params,
)
}
}
Expand Down Expand Up @@ -1202,25 +1242,30 @@ impl_runtime_apis! {
}

fn prepare_message_proof(
params: MessageProofParams,
) -> (bridge_to_polkadot_config::FromPolkadotBridgeHubMessagesProof, Weight) {
params: MessageProofParams<LaneIdOf<Runtime, bridge_to_polkadot_config::WithBridgeHubPolkadotMessagesInstance>>,
) -> (bridge_to_polkadot_config::FromPolkadotBridgeHubMessagesProof<bridge_to_polkadot_config::WithBridgeHubPolkadotMessagesInstance>, Weight) {
use cumulus_primitives_core::XcmpMessageSource;
assert!(XcmpQueue::take_outbound_messages(usize::MAX).is_empty());
ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(42.into());
prepare_message_proof_from_parachain::<
Runtime,
bridge_to_polkadot_config::BridgeGrandpaPolkadotInstance,
bridge_to_polkadot_config::WithBridgeHubPolkadotMessageBridge,
bridge_to_polkadot_config::WithBridgeHubPolkadotMessagesInstance,
>(params, generate_xcm_builder_bridge_message_sample([GlobalConsensus(Kusama), Parachain(42)].into()))
}

fn prepare_message_delivery_proof(
params: MessageDeliveryProofParams<AccountId>,
) -> bridge_to_polkadot_config::ToPolkadotBridgeHubMessagesDeliveryProof {
params: MessageDeliveryProofParams<AccountId, LaneIdOf<Runtime, bridge_to_polkadot_config::WithBridgeHubPolkadotMessagesInstance>>,
) -> bridge_to_polkadot_config::ToPolkadotBridgeHubMessagesDeliveryProof<bridge_to_polkadot_config::WithBridgeHubPolkadotMessagesInstance> {
let _ = bridge_to_polkadot_config::open_bridge_for_benchmarks::<
Runtime,
bridge_to_polkadot_config::XcmOverBridgeHubPolkadotInstance,
xcm_config::LocationToAccountId,
>(params.lane, 42);
prepare_message_delivery_proof_from_parachain::<
Runtime,
bridge_to_polkadot_config::BridgeGrandpaPolkadotInstance,
bridge_to_polkadot_config::WithBridgeHubPolkadotMessageBridge,
bridge_to_polkadot_config::WithBridgeHubPolkadotMessagesInstance,
>(params)
}

Expand Down
Loading

0 comments on commit 9bf828f

Please sign in to comment.