fix: Complete snowbridge pezpallet rebrand and critical bug fixes
- snowbridge-pezpallet-* → pezsnowbridge-pezpallet-* (201 refs) - pallet/ directories → pezpallet/ (4 locations) - Fixed pezpallet.rs self-include recursion bug - Fixed sc-chain-spec hardcoded crate name in derive macro - Reverted .pezpallet_by_name() to .pallet_by_name() (subxt API) - Added BizinikiwiConfig type alias for zombienet tests - Deleted obsolete session state files Verified: pezsnowbridge-pezpallet-*, pezpallet-staking, pezpallet-staking-async, pezframe-benchmarking-cli all pass cargo check
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
[package]
|
||||
name = "bp-relayers"
|
||||
description = "Primitives of relayers module."
|
||||
version = "0.7.0"
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
repository.workspace = true
|
||||
documentation = "https://docs.rs/bp-relayers"
|
||||
homepage = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
codec = { features = ["bit-vec", "derive"], workspace = true }
|
||||
scale-info = { features = ["bit-vec", "derive"], workspace = true }
|
||||
|
||||
# Bridge Dependencies
|
||||
bp-header-pez-chain = { workspace = true }
|
||||
bp-messages = { workspace = true }
|
||||
pezbp-runtime = { workspace = true }
|
||||
bp-teyrchains = { workspace = true }
|
||||
|
||||
# Bizinikiwi Dependencies
|
||||
pezframe-support = { workspace = true }
|
||||
pezframe-system = { workspace = true }
|
||||
pezpallet-utility = { workspace = true }
|
||||
pezsp-runtime = { workspace = true }
|
||||
pezsp-std = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
hex-literal = { workspace = true, default-features = true }
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"bp-header-pez-chain/std",
|
||||
"bp-messages/std",
|
||||
"pezbp-runtime/std",
|
||||
"bp-teyrchains/std",
|
||||
"codec/std",
|
||||
"pezframe-support/std",
|
||||
"pezframe-system/std",
|
||||
"pezpallet-utility/std",
|
||||
"scale-info/std",
|
||||
"pezsp-runtime/std",
|
||||
"pezsp-std/std",
|
||||
]
|
||||
runtime-benchmarks = [
|
||||
"bp-header-pez-chain/runtime-benchmarks",
|
||||
"bp-messages/runtime-benchmarks",
|
||||
"pezbp-runtime/runtime-benchmarks",
|
||||
"bp-teyrchains/runtime-benchmarks",
|
||||
"pezframe-support/runtime-benchmarks",
|
||||
"pezframe-system/runtime-benchmarks",
|
||||
"pezpallet-utility/runtime-benchmarks",
|
||||
"pezsp-runtime/runtime-benchmarks",
|
||||
]
|
||||
@@ -0,0 +1,197 @@
|
||||
// Copyright (C) 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/>.
|
||||
|
||||
//! All runtime calls, supported by `pezpallet-bridge-relayers` when it acts as a signed
|
||||
//! extension.
|
||||
|
||||
use bp_header_pez_chain::SubmitFinalityProofInfo;
|
||||
use bp_messages::MessagesCallInfo;
|
||||
use pezbp_runtime::StaticStrProvider;
|
||||
use bp_teyrchains::SubmitTeyrchainHeadsInfo;
|
||||
use codec::{Decode, Encode};
|
||||
use pezframe_support::{
|
||||
dispatch::CallableCallFor, traits::IsSubType, weights::Weight, RuntimeDebugNoBound,
|
||||
};
|
||||
use pezframe_system::Config as SystemConfig;
|
||||
use pezpallet_utility::{Call as UtilityCall, Pezpallet as UtilityPallet};
|
||||
use pezsp_runtime::{
|
||||
traits::Get,
|
||||
transaction_validity::{TransactionPriority, TransactionValidityError},
|
||||
RuntimeDebug,
|
||||
};
|
||||
use pezsp_std::{fmt::Debug, marker::PhantomData, vec, vec::Vec};
|
||||
|
||||
/// Type of the call that the signed extension recognizes.
|
||||
#[derive(PartialEq, RuntimeDebugNoBound)]
|
||||
pub enum ExtensionCallInfo<RemoteGrandpaChainBlockNumber: Debug, LaneId: Clone + Copy + Debug> {
|
||||
/// Relay chain finality + teyrchain finality + message delivery/confirmation calls.
|
||||
AllFinalityAndMsgs(
|
||||
SubmitFinalityProofInfo<RemoteGrandpaChainBlockNumber>,
|
||||
SubmitTeyrchainHeadsInfo,
|
||||
MessagesCallInfo<LaneId>,
|
||||
),
|
||||
/// Relay chain finality + message delivery/confirmation calls.
|
||||
RelayFinalityAndMsgs(
|
||||
SubmitFinalityProofInfo<RemoteGrandpaChainBlockNumber>,
|
||||
MessagesCallInfo<LaneId>,
|
||||
),
|
||||
/// Teyrchain finality + message delivery/confirmation calls.
|
||||
///
|
||||
/// This variant is used only when bridging with teyrchain.
|
||||
TeyrchainFinalityAndMsgs(SubmitTeyrchainHeadsInfo, MessagesCallInfo<LaneId>),
|
||||
/// Standalone message delivery/confirmation call.
|
||||
Msgs(MessagesCallInfo<LaneId>),
|
||||
}
|
||||
|
||||
impl<RemoteGrandpaChainBlockNumber: Clone + Copy + Debug, LaneId: Clone + Copy + Debug>
|
||||
ExtensionCallInfo<RemoteGrandpaChainBlockNumber, LaneId>
|
||||
{
|
||||
/// Returns true if call is a message delivery call (with optional finality calls).
|
||||
pub fn is_receive_messages_proof_call(&self) -> bool {
|
||||
match self.messages_call_info() {
|
||||
MessagesCallInfo::ReceiveMessagesProof(_) => true,
|
||||
MessagesCallInfo::ReceiveMessagesDeliveryProof(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the pre-dispatch `finality_target` sent to the `SubmitFinalityProof` call.
|
||||
pub fn submit_finality_proof_info(
|
||||
&self,
|
||||
) -> Option<SubmitFinalityProofInfo<RemoteGrandpaChainBlockNumber>> {
|
||||
match *self {
|
||||
Self::AllFinalityAndMsgs(info, _, _) => Some(info),
|
||||
Self::RelayFinalityAndMsgs(info, _) => Some(info),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the pre-dispatch `SubmitTeyrchainHeadsInfo`.
|
||||
pub fn submit_teyrchain_heads_info(&self) -> Option<&SubmitTeyrchainHeadsInfo> {
|
||||
match self {
|
||||
Self::AllFinalityAndMsgs(_, info, _) => Some(info),
|
||||
Self::TeyrchainFinalityAndMsgs(info, _) => Some(info),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the pre-dispatch `ReceiveMessagesProofInfo`.
|
||||
pub fn messages_call_info(&self) -> &MessagesCallInfo<LaneId> {
|
||||
match self {
|
||||
Self::AllFinalityAndMsgs(_, _, info) => info,
|
||||
Self::RelayFinalityAndMsgs(_, info) => info,
|
||||
Self::TeyrchainFinalityAndMsgs(_, info) => info,
|
||||
Self::Msgs(info) => info,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Extra post-dispatch data, associated with the supported runtime call.
|
||||
#[derive(Default, RuntimeDebug)]
|
||||
pub struct ExtensionCallData {
|
||||
/// Extra weight, consumed by the call. We have some assumptions about normal weight
|
||||
/// that may be consumed by expected calls. If the actual weight is larger than that,
|
||||
/// we do not refund relayer for this extra weight.
|
||||
pub extra_weight: Weight,
|
||||
/// Extra size, consumed by the call. We have some assumptions about normal size
|
||||
/// of the encoded call. If the actual size is larger than that, we do not refund relayer
|
||||
/// for this extra size.
|
||||
pub extra_size: u32,
|
||||
}
|
||||
|
||||
/// Signed extension configuration.
|
||||
///
|
||||
/// The single `pezpallet-bridge-relayers` instance may be shared by multiple messages
|
||||
/// pezpallet instances, bridging with different remote networks. We expect every instance
|
||||
/// of the messages pezpallet to add a separate signed extension to runtime. So it must
|
||||
/// have a separate configuration.
|
||||
pub trait ExtensionConfig {
|
||||
/// Unique identifier of the signed extension that will use this configuration.
|
||||
type IdProvider: StaticStrProvider;
|
||||
/// Runtime that optionally supports batched calls. We assume that batched call
|
||||
/// succeeds if and only if all of its nested calls succeed.
|
||||
type Runtime: pezframe_system::Config;
|
||||
/// Relayers pezpallet instance.
|
||||
type BridgeRelayersPalletInstance: 'static;
|
||||
/// Messages pezpallet instance.
|
||||
type BridgeMessagesPalletInstance: 'static;
|
||||
/// Additional priority that is added to base message delivery transaction priority
|
||||
/// for every additional bundled message.
|
||||
type PriorityBoostPerMessage: Get<TransactionPriority>;
|
||||
/// Block number for the remote **GRANDPA chain**. Mind that this chain is not
|
||||
/// necessarily the chain that we are bridging with. If we are bridging with
|
||||
/// teyrchain, it must be its parent relay chain. If we are bridging with the
|
||||
/// GRANDPA chain, it must be it.
|
||||
type RemoteGrandpaChainBlockNumber: Clone + Copy + Debug;
|
||||
/// Lane identifier type.
|
||||
type LaneId: Clone + Copy + Decode + Encode + Debug;
|
||||
|
||||
/// Given runtime call, check if it is supported by the transaction extension. Additionally,
|
||||
/// check if call (or any of batched calls) are obsolete.
|
||||
fn parse_and_check_for_obsolete_call(
|
||||
call: &<Self::Runtime as SystemConfig>::RuntimeCall,
|
||||
) -> Result<
|
||||
Option<ExtensionCallInfo<Self::RemoteGrandpaChainBlockNumber, Self::LaneId>>,
|
||||
TransactionValidityError,
|
||||
>;
|
||||
|
||||
/// Check if runtime call is already obsolete.
|
||||
fn check_obsolete_parsed_call(
|
||||
call: &<Self::Runtime as SystemConfig>::RuntimeCall,
|
||||
) -> Result<&<Self::Runtime as SystemConfig>::RuntimeCall, TransactionValidityError>;
|
||||
|
||||
/// Given runtime call info, check that this call has been successful and has updated
|
||||
/// runtime storage accordingly.
|
||||
fn check_call_result(
|
||||
call_info: &ExtensionCallInfo<Self::RemoteGrandpaChainBlockNumber, Self::LaneId>,
|
||||
call_data: &mut ExtensionCallData,
|
||||
relayer: &<Self::Runtime as SystemConfig>::AccountId,
|
||||
) -> bool;
|
||||
}
|
||||
|
||||
/// Something that can unpack batch calls (all-or-nothing flavor) of given size.
|
||||
pub trait BatchCallUnpacker<Runtime: pezframe_system::Config> {
|
||||
/// Unpack batch call with no more than `max_packed_calls` calls.
|
||||
fn unpack(call: &Runtime::RuntimeCall, max_packed_calls: u32) -> Vec<&Runtime::RuntimeCall>;
|
||||
}
|
||||
|
||||
/// An `BatchCallUnpacker` adapter for runtimes with utility pezpallet.
|
||||
pub struct RuntimeWithUtilityPallet<Runtime>(PhantomData<Runtime>);
|
||||
|
||||
impl<Runtime> BatchCallUnpacker<Runtime> for RuntimeWithUtilityPallet<Runtime>
|
||||
where
|
||||
Runtime: pezpallet_utility::Config<RuntimeCall = <Runtime as SystemConfig>::RuntimeCall>,
|
||||
<Runtime as SystemConfig>::RuntimeCall:
|
||||
IsSubType<CallableCallFor<UtilityPallet<Runtime>, Runtime>>,
|
||||
{
|
||||
fn unpack(
|
||||
call: &<Runtime as pezframe_system::Config>::RuntimeCall,
|
||||
max_packed_calls: u32,
|
||||
) -> Vec<&<Runtime as pezframe_system::Config>::RuntimeCall> {
|
||||
match call.is_sub_type() {
|
||||
Some(UtilityCall::<Runtime>::batch_all { ref calls })
|
||||
if calls.len() <= max_packed_calls as usize =>
|
||||
calls.iter().collect(),
|
||||
Some(_) => vec![],
|
||||
None => vec![call],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Runtime: pezframe_system::Config> BatchCallUnpacker<Runtime> for () {
|
||||
fn unpack(call: &Runtime::RuntimeCall, _max_packed_calls: u32) -> Vec<&Runtime::RuntimeCall> {
|
||||
vec![call]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
// Copyright (C) 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/>.
|
||||
|
||||
//! Primitives of messages module.
|
||||
|
||||
#![warn(missing_docs)]
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
pub use extension::{
|
||||
BatchCallUnpacker, ExtensionCallData, ExtensionCallInfo, ExtensionConfig,
|
||||
RuntimeWithUtilityPallet,
|
||||
};
|
||||
pub use registration::{ExplicitOrAccountParams, Registration, StakeAndSlash};
|
||||
|
||||
use pezbp_runtime::{ChainId, StorageDoubleMapKeyProvider};
|
||||
use pezframe_support::{traits::tokens::Preservation, Blake2_128Concat, Identity};
|
||||
use scale_info::TypeInfo;
|
||||
use pezsp_runtime::{
|
||||
codec::{Codec, Decode, DecodeWithMemTracking, Encode, EncodeLike, MaxEncodedLen},
|
||||
traits::AccountIdConversion,
|
||||
TypeId,
|
||||
};
|
||||
use pezsp_std::{fmt::Debug, marker::PhantomData};
|
||||
|
||||
mod extension;
|
||||
mod registration;
|
||||
|
||||
/// The owner of the sovereign account that should pay the rewards.
|
||||
///
|
||||
/// Each of the 2 final points connected by a bridge owns a sovereign account at each end of the
|
||||
/// bridge. So here, at this end of the bridge there can be 2 sovereign accounts that pay rewards.
|
||||
#[derive(
|
||||
Copy,
|
||||
Clone,
|
||||
Debug,
|
||||
Decode,
|
||||
DecodeWithMemTracking,
|
||||
Encode,
|
||||
Eq,
|
||||
PartialEq,
|
||||
TypeInfo,
|
||||
MaxEncodedLen,
|
||||
)]
|
||||
pub enum RewardsAccountOwner {
|
||||
/// The sovereign account of the final chain on this end of the bridge.
|
||||
ThisChain,
|
||||
/// The sovereign account of the final chain on the other end of the bridge.
|
||||
BridgedChain,
|
||||
}
|
||||
|
||||
/// Structure used to identify the account that pays a reward to the relayer.
|
||||
///
|
||||
/// A bridge connects 2 bridge ends. Each one is located on a separate relay chain. The bridge ends
|
||||
/// can be the final destinations of the bridge, or they can be intermediary points
|
||||
/// (e.g. a bridge hub) used to forward messages between pairs of teyrchains on the bridged relay
|
||||
/// chains. A pair of such teyrchains is connected using a bridge lane. Each of the 2 final
|
||||
/// destinations of a bridge lane must have a sovereign account at each end of the bridge and each
|
||||
/// of the sovereign accounts will pay rewards for different operations. So we need multiple
|
||||
/// parameters to identify the account that pays a reward to the relayer.
|
||||
#[derive(
|
||||
Copy,
|
||||
Clone,
|
||||
Debug,
|
||||
Decode,
|
||||
DecodeWithMemTracking,
|
||||
Encode,
|
||||
Eq,
|
||||
PartialEq,
|
||||
TypeInfo,
|
||||
MaxEncodedLen,
|
||||
)]
|
||||
pub struct RewardsAccountParams<LaneId> {
|
||||
// **IMPORTANT NOTE**: the order of fields here matters - we are using
|
||||
// `into_account_truncating` and lane id is already `32` byte, so if other fields are encoded
|
||||
// after it, they're simply dropped. So lane id shall be the last field.
|
||||
owner: RewardsAccountOwner,
|
||||
bridged_chain_id: ChainId,
|
||||
lane_id: LaneId,
|
||||
}
|
||||
|
||||
impl<LaneId: Decode + Encode> RewardsAccountParams<LaneId> {
|
||||
/// Create a new instance of `RewardsAccountParams`.
|
||||
pub const fn new(
|
||||
lane_id: LaneId,
|
||||
bridged_chain_id: ChainId,
|
||||
owner: RewardsAccountOwner,
|
||||
) -> Self {
|
||||
Self { lane_id, bridged_chain_id, owner }
|
||||
}
|
||||
|
||||
/// Getter for `lane_id`.
|
||||
pub const fn lane_id(&self) -> &LaneId {
|
||||
&self.lane_id
|
||||
}
|
||||
}
|
||||
|
||||
impl<LaneId: Decode + Encode> TypeId for RewardsAccountParams<LaneId> {
|
||||
const TYPE_ID: [u8; 4] = *b"brap";
|
||||
}
|
||||
|
||||
/// Reward payment procedure.
|
||||
pub trait PaymentProcedure<Relayer, Reward, RewardBalance> {
|
||||
/// Error that may be returned by the procedure.
|
||||
type Error: Debug;
|
||||
|
||||
/// Type parameter used to identify the beneficiaries eligible to receive rewards.
|
||||
type Beneficiary: Clone + Debug + Decode + Encode + Eq + TypeInfo;
|
||||
|
||||
/// Pay reward to the relayer (or alternative beneficiary if provided) from the account with
|
||||
/// provided params.
|
||||
fn pay_reward(
|
||||
relayer: &Relayer,
|
||||
reward: Reward,
|
||||
reward_balance: RewardBalance,
|
||||
beneficiary: Self::Beneficiary,
|
||||
) -> Result<(), Self::Error>;
|
||||
}
|
||||
|
||||
impl<Relayer, Reward, RewardBalance> PaymentProcedure<Relayer, Reward, RewardBalance> for () {
|
||||
type Error = &'static str;
|
||||
type Beneficiary = ();
|
||||
|
||||
fn pay_reward(
|
||||
_: &Relayer,
|
||||
_: Reward,
|
||||
_: RewardBalance,
|
||||
_: Self::Beneficiary,
|
||||
) -> Result<(), Self::Error> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Reward payment procedure that executes a `balances::transfer` call from the account
|
||||
/// derived from the given `RewardsAccountParams` to the relayer or an alternative beneficiary.
|
||||
pub struct PayRewardFromAccount<T, Relayer, LaneId, RewardBalance>(
|
||||
PhantomData<(T, Relayer, LaneId, RewardBalance)>,
|
||||
);
|
||||
|
||||
impl<T, Relayer, LaneId, RewardBalance> PayRewardFromAccount<T, Relayer, LaneId, RewardBalance>
|
||||
where
|
||||
Relayer: Decode + Encode,
|
||||
LaneId: Decode + Encode,
|
||||
{
|
||||
/// Return account that pays rewards based on the provided parameters.
|
||||
pub fn rewards_account(params: RewardsAccountParams<LaneId>) -> Relayer {
|
||||
params.into_sub_account_truncating(b"rewards-account")
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Relayer, LaneId, RewardBalance>
|
||||
PaymentProcedure<Relayer, RewardsAccountParams<LaneId>, RewardBalance>
|
||||
for PayRewardFromAccount<T, Relayer, LaneId, RewardBalance>
|
||||
where
|
||||
T: pezframe_support::traits::fungible::Mutate<Relayer>,
|
||||
T::Balance: From<RewardBalance>,
|
||||
Relayer: Clone + Debug + Decode + Encode + Eq + TypeInfo,
|
||||
LaneId: Decode + Encode,
|
||||
{
|
||||
type Error = pezsp_runtime::DispatchError;
|
||||
type Beneficiary = Relayer;
|
||||
|
||||
fn pay_reward(
|
||||
_: &Relayer,
|
||||
reward_kind: RewardsAccountParams<LaneId>,
|
||||
reward: RewardBalance,
|
||||
beneficiary: Self::Beneficiary,
|
||||
) -> Result<(), Self::Error> {
|
||||
T::transfer(
|
||||
&Self::rewards_account(reward_kind),
|
||||
&beneficiary.into(),
|
||||
reward.into(),
|
||||
Preservation::Expendable,
|
||||
)
|
||||
.map(drop)
|
||||
}
|
||||
}
|
||||
|
||||
/// Can be used to access the runtime storage key within the `RelayerRewards` map of the relayers
|
||||
/// pezpallet.
|
||||
pub struct RelayerRewardsKeyProvider<AccountId, Reward, RewardBalance>(
|
||||
PhantomData<(AccountId, Reward, RewardBalance)>,
|
||||
);
|
||||
|
||||
impl<AccountId, Reward, RewardBalance> StorageDoubleMapKeyProvider
|
||||
for RelayerRewardsKeyProvider<AccountId, Reward, RewardBalance>
|
||||
where
|
||||
AccountId: 'static + Codec + EncodeLike + Send + Sync,
|
||||
Reward: Codec + EncodeLike + Send + Sync,
|
||||
RewardBalance: 'static + Codec + EncodeLike + Send + Sync,
|
||||
{
|
||||
const MAP_NAME: &'static str = "RelayerRewards";
|
||||
|
||||
type Hasher1 = Blake2_128Concat;
|
||||
type Key1 = AccountId;
|
||||
type Hasher2 = Identity;
|
||||
type Key2 = Reward;
|
||||
type Value = RewardBalance;
|
||||
}
|
||||
|
||||
/// A trait defining a reward ledger, which tracks rewards that can be later claimed.
|
||||
///
|
||||
/// This ledger allows registering rewards for a relayer, categorized by a specific `Reward`.
|
||||
/// The registered rewards can be claimed later through an appropriate payment procedure.
|
||||
pub trait RewardLedger<Relayer, Reward, RewardBalance> {
|
||||
/// Registers a reward for a given relayer.
|
||||
fn register_reward(relayer: &Relayer, reward: Reward, reward_balance: RewardBalance);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use bp_messages::{HashedLaneId, LaneIdType, LegacyLaneId};
|
||||
use pezsp_runtime::{app_crypto::Ss58Codec, testing::H256};
|
||||
|
||||
#[test]
|
||||
fn different_lanes_are_using_different_accounts() {
|
||||
assert_eq!(
|
||||
PayRewardFromAccount::<(), H256, HashedLaneId, ()>::rewards_account(
|
||||
RewardsAccountParams::new(
|
||||
HashedLaneId::try_new(1, 2).unwrap(),
|
||||
*b"test",
|
||||
RewardsAccountOwner::ThisChain
|
||||
)
|
||||
),
|
||||
hex_literal::hex!("627261700074657374b1d3dccd8b3c3a012afe265f3e3c4432129b8aee50c9dc")
|
||||
.into(),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
PayRewardFromAccount::<(), H256, HashedLaneId, ()>::rewards_account(
|
||||
RewardsAccountParams::new(
|
||||
HashedLaneId::try_new(1, 3).unwrap(),
|
||||
*b"test",
|
||||
RewardsAccountOwner::ThisChain
|
||||
)
|
||||
),
|
||||
hex_literal::hex!("627261700074657374a43e8951aa302c133beb5f85821a21645f07b487270ef3")
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn different_directions_are_using_different_accounts() {
|
||||
assert_eq!(
|
||||
PayRewardFromAccount::<(), H256, HashedLaneId, ()>::rewards_account(
|
||||
RewardsAccountParams::new(
|
||||
HashedLaneId::try_new(1, 2).unwrap(),
|
||||
*b"test",
|
||||
RewardsAccountOwner::ThisChain
|
||||
)
|
||||
),
|
||||
hex_literal::hex!("627261700074657374b1d3dccd8b3c3a012afe265f3e3c4432129b8aee50c9dc")
|
||||
.into(),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
PayRewardFromAccount::<(), H256, HashedLaneId, ()>::rewards_account(
|
||||
RewardsAccountParams::new(
|
||||
HashedLaneId::try_new(1, 2).unwrap(),
|
||||
*b"test",
|
||||
RewardsAccountOwner::BridgedChain
|
||||
)
|
||||
),
|
||||
hex_literal::hex!("627261700174657374b1d3dccd8b3c3a012afe265f3e3c4432129b8aee50c9dc")
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pay_reward_from_account_for_legacy_lane_id_works() {
|
||||
let test_data = vec![
|
||||
// Note: these accounts are used for integration tests within
|
||||
// `bridges_pezkuwichain_zagros.sh`
|
||||
(
|
||||
LegacyLaneId([0, 0, 0, 1]),
|
||||
b"bhks",
|
||||
RewardsAccountOwner::ThisChain,
|
||||
(0_u16, "13E5fui97x6KTwNnSjaEKZ8s7kJNot5F3aUsy3jUtuoMyUec"),
|
||||
),
|
||||
(
|
||||
LegacyLaneId([0, 0, 0, 1]),
|
||||
b"bhks",
|
||||
RewardsAccountOwner::BridgedChain,
|
||||
(0_u16, "13E5fui9Ka9Vz4JbGN3xWjmwDNxnxF1N9Hhhbeu3VCqLChuj"),
|
||||
),
|
||||
(
|
||||
LegacyLaneId([0, 0, 0, 1]),
|
||||
b"bhpd",
|
||||
RewardsAccountOwner::ThisChain,
|
||||
(2_u16, "EoQBtnwtXqnSnr9cgBEJpKU7NjeC9EnR4D1VjgcvHz9ZYmS"),
|
||||
),
|
||||
(
|
||||
LegacyLaneId([0, 0, 0, 1]),
|
||||
b"bhpd",
|
||||
RewardsAccountOwner::BridgedChain,
|
||||
(2_u16, "EoQBtnx69txxumxSJexVzxYD1Q4LWAuWmRq8LrBWb27nhYN"),
|
||||
),
|
||||
// Note: these accounts are used for integration tests within
|
||||
// `bridges_pezkuwi_kusama.sh` from fellows.
|
||||
(
|
||||
LegacyLaneId([0, 0, 0, 2]),
|
||||
b"bhwd",
|
||||
RewardsAccountOwner::ThisChain,
|
||||
(4_u16, "SNihsskf7bFhnHH9HJFMjWD3FJ96ESdAQTFZUAtXudRQbaH"),
|
||||
),
|
||||
(
|
||||
LegacyLaneId([0, 0, 0, 2]),
|
||||
b"bhwd",
|
||||
RewardsAccountOwner::BridgedChain,
|
||||
(4_u16, "SNihsskrjeSDuD5xumyYv9H8sxZEbNkG7g5C5LT8CfPdaSE"),
|
||||
),
|
||||
(
|
||||
LegacyLaneId([0, 0, 0, 2]),
|
||||
b"bhro",
|
||||
RewardsAccountOwner::ThisChain,
|
||||
(4_u16, "SNihsskf7bF2vWogkC6uFoiqPhd3dUX6TGzYZ1ocJdo3xHp"),
|
||||
),
|
||||
(
|
||||
LegacyLaneId([0, 0, 0, 2]),
|
||||
b"bhro",
|
||||
RewardsAccountOwner::BridgedChain,
|
||||
(4_u16, "SNihsskrjeRZ3ScWNfq6SSnw2N3BzQeCAVpBABNCbfmHENB"),
|
||||
),
|
||||
];
|
||||
|
||||
for (lane_id, bridged_chain_id, owner, (expected_ss58, expected_account)) in test_data {
|
||||
assert_eq!(
|
||||
expected_account,
|
||||
pezsp_runtime::AccountId32::new(PayRewardFromAccount::<
|
||||
[u8; 32],
|
||||
[u8; 32],
|
||||
LegacyLaneId,
|
||||
(),
|
||||
>::rewards_account(RewardsAccountParams::new(
|
||||
lane_id,
|
||||
*bridged_chain_id,
|
||||
owner
|
||||
)))
|
||||
.to_ss58check_with_version(expected_ss58.into())
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
// Copyright (C) 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/>.
|
||||
|
||||
//! Bridge relayers registration and slashing scheme.
|
||||
//!
|
||||
//! There is an option to add a refund-relayer signed extension that will compensate
|
||||
//! relayer costs of the message delivery and confirmation transactions (as well as
|
||||
//! required finality proofs). This extension boosts priority of message delivery
|
||||
//! transactions, based on the number of bundled messages. So transaction with more
|
||||
//! messages has larger priority than the transaction with less messages.
|
||||
//! See `pezbridge_runtime_common::extensions::priority_calculator` for details;
|
||||
//!
|
||||
//! This encourages relayers to include more messages to their delivery transactions.
|
||||
//! At the same time, we are not verifying storage proofs before boosting
|
||||
//! priority. Instead, we simply trust relayer, when it says that transaction delivers
|
||||
//! `N` messages.
|
||||
//!
|
||||
//! This allows relayers to submit transactions which declare large number of bundled
|
||||
//! transactions to receive priority boost for free, potentially pushing actual delivery
|
||||
//! transactions from the block (or even transaction queue). Such transactions are
|
||||
//! not free, but their cost is relatively small.
|
||||
//!
|
||||
//! To alleviate that, we only boost transactions of relayers that have some stake
|
||||
//! that guarantees that their transactions are valid. Such relayers get priority
|
||||
//! for free, but they risk to lose their stake.
|
||||
|
||||
use crate::{PayRewardFromAccount, RewardsAccountParams};
|
||||
|
||||
use codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
|
||||
use scale_info::TypeInfo;
|
||||
use pezsp_runtime::{
|
||||
traits::{Get, IdentifyAccount, Zero},
|
||||
DispatchError, DispatchResult,
|
||||
};
|
||||
|
||||
/// Either explicit account reference or `RewardsAccountParams`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum ExplicitOrAccountParams<AccountId, LaneId: Decode + Encode> {
|
||||
/// Explicit account reference.
|
||||
Explicit(AccountId),
|
||||
/// Account, referenced using `RewardsAccountParams`.
|
||||
Params(RewardsAccountParams<LaneId>),
|
||||
}
|
||||
|
||||
impl<AccountId, LaneId: Decode + Encode> From<RewardsAccountParams<LaneId>>
|
||||
for ExplicitOrAccountParams<AccountId, LaneId>
|
||||
{
|
||||
fn from(params: RewardsAccountParams<LaneId>) -> Self {
|
||||
ExplicitOrAccountParams::Params(params)
|
||||
}
|
||||
}
|
||||
|
||||
impl<AccountId: Decode + Encode, LaneId: Decode + Encode> IdentifyAccount
|
||||
for ExplicitOrAccountParams<AccountId, LaneId>
|
||||
{
|
||||
type AccountId = AccountId;
|
||||
|
||||
fn into_account(self) -> Self::AccountId {
|
||||
match self {
|
||||
ExplicitOrAccountParams::Explicit(account_id) => account_id,
|
||||
ExplicitOrAccountParams::Params(params) =>
|
||||
PayRewardFromAccount::<(), AccountId, LaneId, ()>::rewards_account(params),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Relayer registration.
|
||||
#[derive(
|
||||
Copy,
|
||||
Clone,
|
||||
Debug,
|
||||
Decode,
|
||||
DecodeWithMemTracking,
|
||||
Encode,
|
||||
Eq,
|
||||
PartialEq,
|
||||
TypeInfo,
|
||||
MaxEncodedLen,
|
||||
)]
|
||||
pub struct Registration<BlockNumber, Balance> {
|
||||
/// The last block number, where this registration is considered active.
|
||||
///
|
||||
/// Relayer has an option to renew his registration (this may be done before it
|
||||
/// is spoiled as well). Starting from block `valid_till + 1`, relayer may `deregister`
|
||||
/// himself and get his stake back.
|
||||
///
|
||||
/// Please keep in mind that priority boost stops working some blocks before the
|
||||
/// registration ends (see [`StakeAndSlash::RequiredRegistrationLease`]).
|
||||
pub valid_till: BlockNumber,
|
||||
/// Active relayer stake, which is mapped to the relayer reserved balance.
|
||||
///
|
||||
/// If `stake` is less than the [`StakeAndSlash::RequiredStake`], the registration
|
||||
/// is considered inactive even if `valid_till + 1` is not yet reached.
|
||||
pub stake: Balance,
|
||||
}
|
||||
|
||||
/// Relayer stake-and-slash mechanism.
|
||||
pub trait StakeAndSlash<AccountId, BlockNumber, Balance> {
|
||||
/// The stake that the relayer must have to have its transactions boosted.
|
||||
type RequiredStake: Get<Balance>;
|
||||
/// Required **remaining** registration lease to be able to get transaction priority boost.
|
||||
///
|
||||
/// If the difference between registration's `valid_till` and the current block number
|
||||
/// is less than the `RequiredRegistrationLease`, it becomes inactive and relayer transaction
|
||||
/// won't get priority boost. This period exists, because priority is calculated when
|
||||
/// transaction is placed to the queue (and it is reevaluated periodically) and then some time
|
||||
/// may pass before transaction will be included into the block.
|
||||
type RequiredRegistrationLease: Get<BlockNumber>;
|
||||
|
||||
/// Reserve the given amount at relayer account.
|
||||
fn reserve(relayer: &AccountId, amount: Balance) -> DispatchResult;
|
||||
/// `Unreserve` the given amount from relayer account.
|
||||
///
|
||||
/// Returns amount that we have failed to `unreserve`.
|
||||
fn unreserve(relayer: &AccountId, amount: Balance) -> Balance;
|
||||
/// Slash up to `amount` from reserved balance of account `relayer` and send funds to given
|
||||
/// `beneficiary`.
|
||||
///
|
||||
/// Returns `Ok(_)` with non-zero balance if we have failed to repatriate some portion of stake.
|
||||
fn repatriate_reserved(
|
||||
relayer: &AccountId,
|
||||
beneficiary: &AccountId,
|
||||
amount: Balance,
|
||||
) -> Result<Balance, DispatchError>;
|
||||
}
|
||||
|
||||
impl<AccountId, BlockNumber, Balance> StakeAndSlash<AccountId, BlockNumber, Balance> for ()
|
||||
where
|
||||
Balance: Default + Zero,
|
||||
BlockNumber: Default,
|
||||
{
|
||||
type RequiredStake = ();
|
||||
type RequiredRegistrationLease = ();
|
||||
|
||||
fn reserve(_relayer: &AccountId, _amount: Balance) -> DispatchResult {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn unreserve(_relayer: &AccountId, _amount: Balance) -> Balance {
|
||||
Zero::zero()
|
||||
}
|
||||
|
||||
fn repatriate_reserved(
|
||||
_relayer: &AccountId,
|
||||
_beneficiary: &AccountId,
|
||||
_amount: Balance,
|
||||
) -> Result<Balance, DispatchError> {
|
||||
Ok(Zero::zero())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user