From cbd075edf3b068de7adf79ec3007847112e402ed Mon Sep 17 00:00:00 2001 From: Svyatoslav Nikolsky Date: Wed, 1 Sep 2021 16:16:06 +0300 Subject: [PATCH 01/31] add bridge GRANDPA pallets to Kusama and Polkadot --- Cargo.lock | 34 ++++++++++++++++++++++++++++ runtime/kusama/Cargo.toml | 5 +++++ runtime/kusama/src/lib.rs | 41 +++++++++++++++++++++++++++++++++ runtime/polkadot/Cargo.toml | 5 +++++ runtime/polkadot/src/lib.rs | 45 ++++++++++++++++++++++++++++++++++--- 5 files changed, 127 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 194de7660432..9933327e644f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -741,6 +741,21 @@ dependencies = [ "sp-std", ] +[[package]] +name = "bp-kusama" +version = "0.1.0" +dependencies = [ + "bp-messages", + "bp-polkadot-core", + "bp-runtime", + "frame-support", + "smallvec", + "sp-api", + "sp-runtime", + "sp-std", + "sp-version", +] + [[package]] name = "bp-message-dispatch" version = "0.1.0" @@ -770,6 +785,21 @@ dependencies = [ "sp-std", ] +[[package]] +name = "bp-polkadot" +version = "0.1.0" +dependencies = [ + "bp-messages", + "bp-polkadot-core", + "bp-runtime", + "frame-support", + "smallvec", + "sp-api", + "sp-runtime", + "sp-std", + "sp-version", +] + [[package]] name = "bp-polkadot-core" version = "0.1.0" @@ -3499,6 +3529,7 @@ version = "0.9.18" dependencies = [ "beefy-primitives", "bitvec", + "bp-polkadot", "frame-benchmarking", "frame-election-provider-support", "frame-executive", @@ -3516,6 +3547,7 @@ dependencies = [ "pallet-bags-list", "pallet-balances", "pallet-bounties", + "pallet-bridge-grandpa", "pallet-child-bounties", "pallet-collective", "pallet-democracy", @@ -7260,6 +7292,7 @@ version = "0.9.18" dependencies = [ "beefy-primitives", "bitvec", + "bp-kusama", "frame-benchmarking", "frame-election-provider-support", "frame-executive", @@ -7276,6 +7309,7 @@ dependencies = [ "pallet-bags-list", "pallet-balances", "pallet-bounties", + "pallet-bridge-grandpa", "pallet-child-bounties", "pallet-collective", "pallet-democracy", diff --git a/runtime/kusama/Cargo.toml b/runtime/kusama/Cargo.toml index c6190c7c4823..a02d7b2df89b 100644 --- a/runtime/kusama/Cargo.toml +++ b/runtime/kusama/Cargo.toml @@ -19,6 +19,7 @@ smallvec = "1.8.0" authority-discovery-primitives = { package = "sp-authority-discovery", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } babe-primitives = { package = "sp-consensus-babe", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } beefy-primitives = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +bp-polkadot = { path = "../../bridges/primitives/chain-polkadot", default-features = false } kusama-runtime-constants = { package = "kusama-runtime-constants", path = "./constants", default-features = false } sp-api = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } inherents = { package = "sp-inherents", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } @@ -41,6 +42,7 @@ pallet-babe = { git = "https://github.com/paritytech/substrate", branch = "maste pallet-bags-list = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } pallet-bounties = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +pallet-bridge-grandpa = { path = "../../bridges/modules/grandpa", default-features = false } pallet-child-bounties = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } pallet-transaction-payment = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } pallet-transaction-payment-rpc-runtime-api = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } @@ -111,6 +113,7 @@ only-staking = [] std = [ "authority-discovery-primitives/std", "bitvec/std", + "bp-polkadot/std", "primitives/std", "rustc-hex/std", "parity-scale-codec/std", @@ -130,6 +133,7 @@ std = [ "pallet-bags-list/std", "pallet-balances/std", "pallet-bounties/std", + "pallet-bridge-grandpa/std", "pallet-child-bounties/std", "pallet-transaction-payment/std", "pallet-transaction-payment-rpc-runtime-api/std", @@ -192,6 +196,7 @@ runtime-benchmarks = [ "pallet-babe/runtime-benchmarks", "pallet-balances/runtime-benchmarks", "pallet-bounties/runtime-benchmarks", + "pallet-bridge-grandpa/runtime-benchmarks", "pallet-child-bounties/runtime-benchmarks", "pallet-collective/runtime-benchmarks", "pallet-democracy/runtime-benchmarks", diff --git a/runtime/kusama/src/lib.rs b/runtime/kusama/src/lib.rs index 494d5590d941..c47ae078d497 100644 --- a/runtime/kusama/src/lib.rs +++ b/runtime/kusama/src/lib.rs @@ -1379,6 +1379,31 @@ impl pallet_gilt::Config for Runtime { type WeightInfo = weights::pallet_gilt::WeightInfo; } +parameter_types! { + /// This is a pretty unscientific cap. + /// + /// Note that once this is hit the bridge GRANDPA pallet will essentially throttle incoming requests down to one + /// call per block. + pub const MaxBridgeGrandpaRequests: u32 = 50; + /// Number of headers to keep in bridge GRANDPA pallet. + /// + /// Assuming the worst case of every header being finalized, we will keep headers at least for a + /// week. + pub const BridgeGrandpaHeadersToKeep: u32 = 7 * bp_polkadot::DAYS as u32; +} + +/// Instance of the with-Polkadot bridge GRANDPA pallet. +pub type PolkadotGrandpaInstance = (); + +impl pallet_bridge_grandpa::Config for Runtime { + type BridgedChain = bp_polkadot::Polkadot; + type MaxRequests = MaxBridgeGrandpaRequests; + type HeadersToKeep = BridgeGrandpaHeadersToKeep; + + type WeightInfo = pallet_bridge_grandpa::weights::RialtoWeight; // TODO +} + + construct_runtime! { pub enum Runtime where Block = Block, @@ -1486,6 +1511,11 @@ construct_runtime! { // Pallet for sending XCM. XcmPallet: pallet_xcm::{Pallet, Call, Storage, Event, Origin, Config} = 99, + + // Bridge pallets to bridge with Polkadot. + BridgePolkadotGrandpa: pallet_bridge_grandpa::{Pallet, Call, Storage, Config} = 110, + //BridgePolkadotMessages: pallet_bridge_messages::{Pallet, Call, Storage, Event, Config} = 111, + //BridgePolkadotMessagesDispatch: pallet_bridge_dispatch::{Pallet, Event} = 112, } } @@ -1785,6 +1815,17 @@ sp_api::impl_runtime_apis! { } } + impl bp_polkadot::PolkadotFinalityApi for Runtime { + fn best_finalized() -> (bp_polkadot::BlockNumber, bp_polkadot::Hash) { + let header = BridgePolkadotGrandpa::best_finalized(); + (header.number, header.hash()) + } + + fn is_known_header(hash: bp_polkadot::Hash) -> bool { + BridgePolkadotGrandpa::is_known_header(hash) + } + } + impl fg_primitives::GrandpaApi for Runtime { fn grandpa_authorities() -> Vec<(GrandpaId, u64)> { Grandpa::grandpa_authorities() diff --git a/runtime/polkadot/Cargo.toml b/runtime/polkadot/Cargo.toml index 4bb1967bd328..b66091e3504b 100644 --- a/runtime/polkadot/Cargo.toml +++ b/runtime/polkadot/Cargo.toml @@ -20,6 +20,7 @@ authority-discovery-primitives = { package = "sp-authority-discovery", git = "ht babe-primitives = { package = "sp-consensus-babe", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } beefy-primitives = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } block-builder-api = { package = "sp-block-builder", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +bp-kusama = { path = "../../bridges/primitives/chain-kusama", default-features = false } inherents = { package = "sp-inherents", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } offchain-primitives = { package = "sp-offchain", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } tx-pool-api = { package = "sp-transaction-pool", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } @@ -39,6 +40,7 @@ pallet-babe = { git = "https://github.com/paritytech/substrate", branch = "maste pallet-bags-list = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } pallet-bounties = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +pallet-bridge-grandpa = { path = "../../bridges/modules/grandpa", default-features = false } pallet-child-bounties = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } pallet-transaction-payment = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } pallet-transaction-payment-rpc-runtime-api = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } @@ -108,6 +110,7 @@ only-staking = [] std = [ "authority-discovery-primitives/std", "bitvec/std", + "bp-kusama/std", "primitives/std", "rustc-hex/std", "parity-scale-codec/std", @@ -126,6 +129,7 @@ std = [ "pallet-bags-list/std", "pallet-balances/std", "pallet-bounties/std", + "pallet-bridge-grandpa/std", "pallet-child-bounties/std", "pallet-transaction-payment/std", "pallet-transaction-payment-rpc-runtime-api/std", @@ -183,6 +187,7 @@ runtime-benchmarks = [ "pallet-babe/runtime-benchmarks", "pallet-bags-list/runtime-benchmarks", "pallet-balances/runtime-benchmarks", + "pallet-bridge-grandpa/runtime-benchmarks", "pallet-collective/runtime-benchmarks", "pallet-democracy/runtime-benchmarks", "pallet-elections-phragmen/runtime-benchmarks", diff --git a/runtime/polkadot/src/lib.rs b/runtime/polkadot/src/lib.rs index 8cb75e3fe941..9593a2519d0c 100644 --- a/runtime/polkadot/src/lib.rs +++ b/runtime/polkadot/src/lib.rs @@ -178,9 +178,8 @@ impl Contains for BaseFilter { Call::Auctions(_) | Call::Crowdloan(_) | Call::BagsList(_) | - Call::XcmPallet(_) => true, - // All pallets are allowed, but exhaustive match is defensive - // in the case of adding new pallets. + Call::XcmPallet(_) | + Call::BridgeKusamaGrandpa(_) => true, } } } @@ -1346,6 +1345,30 @@ impl auctions::Config for Runtime { type WeightInfo = weights::runtime_common_auctions::WeightInfo; } +parameter_types! { + /// This is a pretty unscientific cap. + /// + /// Note that once this is hit the bridge GRANDPA pallet will essentially throttle incoming requests down to one + /// call per block. + pub const MaxBridgeGrandpaRequests: u32 = 50; + /// Number of headers to keep in bridge GRANDPA pallet. + /// + /// Assuming the worst case of every header being finalized, we will keep headers at least for a + /// week. + pub const BridgeGrandpaHeadersToKeep: u32 = 7 * bp_kusama::DAYS as u32; +} + +/// Instance of the with-Kusama bridge GRANDPA pallet. +pub type KusamaGrandpaInstance = (); + +impl pallet_bridge_grandpa::Config for Runtime { + type BridgedChain = bp_kusama::Kusama; + type MaxRequests = MaxBridgeGrandpaRequests; + type HeadersToKeep = BridgeGrandpaHeadersToKeep; + + type WeightInfo = pallet_bridge_grandpa::weights::RialtoWeight; // TODO +} + construct_runtime! { pub enum Runtime where Block = Block, @@ -1438,6 +1461,11 @@ construct_runtime! { // Pallet for sending XCM. XcmPallet: pallet_xcm::{Pallet, Call, Storage, Event, Origin, Config} = 99, + + // Bridge pallets to bridge with Kusama. + BridgeKusamaGrandpa: pallet_bridge_grandpa::{Pallet, Call, Storage, Config} = 110, + //BridgeKusamaMessages: pallet_bridge_messages::{Pallet, Call, Storage, Event, Config} = 111, + //BridgeKusamaMessagesDispatch: pallet_bridge_dispatch::{Pallet, Event} = 112, } } @@ -1930,6 +1958,17 @@ sp_api::impl_runtime_apis! { } } + impl bp_kusama::KusamaFinalityApi for Runtime { + fn best_finalized() -> (bp_kusama::BlockNumber, bp_kusama::Hash) { + let header = BridgeKusamaGrandpa::best_finalized(); + (header.number, header.hash()) + } + + fn is_known_header(hash: bp_kusama::Hash) -> bool { + BridgeKusamaGrandpa::is_known_header(hash) + } + } + impl fg_primitives::GrandpaApi for Runtime { fn grandpa_authorities() -> Vec<(GrandpaId, u64)> { Grandpa::grandpa_authorities() From 57ca5f5bb1df74829148b4311f58679dc1e77d88 Mon Sep 17 00:00:00 2001 From: Svyatoslav Nikolsky Date: Mon, 6 Sep 2021 13:50:47 +0300 Subject: [PATCH 02/31] add bridge messages pallets to Polkadot & Kusama runtimes --- Cargo.lock | 12 + bridges/primitives/polkadot-core/src/lib.rs | 33 ++ runtime/kusama/Cargo.toml | 13 + runtime/kusama/src/lib.rs | 66 +++- runtime/kusama/src/polkadot_messages.rs | 324 ++++++++++++++++++++ runtime/polkadot/Cargo.toml | 12 + runtime/polkadot/src/kusama_messages.rs | 324 ++++++++++++++++++++ runtime/polkadot/src/lib.rs | 70 ++++- 8 files changed, 849 insertions(+), 5 deletions(-) create mode 100644 runtime/kusama/src/polkadot_messages.rs create mode 100644 runtime/polkadot/src/kusama_messages.rs diff --git a/Cargo.lock b/Cargo.lock index 9933327e644f..fe9a6167f01c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3529,7 +3529,11 @@ version = "0.9.18" dependencies = [ "beefy-primitives", "bitvec", + "bp-kusama", + "bp-messages", "bp-polkadot", + "bp-runtime", + "bridge-runtime-common", "frame-benchmarking", "frame-election-provider-support", "frame-executive", @@ -3547,7 +3551,9 @@ dependencies = [ "pallet-bags-list", "pallet-balances", "pallet-bounties", + "pallet-bridge-dispatch", "pallet-bridge-grandpa", + "pallet-bridge-messages", "pallet-child-bounties", "pallet-collective", "pallet-democracy", @@ -7293,6 +7299,10 @@ dependencies = [ "beefy-primitives", "bitvec", "bp-kusama", + "bp-messages", + "bp-polkadot", + "bp-runtime", + "bridge-runtime-common", "frame-benchmarking", "frame-election-provider-support", "frame-executive", @@ -7309,7 +7319,9 @@ dependencies = [ "pallet-bags-list", "pallet-balances", "pallet-bounties", + "pallet-bridge-dispatch", "pallet-bridge-grandpa", + "pallet-bridge-messages", "pallet-child-bounties", "pallet-collective", "pallet-democracy", diff --git a/bridges/primitives/polkadot-core/src/lib.rs b/bridges/primitives/polkadot-core/src/lib.rs index 4c0a450eb719..3a3cba6ba854 100644 --- a/bridges/primitives/polkadot-core/src/lib.rs +++ b/bridges/primitives/polkadot-core/src/lib.rs @@ -170,6 +170,39 @@ pub const DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT: Weight = 1_500_000_000; /// transactions cheaper. pub const PAY_INBOUND_DISPATCH_FEE_WEIGHT: Weight = 600_000_000; +/// Maximal weight of single message delivery confirmation transaction on Polkadot-like chain. +/// +/// This value is a result of `pallet_bridge_messages::Pallet::receive_messages_delivery_proof` weight formula +/// computation for the case when single message is confirmed. The result then must be rounded up to account possible +/// future runtime upgrades. +pub const MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT: Weight = 2_000_000_000; + +/// Increase of delivery transaction weight on Polkadot-like chain with every additional message byte. +/// +/// This value is a result of `pallet_bridge_messages::WeightInfoExt::storage_proof_size_overhead(1)` call. The +/// result then must be rounded up to account possible future runtime upgrades. +pub const ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT: Weight = 25_000; + +/// Maximal number of bytes, included in the signed Polkadot-like transaction apart from the encoded call itself. +/// +/// Can be computed by subtracting encoded call size from raw transaction size. +pub const TX_EXTRA_BYTES: u32 = 256; + +/// Weight of single regular message delivery transaction on Polkadot-like chain. +/// +/// This value is a result of `pallet_bridge_messages::Pallet::receive_messages_proof_weight()` call +/// for the case when single message of `pallet_bridge_messages::EXPECTED_DEFAULT_MESSAGE_LENGTH` bytes is delivered. +/// The message must have dispatch weight set to zero. The result then must be rounded up to account +/// possible future runtime upgrades. +pub const DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT: Weight = 1_500_000_000; + +/// Weight of pay-dispatch-fee operation for inbound messages at Polkadot-like chain. +/// +/// This value corresponds to the result of `pallet_bridge_messages::WeightInfoExt::pay_inbound_dispatch_fee_overhead()` +/// call for your chain. Don't put too much reserve there, because it is used to **decrease** +/// `DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT` cost. So putting large reserve would make delivery transactions cheaper. +pub const PAY_INBOUND_DISPATCH_FEE_WEIGHT: Weight = 600_000_000; + /// Re-export `time_units` to make usage easier. pub use time_units::*; diff --git a/runtime/kusama/Cargo.toml b/runtime/kusama/Cargo.toml index a02d7b2df89b..11fa425a8fe4 100644 --- a/runtime/kusama/Cargo.toml +++ b/runtime/kusama/Cargo.toml @@ -20,6 +20,10 @@ authority-discovery-primitives = { package = "sp-authority-discovery", git = "ht babe-primitives = { package = "sp-consensus-babe", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } beefy-primitives = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } bp-polkadot = { path = "../../bridges/primitives/chain-polkadot", default-features = false } +bp-kusama = { path = "../../bridges/primitives/chain-kusama", default-features = false } +bp-messages = { path = "../../bridges/primitives/messages", default-features = false } +bp-polkadot = { path = "../../bridges/primitives/chain-polkadot", default-features = false } +bp-runtime = { path = "../../bridges/primitives/runtime", default-features = false } kusama-runtime-constants = { package = "kusama-runtime-constants", path = "./constants", default-features = false } sp-api = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } inherents = { package = "sp-inherents", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } @@ -42,7 +46,9 @@ pallet-babe = { git = "https://github.com/paritytech/substrate", branch = "maste pallet-bags-list = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } pallet-bounties = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +pallet-bridge-dispatch = { path = "../../bridges/modules/dispatch", default-features = false } pallet-bridge-grandpa = { path = "../../bridges/modules/grandpa", default-features = false } +pallet-bridge-messages = { path = "../../bridges/modules/messages", default-features = false } pallet-child-bounties = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } pallet-transaction-payment = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } pallet-transaction-payment-rpc-runtime-api = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } @@ -87,6 +93,7 @@ pallet-session-benchmarking = { git = "https://github.com/paritytech/substrate", frame-system-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false, optional = true } hex-literal = { version = "0.3.4", optional = true } +bridge-runtime-common = { path = "../../bridges/bin/runtime-common", default-features = false } runtime-common = { package = "polkadot-runtime-common", path = "../common", default-features = false } runtime-parachains = { package = "polkadot-runtime-parachains", path = "../parachains", default-features = false } primitives = { package = "polkadot-primitives", path = "../../primitives", default-features = false } @@ -113,7 +120,11 @@ only-staking = [] std = [ "authority-discovery-primitives/std", "bitvec/std", + "bp-kusama/std", + "bp-messages/std", "bp-polkadot/std", + "bp-runtime/std", + "bridge-runtime-common/std", "primitives/std", "rustc-hex/std", "parity-scale-codec/std", @@ -133,7 +144,9 @@ std = [ "pallet-bags-list/std", "pallet-balances/std", "pallet-bounties/std", + "pallet-bridge-dispatch/std", "pallet-bridge-grandpa/std", + "pallet-bridge-messages/std", "pallet-child-bounties/std", "pallet-transaction-payment/std", "pallet-transaction-payment-rpc-runtime-api/std", diff --git a/runtime/kusama/src/lib.rs b/runtime/kusama/src/lib.rs index c47ae078d497..ef1c4d2acc11 100644 --- a/runtime/kusama/src/lib.rs +++ b/runtime/kusama/src/lib.rs @@ -86,6 +86,9 @@ pub use sp_runtime::BuildStorage; /// Constant values used within the runtime. use kusama_runtime_constants::{currency::*, fee::*, time::*}; +// Messaging with Polkadot support. +mod polkadot_messages; + // Weights used in the runtime. mod weights; @@ -1403,6 +1406,65 @@ impl pallet_bridge_grandpa::Config for Runtime { type WeightInfo = pallet_bridge_grandpa::weights::RialtoWeight; // TODO } +parameter_types! { + pub const MaxMessagesToPruneAtOnce: bp_messages::MessageNonce = 8; + pub const MaxUnrewardedRelayerEntriesAtInboundLane: bp_messages::MessageNonce = + bp_kusama::MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE; + pub const MaxUnconfirmedMessagesAtInboundLane: bp_messages::MessageNonce = + bp_kusama::MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE; + pub const RootAccountForPayments: Option = None; + pub const PolkadotChainId: bp_runtime::ChainId = bp_runtime::POLKADOT_CHAIN_ID; +} + +/// Instance of the messages pallet used to relay messages to/from Polkadot chain. +pub type PolkadotMessagesInstance = (); + +impl pallet_bridge_messages::Config for Runtime { + type Event = Event; + type WeightInfo = pallet_bridge_messages::weights::RialtoWeight; // TODO + type Parameter = polkadot_messages::WithPolkadotMessageBridgeParameter; + type MaxMessagesToPruneAtOnce = MaxMessagesToPruneAtOnce; + type MaxUnrewardedRelayerEntriesAtInboundLane = MaxUnrewardedRelayerEntriesAtInboundLane; + type MaxUnconfirmedMessagesAtInboundLane = MaxUnconfirmedMessagesAtInboundLane; + + type OutboundPayload = polkadot_messages::ToPolkadotMessagePayload; + type OutboundMessageFee = Balance; + + type InboundPayload = polkadot_messages::FromPolkadotMessagePayload; + type InboundMessageFee = bp_polkadot::Balance; + type InboundRelayer = bp_polkadot::AccountId; + + type AccountIdConverter = bp_kusama::AccountIdConverter; + + type TargetHeaderChain = polkadot_messages::Polkadot; + type LaneMessageVerifier = polkadot_messages::ToPolkadotMessageVerifier; + type MessageDeliveryAndDispatchPayment = pallet_bridge_messages::instant_payments::InstantCurrencyPayments< + Runtime, + pallet_balances::Pallet, + polkadot_messages::GetDeliveryConfirmationTransactionFee, + RootAccountForPayments, + >; + type OnDeliveryConfirmed = (); + + type SourceHeaderChain = polkadot_messages::Polkadot; + type MessageDispatch = polkadot_messages::FromPolkadotMessageDispatch; + type BridgedChainId = PolkadotChainId; +} + +/// Instance of the dispatch pallet used to dispatch incoming Polkadot messages. +pub type PolkadotMessagesDispatchInstance = (); + +impl pallet_bridge_dispatch::Config for Runtime { + type Event = Event; + type MessageId = (bp_messages::LaneId, bp_messages::MessageNonce); + type Call = Call; + type CallFilter = frame_support::traits::Everything; + type EncodedCall = polkadot_messages::FromPolkadotEncodedCall; + type SourceChainAccountId = bp_polkadot::AccountId; + type TargetChainAccountPublic = sp_runtime::MultiSigner; + type TargetChainSignature = sp_runtime::MultiSignature; + type AccountIdConverter = bp_kusama::AccountIdConverter; +} construct_runtime! { pub enum Runtime where @@ -1514,8 +1576,8 @@ construct_runtime! { // Bridge pallets to bridge with Polkadot. BridgePolkadotGrandpa: pallet_bridge_grandpa::{Pallet, Call, Storage, Config} = 110, - //BridgePolkadotMessages: pallet_bridge_messages::{Pallet, Call, Storage, Event, Config} = 111, - //BridgePolkadotMessagesDispatch: pallet_bridge_dispatch::{Pallet, Event} = 112, + BridgePolkadotMessages: pallet_bridge_messages::{Pallet, Call, Storage, Event, Config} = 111, + BridgePolkadotMessagesDispatch: pallet_bridge_dispatch::{Pallet, Event} = 112, } } diff --git a/runtime/kusama/src/polkadot_messages.rs b/runtime/kusama/src/polkadot_messages.rs new file mode 100644 index 000000000000..400f0bbcb8c6 --- /dev/null +++ b/runtime/kusama/src/polkadot_messages.rs @@ -0,0 +1,324 @@ +// Copyright 2017-2020 Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot 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. + +// Polkadot 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 Polkadot. If not, see . + +//! Over-bridge messaging support for Kusama <> Polkadot bridge. + +use crate::Runtime; + +use bp_messages::{ + source_chain::TargetHeaderChain, + target_chain::{ProvedMessages, SourceHeaderChain}, + InboundLaneData, LaneId, Message, MessageNonce, Parameter as MessagesParameter, +}; +use bp_runtime::{ChainId, KUSAMA_CHAIN_ID, POLKADOT_CHAIN_ID}; +use bridge_runtime_common::messages::{self, MessageBridge, MessageTransaction, ThisChainWithMessages}; +use parity_scale_codec::{Decode, Encode}; +use frame_support::{ + parameter_types, + traits::Get, + weights::{DispatchClass, Weight, WeightToFeePolynomial}, + RuntimeDebug, +}; +use sp_runtime::{traits::Saturating, FixedPointNumber, FixedU128}; +use sp_std::{convert::TryFrom, ops::RangeInclusive}; + +/// Initial value of `PolkadotToKusamaConversionRate` parameter. +pub const INITIAL_POLKADOT_TO_KUSAMA_CONVERSION_RATE: FixedU128 = FixedU128::from_inner(FixedU128::DIV); +/// Initial value of `PolkadotFeeMultiplier` parameter. +pub const INITIAL_POLKADOT_FEE_MULTIPLIER: FixedU128 = FixedU128::from_inner(FixedU128::DIV); + +parameter_types! { + /// Polkadot (DOT) to Kusama (KSM) conversion rate. + pub storage PolkadotToKusamaConversionRate: FixedU128 = INITIAL_POLKADOT_TO_KUSAMA_CONVERSION_RATE; + /// Fee multiplier at Polkadot. + pub storage PolkadotFeeMultiplier: FixedU128 = INITIAL_POLKADOT_FEE_MULTIPLIER; +} + +/// Message payload for Kusama -> Polkadot messages. +pub type ToPolkadotMessagePayload = messages::source::FromThisChainMessagePayload; + +/// Message verifier for Kusama -> Polkadot messages. +pub type ToPolkadotMessageVerifier = messages::source::FromThisChainMessageVerifier; + +/// Message payload for Polkadot -> Kusama messages. +pub type FromPolkadotMessagePayload = messages::target::FromBridgedChainMessagePayload; + +/// Encoded Kusama Call as it comes from Polkadot. +pub type FromPolkadotEncodedCall = messages::target::FromBridgedChainEncodedMessageCall; + +/// Call-dispatch based message dispatch for Polkadot -> Kusama messages. +pub type FromPolkadotMessageDispatch = messages::target::FromBridgedChainMessageDispatch< + WithPolkadotMessageBridge, + crate::Runtime, + pallet_balances::Pallet, + crate::PolkadotMessagesDispatchInstance, +>; + +/// Kusama <-> Polkadot message bridge. +#[derive(RuntimeDebug, Clone, Copy)] +pub struct WithPolkadotMessageBridge; + +impl MessageBridge for WithPolkadotMessageBridge { + const RELAYER_FEE_PERCENT: u32 = 10; + const THIS_CHAIN_ID: ChainId = KUSAMA_CHAIN_ID; + const BRIDGED_CHAIN_ID: ChainId = POLKADOT_CHAIN_ID; + const BRIDGED_MESSAGES_PALLET_NAME: &'static str = bp_polkadot::WITH_KUSAMA_MESSAGES_PALLET_NAME; + + type ThisChain = Kusama; + type BridgedChain = Polkadot; + + fn bridged_balance_to_this_balance(bridged_balance: bp_polkadot::Balance) -> bp_kusama::Balance { + bp_kusama::Balance::try_from(PolkadotToKusamaConversionRate::get().saturating_mul_int(bridged_balance)) + .unwrap_or(bp_kusama::Balance::MAX) + } +} + +/// Kusama from messages point of view. +#[derive(RuntimeDebug, Clone, Copy)] +pub struct Kusama; + +impl messages::ChainWithMessages for Kusama { + type Hash = bp_kusama::Hash; + type AccountId = bp_kusama::AccountId; + type Signer = bp_kusama::AccountPublic; + type Signature = bp_kusama::Signature; + type Weight = Weight; + type Balance = bp_kusama::Balance; +} + +impl ThisChainWithMessages for Kusama { + type Call = crate::Call; + + fn is_outbound_lane_enabled(lane: &LaneId) -> bool { + *lane == [0, 0, 0, 0] + } + + fn maximal_pending_messages_at_outbound_lane() -> MessageNonce { + bp_polkadot::MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE + } + + fn estimate_delivery_confirmation_transaction() -> MessageTransaction { + let inbound_data_size = InboundLaneData::::encoded_size_hint( + bp_kusama::MAXIMAL_ENCODED_ACCOUNT_ID_SIZE, + 1, + 1, + ) + .unwrap_or(u32::MAX); + + MessageTransaction { + dispatch_weight: bp_kusama::MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT, + size: inbound_data_size + .saturating_add(bp_polkadot::EXTRA_STORAGE_PROOF_SIZE) + .saturating_add(bp_kusama::TX_EXTRA_BYTES), + } + } + + fn transaction_payment(transaction: MessageTransaction) -> bp_kusama::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::::next_fee_multiplier()); + let per_byte_fee = crate::TransactionByteFee::get(); + messages::transaction_payment( + bp_kusama::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic, + per_byte_fee, + multiplier, + |weight| crate::WeightToFee::calc(&weight), + transaction, + ) + } +} + +/// Polkadot from messages point of view. +#[derive(RuntimeDebug, Clone, Copy)] +pub struct Polkadot; + +impl messages::ChainWithMessages for Polkadot { + type Hash = bp_polkadot::Hash; + type AccountId = bp_polkadot::AccountId; + type Signer = bp_polkadot::AccountPublic; + type Signature = bp_polkadot::Signature; + type Weight = Weight; + type Balance = bp_polkadot::Balance; +} + +impl messages::BridgedChainWithMessages for Polkadot { + fn maximal_extrinsic_size() -> u32 { + bp_polkadot::max_extrinsic_size() + } + + fn message_weight_limits(_message_payload: &[u8]) -> RangeInclusive { + // we don't want to relay too large messages + keep reserve for future upgrades + let upper_limit = messages::target::maximal_incoming_message_dispatch_weight( + bp_polkadot::max_extrinsic_weight(), + ); + + // this bridge may be used to deliver all kind of messages, so we're not making any assumptions about + // minimal dispatch weight here + + 0..=upper_limit + } + + fn estimate_delivery_transaction( + message_payload: &[u8], + include_pay_dispatch_fee_cost: bool, + message_dispatch_weight: Weight, + ) -> MessageTransaction { + 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_polkadot::ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT) + .saturating_add(bp_polkadot::DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT) + .saturating_sub(if include_pay_dispatch_fee_cost { + 0 + } else { + bp_polkadot::PAY_INBOUND_DISPATCH_FEE_WEIGHT + }) + .saturating_add(message_dispatch_weight), + size: message_payload_len + .saturating_add(bp_kusama::EXTRA_STORAGE_PROOF_SIZE) + .saturating_add(bp_polkadot::TX_EXTRA_BYTES), + } + } + + fn transaction_payment(transaction: MessageTransaction) -> bp_polkadot::Balance { + // we don't have a direct access to the value of multiplier of Polkadot chain + // => it is a messages module parameter + let multiplier = PolkadotFeeMultiplier::get(); + let per_byte_fee = bp_polkadot::TRANSACTION_BYTE_FEE; + messages::transaction_payment( + bp_polkadot::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic, + per_byte_fee, + multiplier, + |weight| bp_polkadot::WeightToFee::calc(&weight), + transaction, + ) + } +} + +impl TargetHeaderChain for Polkadot { + type Error = &'static str; + type MessagesDeliveryProof = messages::source::FromBridgedChainMessagesDeliveryProof; + + fn verify_message(payload: &ToPolkadotMessagePayload) -> Result<(), Self::Error> { + messages::source::verify_chain_message::(payload) + } + + fn verify_messages_delivery_proof( + proof: Self::MessagesDeliveryProof, + ) -> Result<(LaneId, InboundLaneData), Self::Error> { + messages::source::verify_messages_delivery_proof::< + WithPolkadotMessageBridge, + Runtime, + crate::PolkadotGrandpaInstance, + >(proof) + } +} + +impl SourceHeaderChain for Polkadot { + type Error = &'static str; + type MessagesProof = messages::target::FromBridgedChainMessagesProof; + + fn verify_messages_proof( + proof: Self::MessagesProof, + messages_count: u32, + ) -> Result>, Self::Error> { + messages::target::verify_messages_proof::( + proof, + messages_count, + ) + } +} + +/// Kusama <> Polkadot messages pallet parameters. +#[derive(RuntimeDebug, Clone, Encode, Decode, PartialEq, Eq)] +pub enum WithPolkadotMessageBridgeParameter { + /// The conversion formula we use is: `KusamaTokens = PolkadotTokens * conversion_rate`. + PolkadotToKusamaConversionRate(FixedU128), + /// Fee multiplier at the Polkadot chain. + PolkadotFeeMultiplier(FixedU128), +} + +impl MessagesParameter for WithPolkadotMessageBridgeParameter { + fn save(&self) { + match *self { + WithPolkadotMessageBridgeParameter::PolkadotToKusamaConversionRate(ref conversion_rate) => { + PolkadotToKusamaConversionRate::set(conversion_rate); + }, + WithPolkadotMessageBridgeParameter::PolkadotFeeMultiplier(ref fee_multiplier) => { + PolkadotFeeMultiplier::set(fee_multiplier); + }, + } + } +} + +/// The cost of delivery confirmation transaction. +pub struct GetDeliveryConfirmationTransactionFee; + +impl Get for GetDeliveryConfirmationTransactionFee { + fn get() -> crate::Balance { + ::transaction_payment( + Kusama::estimate_delivery_confirmation_transaction(), + ) + } +} + +#[cfg(test)] +mod tests { + use crate::*; + use super::*; + + #[test] + fn ensure_kusama_message_lane_weights_are_correct() { + type Weights = pallet_bridge_messages::weights::RialtoWeight; // TODO: use Kusama weights + + pallet_bridge_messages::ensure_weights_are_correct::( + bp_kusama::DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT, + bp_kusama::ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT, + bp_kusama::MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT, + bp_kusama::PAY_INBOUND_DISPATCH_FEE_WEIGHT, + DbWeight::get(), + ); + + let max_incoming_message_proof_size = bp_polkadot::EXTRA_STORAGE_PROOF_SIZE.saturating_add( + messages::target::maximal_incoming_message_size(bp_kusama::max_extrinsic_size()), + ); + pallet_bridge_messages::ensure_able_to_receive_message::( + bp_kusama::max_extrinsic_size(), + bp_kusama::max_extrinsic_weight(), + max_incoming_message_proof_size, + messages::target::maximal_incoming_message_dispatch_weight(bp_kusama::max_extrinsic_weight()), + ); + + let max_incoming_inbound_lane_data_proof_size = bp_messages::InboundLaneData::<()>::encoded_size_hint( + bp_kusama::MAXIMAL_ENCODED_ACCOUNT_ID_SIZE, + bp_polkadot::MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE as _, + bp_polkadot::MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE as _, + ) + .unwrap_or(u32::MAX); + pallet_bridge_messages::ensure_able_to_receive_confirmation::( + bp_kusama::max_extrinsic_size(), + bp_kusama::max_extrinsic_weight(), + max_incoming_inbound_lane_data_proof_size, + bp_polkadot::MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE, + bp_polkadot::MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE, + DbWeight::get(), + ); + } +} diff --git a/runtime/polkadot/Cargo.toml b/runtime/polkadot/Cargo.toml index b66091e3504b..70bd01d56e2f 100644 --- a/runtime/polkadot/Cargo.toml +++ b/runtime/polkadot/Cargo.toml @@ -21,6 +21,9 @@ babe-primitives = { package = "sp-consensus-babe", git = "https://github.com/par beefy-primitives = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } block-builder-api = { package = "sp-block-builder", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } bp-kusama = { path = "../../bridges/primitives/chain-kusama", default-features = false } +bp-messages = { path = "../../bridges/primitives/messages", default-features = false } +bp-polkadot = { path = "../../bridges/primitives/chain-polkadot", default-features = false } +bp-runtime = { path = "../../bridges/primitives/runtime", default-features = false } inherents = { package = "sp-inherents", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } offchain-primitives = { package = "sp-offchain", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } tx-pool-api = { package = "sp-transaction-pool", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } @@ -40,7 +43,9 @@ pallet-babe = { git = "https://github.com/paritytech/substrate", branch = "maste pallet-bags-list = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } pallet-bounties = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +pallet-bridge-dispatch = { path = "../../bridges/modules/dispatch", default-features = false } pallet-bridge-grandpa = { path = "../../bridges/modules/grandpa", default-features = false } +pallet-bridge-messages = { path = "../../bridges/modules/messages", default-features = false } pallet-child-bounties = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } pallet-transaction-payment = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } pallet-transaction-payment-rpc-runtime-api = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } @@ -83,6 +88,7 @@ pallet-offences-benchmarking = { git = "https://github.com/paritytech/substrate" pallet-session-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false, optional = true } hex-literal = { version = "0.3.4", optional = true } +bridge-runtime-common = { path = "../../bridges/bin/runtime-common", default-features = false } runtime-common = { package = "polkadot-runtime-common", path = "../common", default-features = false } runtime-parachains = { package = "polkadot-runtime-parachains", path = "../parachains", default-features = false } primitives = { package = "polkadot-primitives", path = "../../primitives", default-features = false } @@ -111,6 +117,10 @@ std = [ "authority-discovery-primitives/std", "bitvec/std", "bp-kusama/std", + "bp-messages/std", + "bp-polkadot/std", + "bp-runtime/std", + "bridge-runtime-common/std", "primitives/std", "rustc-hex/std", "parity-scale-codec/std", @@ -129,7 +139,9 @@ std = [ "pallet-bags-list/std", "pallet-balances/std", "pallet-bounties/std", + "pallet-bridge-dispatch/std", "pallet-bridge-grandpa/std", + "pallet-bridge-messages/std", "pallet-child-bounties/std", "pallet-transaction-payment/std", "pallet-transaction-payment-rpc-runtime-api/std", diff --git a/runtime/polkadot/src/kusama_messages.rs b/runtime/polkadot/src/kusama_messages.rs new file mode 100644 index 000000000000..f7b577f49d23 --- /dev/null +++ b/runtime/polkadot/src/kusama_messages.rs @@ -0,0 +1,324 @@ +// Copyright 2017-2020 Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot 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. + +// Polkadot 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 Polkadot. If not, see . + +//! Over-bridge messaging support for Polkadot <> Kusama bridge. + +use crate::Runtime; + +use bp_messages::{ + source_chain::TargetHeaderChain, + target_chain::{ProvedMessages, SourceHeaderChain}, + InboundLaneData, LaneId, Message, MessageNonce, Parameter as MessagesParameter, +}; +use bp_runtime::{ChainId, POLKADOT_CHAIN_ID, KUSAMA_CHAIN_ID}; +use bridge_runtime_common::messages::{self, MessageBridge, MessageTransaction, ThisChainWithMessages}; +use parity_scale_codec::{Decode, Encode}; +use frame_support::{ + parameter_types, + traits::Get, + weights::{DispatchClass, Weight, WeightToFeePolynomial}, + RuntimeDebug, +}; +use sp_runtime::{traits::Saturating, FixedPointNumber, FixedU128}; +use sp_std::{convert::TryFrom, ops::RangeInclusive}; + +/// Initial value of `KusamaToPolkadotConversionRate` parameter. +pub const INITIAL_KUSAMA_TO_POLKADOT_CONVERSION_RATE: FixedU128 = FixedU128::from_inner(FixedU128::DIV); +/// Initial value of `KusamaFeeMultiplier` parameter. +pub const INITIAL_KUSAMA_FEE_MULTIPLIER: FixedU128 = FixedU128::from_inner(FixedU128::DIV); + +parameter_types! { + /// Kusama (DOT) to Polkadot (KSM) conversion rate. + pub storage KusamaToPolkadotConversionRate: FixedU128 = INITIAL_KUSAMA_TO_POLKADOT_CONVERSION_RATE; + /// Fee multiplier at Kusama. + pub storage KusamaFeeMultiplier: FixedU128 = INITIAL_KUSAMA_FEE_MULTIPLIER; +} + +/// Message payload for Polkadot -> Kusama messages. +pub type ToKusamaMessagePayload = messages::source::FromThisChainMessagePayload; + +/// Message verifier for Polkadot -> Kusama messages. +pub type ToKusamaMessageVerifier = messages::source::FromThisChainMessageVerifier; + +/// Message payload for Kusama -> Polkadot messages. +pub type FromKusamaMessagePayload = messages::target::FromBridgedChainMessagePayload; + +/// Encoded Polkadot Call as it comes from Kusama. +pub type FromKusamaEncodedCall = messages::target::FromBridgedChainEncodedMessageCall; + +/// Call-dispatch based message dispatch for Kusama -> Polkadot messages. +pub type FromKusamaMessageDispatch = messages::target::FromBridgedChainMessageDispatch< + WithKusamaMessageBridge, + crate::Runtime, + pallet_balances::Pallet, + crate::KusamaMessagesDispatchInstance, +>; + +/// Polkadot <-> Kusama message bridge. +#[derive(RuntimeDebug, Clone, Copy)] +pub struct WithKusamaMessageBridge; + +impl MessageBridge for WithKusamaMessageBridge { + const RELAYER_FEE_PERCENT: u32 = 10; + const THIS_CHAIN_ID: ChainId = POLKADOT_CHAIN_ID; + const BRIDGED_CHAIN_ID: ChainId = KUSAMA_CHAIN_ID; + const BRIDGED_MESSAGES_PALLET_NAME: &'static str = bp_kusama::WITH_POLKADOT_MESSAGES_PALLET_NAME; + + type ThisChain = Polkadot; + type BridgedChain = Kusama; + + fn bridged_balance_to_this_balance(bridged_balance: bp_kusama::Balance) -> bp_polkadot::Balance { + bp_polkadot::Balance::try_from(KusamaToPolkadotConversionRate::get().saturating_mul_int(bridged_balance)) + .unwrap_or(bp_polkadot::Balance::MAX) + } +} + +/// Polkadot from messages point of view. +#[derive(RuntimeDebug, Clone, Copy)] +pub struct Polkadot; + +impl messages::ChainWithMessages for Polkadot { + type Hash = bp_polkadot::Hash; + type AccountId = bp_polkadot::AccountId; + type Signer = bp_polkadot::AccountPublic; + type Signature = bp_polkadot::Signature; + type Weight = Weight; + type Balance = bp_polkadot::Balance; +} + +impl ThisChainWithMessages for Polkadot { + type Call = crate::Call; + + fn is_outbound_lane_enabled(lane: &LaneId) -> bool { + *lane == [0, 0, 0, 0] + } + + fn maximal_pending_messages_at_outbound_lane() -> MessageNonce { + bp_kusama::MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE + } + + fn estimate_delivery_confirmation_transaction() -> MessageTransaction { + let inbound_data_size = InboundLaneData::::encoded_size_hint( + bp_polkadot::MAXIMAL_ENCODED_ACCOUNT_ID_SIZE, + 1, + 1, + ) + .unwrap_or(u32::MAX); + + MessageTransaction { + dispatch_weight: bp_polkadot::MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT, + size: inbound_data_size + .saturating_add(bp_kusama::EXTRA_STORAGE_PROOF_SIZE) + .saturating_add(bp_polkadot::TX_EXTRA_BYTES), + } + } + + fn transaction_payment(transaction: MessageTransaction) -> bp_polkadot::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::::next_fee_multiplier()); + let per_byte_fee = crate::TransactionByteFee::get(); + messages::transaction_payment( + bp_polkadot::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic, + per_byte_fee, + multiplier, + |weight| crate::WeightToFee::calc(&weight), + transaction, + ) + } +} + +/// Kusama from messages point of view. +#[derive(RuntimeDebug, Clone, Copy)] +pub struct Kusama; + +impl messages::ChainWithMessages for Kusama { + type Hash = bp_kusama::Hash; + type AccountId = bp_kusama::AccountId; + type Signer = bp_kusama::AccountPublic; + type Signature = bp_kusama::Signature; + type Weight = Weight; + type Balance = bp_kusama::Balance; +} + +impl messages::BridgedChainWithMessages for Kusama { + fn maximal_extrinsic_size() -> u32 { + bp_kusama::max_extrinsic_size() + } + + fn message_weight_limits(_message_payload: &[u8]) -> RangeInclusive { + // we don't want to relay too large messages + keep reserve for future upgrades + let upper_limit = messages::target::maximal_incoming_message_dispatch_weight( + bp_kusama::max_extrinsic_weight(), + ); + + // this bridge may be used to deliver all kind of messages, so we're not making any assumptions about + // minimal dispatch weight here + + 0..=upper_limit + } + + fn estimate_delivery_transaction( + message_payload: &[u8], + include_pay_dispatch_fee_cost: bool, + message_dispatch_weight: Weight, + ) -> MessageTransaction { + 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_kusama::ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT) + .saturating_add(bp_kusama::DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT) + .saturating_sub(if include_pay_dispatch_fee_cost { + 0 + } else { + bp_kusama::PAY_INBOUND_DISPATCH_FEE_WEIGHT + }) + .saturating_add(message_dispatch_weight), + size: message_payload_len + .saturating_add(bp_polkadot::EXTRA_STORAGE_PROOF_SIZE) + .saturating_add(bp_kusama::TX_EXTRA_BYTES), + } + } + + fn transaction_payment(transaction: MessageTransaction) -> bp_kusama::Balance { + // we don't have a direct access to the value of multiplier of Kusama chain + // => it is a messages module parameter + let multiplier = KusamaFeeMultiplier::get(); + let per_byte_fee = bp_kusama::TRANSACTION_BYTE_FEE; + messages::transaction_payment( + bp_kusama::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic, + per_byte_fee, + multiplier, + |weight| bp_kusama::WeightToFee::calc(&weight), + transaction, + ) + } +} + +impl TargetHeaderChain for Kusama { + type Error = &'static str; + type MessagesDeliveryProof = messages::source::FromBridgedChainMessagesDeliveryProof; + + fn verify_message(payload: &ToKusamaMessagePayload) -> Result<(), Self::Error> { + messages::source::verify_chain_message::(payload) + } + + fn verify_messages_delivery_proof( + proof: Self::MessagesDeliveryProof, + ) -> Result<(LaneId, InboundLaneData), Self::Error> { + messages::source::verify_messages_delivery_proof::< + WithKusamaMessageBridge, + Runtime, + crate::KusamaGrandpaInstance, + >(proof) + } +} + +impl SourceHeaderChain for Kusama { + type Error = &'static str; + type MessagesProof = messages::target::FromBridgedChainMessagesProof; + + fn verify_messages_proof( + proof: Self::MessagesProof, + messages_count: u32, + ) -> Result>, Self::Error> { + messages::target::verify_messages_proof::( + proof, + messages_count, + ) + } +} + +/// Polkadot <> Kusama messages pallet parameters. +#[derive(RuntimeDebug, Clone, Encode, Decode, PartialEq, Eq)] +pub enum WithKusamaMessageBridgeParameter { + /// The conversion formula we use is: `PolkadotTokens = KusamaTokens * conversion_rate`. + KusamaToPolkadotConversionRate(FixedU128), + /// Fee multiplier at the Kusama chain. + KusamaFeeMultiplier(FixedU128), +} + +impl MessagesParameter for WithKusamaMessageBridgeParameter { + fn save(&self) { + match *self { + WithKusamaMessageBridgeParameter::KusamaToPolkadotConversionRate(ref conversion_rate) => { + KusamaToPolkadotConversionRate::set(conversion_rate); + }, + WithKusamaMessageBridgeParameter::KusamaFeeMultiplier(ref fee_multiplier) => { + KusamaFeeMultiplier::set(fee_multiplier); + }, + } + } +} + +/// The cost of delivery confirmation transaction. +pub struct GetDeliveryConfirmationTransactionFee; + +impl Get for GetDeliveryConfirmationTransactionFee { + fn get() -> crate::Balance { + ::transaction_payment( + Polkadot::estimate_delivery_confirmation_transaction(), + ) + } +} + +#[cfg(test)] +mod tests { + use crate::*; + use super::*; + + #[test] + fn ensure_polkadot_message_lane_weights_are_correct() { + type Weights = pallet_bridge_messages::weights::RialtoWeight; // TODO: use Polkadot weights + + pallet_bridge_messages::ensure_weights_are_correct::( + bp_polkadot::DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT, + bp_polkadot::ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT, + bp_polkadot::MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT, + bp_polkadot::PAY_INBOUND_DISPATCH_FEE_WEIGHT, + DbWeight::get(), + ); + + let max_incoming_message_proof_size = bp_kusama::EXTRA_STORAGE_PROOF_SIZE.saturating_add( + messages::target::maximal_incoming_message_size(bp_polkadot::max_extrinsic_size()), + ); + pallet_bridge_messages::ensure_able_to_receive_message::( + bp_polkadot::max_extrinsic_size(), + bp_polkadot::max_extrinsic_weight(), + max_incoming_message_proof_size, + messages::target::maximal_incoming_message_dispatch_weight(bp_polkadot::max_extrinsic_weight()), + ); + + let max_incoming_inbound_lane_data_proof_size = bp_messages::InboundLaneData::<()>::encoded_size_hint( + bp_polkadot::MAXIMAL_ENCODED_ACCOUNT_ID_SIZE, + bp_kusama::MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE as _, + bp_kusama::MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE as _, + ) + .unwrap_or(u32::MAX); + pallet_bridge_messages::ensure_able_to_receive_confirmation::( + bp_polkadot::max_extrinsic_size(), + bp_polkadot::max_extrinsic_weight(), + max_incoming_inbound_lane_data_proof_size, + bp_kusama::MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE, + bp_kusama::MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE, + DbWeight::get(), + ); + } +} diff --git a/runtime/polkadot/src/lib.rs b/runtime/polkadot/src/lib.rs index 9593a2519d0c..b34430a4c1ae 100644 --- a/runtime/polkadot/src/lib.rs +++ b/runtime/polkadot/src/lib.rs @@ -88,6 +88,9 @@ pub use sp_runtime::BuildStorage; /// Constant values used within the runtime. use polkadot_runtime_constants::{currency::*, fee::*, time::*}; +// Messaging with Kusama support. +mod kusama_messages; + // Weights used in the runtime. mod weights; @@ -179,7 +182,8 @@ impl Contains for BaseFilter { Call::Crowdloan(_) | Call::BagsList(_) | Call::XcmPallet(_) | - Call::BridgeKusamaGrandpa(_) => true, + Call::BridgeKusamaGrandpa(_) | + Call::BridgeKusamaMessages(_) => true, } } } @@ -1369,6 +1373,66 @@ impl pallet_bridge_grandpa::Config for Runtime { type WeightInfo = pallet_bridge_grandpa::weights::RialtoWeight; // TODO } +parameter_types! { + pub const MaxMessagesToPruneAtOnce: bp_messages::MessageNonce = 8; + pub const MaxUnrewardedRelayerEntriesAtInboundLane: bp_messages::MessageNonce = + bp_polkadot::MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE; + pub const MaxUnconfirmedMessagesAtInboundLane: bp_messages::MessageNonce = + bp_polkadot::MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE; + pub const RootAccountForPayments: Option = None; + pub const KusamaChainId: bp_runtime::ChainId = bp_runtime::KUSAMA_CHAIN_ID; +} + +/// Instance of the messages pallet used to relay messages to/from Kusama chain. +pub type KusamaMessagesInstance = (); + +impl pallet_bridge_messages::Config for Runtime { + type Event = Event; + type WeightInfo = pallet_bridge_messages::weights::RialtoWeight; // TODO + type Parameter = kusama_messages::WithKusamaMessageBridgeParameter; + type MaxMessagesToPruneAtOnce = MaxMessagesToPruneAtOnce; + type MaxUnrewardedRelayerEntriesAtInboundLane = MaxUnrewardedRelayerEntriesAtInboundLane; + type MaxUnconfirmedMessagesAtInboundLane = MaxUnconfirmedMessagesAtInboundLane; + + type OutboundPayload = kusama_messages::ToKusamaMessagePayload; + type OutboundMessageFee = Balance; + + type InboundPayload = kusama_messages::FromKusamaMessagePayload; + type InboundMessageFee = bp_kusama::Balance; + type InboundRelayer = bp_kusama::AccountId; + + type AccountIdConverter = bp_polkadot::AccountIdConverter; + + type TargetHeaderChain = kusama_messages::Kusama; + type LaneMessageVerifier = kusama_messages::ToKusamaMessageVerifier; + type MessageDeliveryAndDispatchPayment = pallet_bridge_messages::instant_payments::InstantCurrencyPayments< + Runtime, + pallet_balances::Pallet, + kusama_messages::GetDeliveryConfirmationTransactionFee, + RootAccountForPayments, + >; + type OnDeliveryConfirmed = (); + + type SourceHeaderChain = kusama_messages::Kusama; + type MessageDispatch = kusama_messages::FromKusamaMessageDispatch; + type BridgedChainId = KusamaChainId; +} + +/// Instance of the dispatch pallet used to dispatch incoming Kusama messages. +pub type KusamaMessagesDispatchInstance = (); + +impl pallet_bridge_dispatch::Config for Runtime { + type Event = Event; + type MessageId = (bp_messages::LaneId, bp_messages::MessageNonce); + type Call = Call; + type CallFilter = frame_support::traits::Everything; + type EncodedCall = kusama_messages::FromKusamaEncodedCall; + type SourceChainAccountId = bp_kusama::AccountId; + type TargetChainAccountPublic = sp_runtime::MultiSigner; + type TargetChainSignature = sp_runtime::MultiSignature; + type AccountIdConverter = bp_polkadot::AccountIdConverter; +} + construct_runtime! { pub enum Runtime where Block = Block, @@ -1464,8 +1528,8 @@ construct_runtime! { // Bridge pallets to bridge with Kusama. BridgeKusamaGrandpa: pallet_bridge_grandpa::{Pallet, Call, Storage, Config} = 110, - //BridgeKusamaMessages: pallet_bridge_messages::{Pallet, Call, Storage, Event, Config} = 111, - //BridgeKusamaMessagesDispatch: pallet_bridge_dispatch::{Pallet, Event} = 112, + BridgeKusamaMessages: pallet_bridge_messages::{Pallet, Call, Storage, Event, Config} = 111, + BridgeKusamaMessagesDispatch: pallet_bridge_dispatch::{Pallet, Event} = 112, } } From e21765957d7aebb3db3534cd3ceebcdfdfeebb9e Mon Sep 17 00:00:00 2001 From: Svyatoslav Nikolsky Date: Tue, 7 Sep 2021 14:54:41 +0300 Subject: [PATCH 03/31] fix compilation --- node/service/src/chain_spec.rs | 34 ++++++++++++++++++++++++++- runtime/rococo/src/bridge_messages.rs | 4 ++-- runtime/rococo/src/lib.rs | 2 ++ 3 files changed, 37 insertions(+), 3 deletions(-) diff --git a/node/service/src/chain_spec.rs b/node/service/src/chain_spec.rs index f53013fe1e6b..78d22d625d12 100644 --- a/node/service/src/chain_spec.rs +++ b/node/service/src/chain_spec.rs @@ -388,6 +388,14 @@ fn polkadot_staging_testnet_config_genesis(wasm_binary: &[u8]) -> polkadot::Gene }, paras: Default::default(), xcm_pallet: Default::default(), + bridge_kusama_grandpa: polkadot_runtime::BridgeKusamaGrandpaConfig { + owner: Some(endowed_accounts[0].clone()), + ..Default::default() + }, + bridge_kusama_messages: polkadot_runtime::BridgeKusamaMessagesConfig { + owner: Some(endowed_accounts[0].clone()), + ..Default::default() + }, } } @@ -768,6 +776,14 @@ fn kusama_staging_testnet_config_genesis(wasm_binary: &[u8]) -> kusama::GenesisC gilt: Default::default(), paras: Default::default(), xcm_pallet: Default::default(), + bridge_polkadot_grandpa: kusama_runtime::BridgePolkadotGrandpaConfig { + owner: Some(endowed_accounts[0].clone()), + ..Default::default() + }, + bridge_polkadot_messages: kusama_runtime::BridgePolkadotMessagesConfig { + owner: Some(endowed_accounts[0].clone()), + ..Default::default() + }, } } @@ -1338,6 +1354,14 @@ pub fn polkadot_testnet_genesis( }, paras: Default::default(), xcm_pallet: Default::default(), + bridge_kusama_grandpa: polkadot_runtime::BridgeKusamaGrandpaConfig { + owner: Some(endowed_accounts[0].clone()), + ..Default::default() + }, + bridge_kusama_messages: polkadot_runtime::BridgeKusamaMessagesConfig { + owner: Some(endowed_accounts[0].clone()), + ..Default::default() + }, } } @@ -1423,8 +1447,16 @@ pub fn kusama_testnet_genesis( config: default_parachains_host_configuration(), }, gilt: Default::default(), - paras: Default::default(), + paras: Default::default() xcm_pallet: Default::default(), + bridge_polkadot_grandpa: kusama_runtime::BridgePolkadotGrandpaConfig { + owner: Some(endowed_accounts[0].clone()), + ..Default::default() + }, + bridge_polkadot_messages: kusama_runtime::BridgePolkadotMessagesConfig { + owner: Some(endowed_accounts[0].clone()), + ..Default::default() + }, } } diff --git a/runtime/rococo/src/bridge_messages.rs b/runtime/rococo/src/bridge_messages.rs index ca18aef8148f..3df72ba842ea 100644 --- a/runtime/rococo/src/bridge_messages.rs +++ b/runtime/rococo/src/bridge_messages.rs @@ -305,7 +305,7 @@ mod at_rococo { const BRIDGED_CHAIN_ID: ChainId = WOCOCO_CHAIN_ID; const RELAYER_FEE_PERCENT: u32 = 10; const BRIDGED_MESSAGES_PALLET_NAME: &'static str = - bp_rococo::WITH_ROCOCO_MESSAGES_PALLET_NAME; + bp_wococo::WITH_WOCOCO_MESSAGES_PALLET_NAME; type ThisChain = RococoAtRococo; type BridgedChain = WococoAtRococo; @@ -356,7 +356,7 @@ mod at_wococo { const BRIDGED_CHAIN_ID: ChainId = ROCOCO_CHAIN_ID; const RELAYER_FEE_PERCENT: u32 = 10; const BRIDGED_MESSAGES_PALLET_NAME: &'static str = - bp_wococo::WITH_WOCOCO_MESSAGES_PALLET_NAME; + bp_rococo::WITH_ROCOCO_MESSAGES_PALLET_NAME; type ThisChain = WococoAtWococo; type BridgedChain = RococoAtWococo; diff --git a/runtime/rococo/src/lib.rs b/runtime/rococo/src/lib.rs index b534311bca84..a63a6bb32238 100644 --- a/runtime/rococo/src/lib.rs +++ b/runtime/rococo/src/lib.rs @@ -821,6 +821,7 @@ impl pallet_bridge_messages::Config for Runt type SourceHeaderChain = crate::bridge_messages::RococoAtWococo; type MessageDispatch = crate::bridge_messages::FromRococoMessageDispatch; + type BridgedChainId = RococoChainId; } // Instance that is "deployed" at Rococo chain. Responsible for sending Rococo -> Wococo messages @@ -858,6 +859,7 @@ impl pallet_bridge_messages::Config for Runt type SourceHeaderChain = crate::bridge_messages::WococoAtRococo; type MessageDispatch = crate::bridge_messages::FromWococoMessageDispatch; + type BridgedChainId = WococoChainId; } parameter_types! { From 99851955c3c6b65ca49554b6560538f78da83a8e Mon Sep 17 00:00:00 2001 From: Svyatoslav Nikolsky Date: Thu, 9 Sep 2021 12:25:36 +0300 Subject: [PATCH 04/31] add missed runtime APIs for messaging --- runtime/kusama/src/lib.rs | 47 +++++++++++++++++++++++++++++++++++++ runtime/polkadot/src/lib.rs | 47 +++++++++++++++++++++++++++++++++++++ 2 files changed, 94 insertions(+) diff --git a/runtime/kusama/src/lib.rs b/runtime/kusama/src/lib.rs index ef1c4d2acc11..b0c577e2fd91 100644 --- a/runtime/kusama/src/lib.rs +++ b/runtime/kusama/src/lib.rs @@ -45,6 +45,7 @@ use runtime_parachains::{ use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId; use beefy_primitives::crypto::AuthorityId as BeefyId; +use bridge_runtime_common::messages::{source::estimate_message_dispatch_and_delivery_fee, MessageBridge}; use frame_support::{ construct_runtime, parameter_types, traits::{ @@ -1888,6 +1889,52 @@ sp_api::impl_runtime_apis! { } } + impl bp_polkadot::ToPolkadotOutboundLaneApi for Runtime { + fn estimate_message_delivery_and_dispatch_fee( + _lane_id: bp_messages::LaneId, + payload: polkadot_messages::ToPolkadotMessagePayload, + ) -> Option { + estimate_message_dispatch_and_delivery_fee::( + &payload, + polkadot_messages::WithPolkadotMessageBridge::RELAYER_FEE_PERCENT, + ).ok() + } + + fn message_details( + lane: bp_messages::LaneId, + begin: bp_messages::MessageNonce, + end: bp_messages::MessageNonce, + ) -> Vec> { + bridge_runtime_common::messages_api::outbound_message_details::< + Runtime, + PolkadotMessagesInstance, + polkadot_messages::WithPolkadotMessageBridge, + >(lane, begin, end) + } + + fn latest_received_nonce(lane: bp_messages::LaneId) -> bp_messages::MessageNonce { + BridgePolkadotMessages::outbound_latest_received_nonce(lane) + } + + fn latest_generated_nonce(lane: bp_messages::LaneId) -> bp_messages::MessageNonce { + BridgePolkadotMessages::outbound_latest_generated_nonce(lane) + } + } + + impl bp_polkadot::FromPolkadotInboundLaneApi for Runtime { + fn latest_received_nonce(lane: bp_messages::LaneId) -> bp_messages::MessageNonce { + BridgePolkadotMessages::inbound_latest_received_nonce(lane) + } + + fn latest_confirmed_nonce(lane: bp_messages::LaneId) -> bp_messages::MessageNonce { + BridgePolkadotMessages::inbound_latest_confirmed_nonce(lane) + } + + fn unrewarded_relayers_state(lane: bp_messages::LaneId) -> bp_messages::UnrewardedRelayersState { + BridgePolkadotMessages::inbound_unrewarded_relayers_state(lane) + } + } + impl fg_primitives::GrandpaApi for Runtime { fn grandpa_authorities() -> Vec<(GrandpaId, u64)> { Grandpa::grandpa_authorities() diff --git a/runtime/polkadot/src/lib.rs b/runtime/polkadot/src/lib.rs index b34430a4c1ae..c908b4c88347 100644 --- a/runtime/polkadot/src/lib.rs +++ b/runtime/polkadot/src/lib.rs @@ -37,6 +37,7 @@ use runtime_parachains::{ use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId; use beefy_primitives::crypto::AuthorityId as BeefyId; +use bridge_runtime_common::messages::{source::estimate_message_dispatch_and_delivery_fee, MessageBridge}; use frame_support::{ construct_runtime, parameter_types, traits::{ @@ -2033,6 +2034,52 @@ sp_api::impl_runtime_apis! { } } + impl bp_kusama::ToKusamaOutboundLaneApi for Runtime { + fn estimate_message_delivery_and_dispatch_fee( + _lane_id: bp_messages::LaneId, + payload: kusama_messages::ToKusamaMessagePayload, + ) -> Option { + estimate_message_dispatch_and_delivery_fee::( + &payload, + kusama_messages::WithKusamaMessageBridge::RELAYER_FEE_PERCENT, + ).ok() + } + + fn message_details( + lane: bp_messages::LaneId, + begin: bp_messages::MessageNonce, + end: bp_messages::MessageNonce, + ) -> Vec> { + bridge_runtime_common::messages_api::outbound_message_details::< + Runtime, + KusamaMessagesInstance, + kusama_messages::WithKusamaMessageBridge, + >(lane, begin, end) + } + + fn latest_received_nonce(lane: bp_messages::LaneId) -> bp_messages::MessageNonce { + BridgeKusamaMessages::outbound_latest_received_nonce(lane) + } + + fn latest_generated_nonce(lane: bp_messages::LaneId) -> bp_messages::MessageNonce { + BridgeKusamaMessages::outbound_latest_generated_nonce(lane) + } + } + + impl bp_kusama::FromKusamaInboundLaneApi for Runtime { + fn latest_received_nonce(lane: bp_messages::LaneId) -> bp_messages::MessageNonce { + BridgeKusamaMessages::inbound_latest_received_nonce(lane) + } + + fn latest_confirmed_nonce(lane: bp_messages::LaneId) -> bp_messages::MessageNonce { + BridgeKusamaMessages::inbound_latest_confirmed_nonce(lane) + } + + fn unrewarded_relayers_state(lane: bp_messages::LaneId) -> bp_messages::UnrewardedRelayersState { + BridgeKusamaMessages::inbound_unrewarded_relayers_state(lane) + } + } + impl fg_primitives::GrandpaApi for Runtime { fn grandpa_authorities() -> Vec<(GrandpaId, u64)> { Grandpa::grandpa_authorities() From 7f0a28d447de0c270e754397279686a63f0fa4a5 Mon Sep 17 00:00:00 2001 From: Svyatoslav Nikolsky Date: Wed, 22 Sep 2021 13:31:09 +0300 Subject: [PATCH 05/31] only accept messages from given user --- Cargo.lock | 2 + runtime/kusama/Cargo.toml | 1 + runtime/kusama/src/polkadot_messages.rs | 96 +++++++++++++++++++++++-- runtime/polkadot/Cargo.toml | 1 + runtime/polkadot/src/kusama_messages.rs | 96 +++++++++++++++++++++++-- 5 files changed, 182 insertions(+), 14 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index fe9a6167f01c..a5b1a03f794a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3530,6 +3530,7 @@ dependencies = [ "beefy-primitives", "bitvec", "bp-kusama", + "bp-message-dispatch", "bp-messages", "bp-polkadot", "bp-runtime", @@ -7299,6 +7300,7 @@ dependencies = [ "beefy-primitives", "bitvec", "bp-kusama", + "bp-message-dispatch", "bp-messages", "bp-polkadot", "bp-runtime", diff --git a/runtime/kusama/Cargo.toml b/runtime/kusama/Cargo.toml index 11fa425a8fe4..8ab1061ed8cf 100644 --- a/runtime/kusama/Cargo.toml +++ b/runtime/kusama/Cargo.toml @@ -103,6 +103,7 @@ xcm-executor = { package = "xcm-executor", path = "../../xcm/xcm-executor", defa xcm-builder = { package = "xcm-builder", path = "../../xcm/xcm-builder", default-features = false } [dev-dependencies] +bp-message-dispatch = { path = "../../bridges/primitives/message-dispatch" } hex-literal = "0.3.4" tiny-keccak = "2.0.2" keyring = { package = "sp-keyring", git = "https://github.com/paritytech/substrate", branch = "master" } diff --git a/runtime/kusama/src/polkadot_messages.rs b/runtime/kusama/src/polkadot_messages.rs index 400f0bbcb8c6..f933b6d5d3ee 100644 --- a/runtime/kusama/src/polkadot_messages.rs +++ b/runtime/kusama/src/polkadot_messages.rs @@ -19,9 +19,9 @@ use crate::Runtime; use bp_messages::{ - source_chain::TargetHeaderChain, + source_chain::{LaneMessageVerifier, TargetHeaderChain}, target_chain::{ProvedMessages, SourceHeaderChain}, - InboundLaneData, LaneId, Message, MessageNonce, Parameter as MessagesParameter, + InboundLaneData, LaneId, Message, MessageNonce, OutboundLaneData, Parameter as MessagesParameter, }; use bp_runtime::{ChainId, KUSAMA_CHAIN_ID, POLKADOT_CHAIN_ID}; use bridge_runtime_common::messages::{self, MessageBridge, MessageTransaction, ThisChainWithMessages}; @@ -32,6 +32,7 @@ use frame_support::{ weights::{DispatchClass, Weight, WeightToFeePolynomial}, RuntimeDebug, }; +use frame_system::RawOrigin; use sp_runtime::{traits::Saturating, FixedPointNumber, FixedU128}; use sp_std::{convert::TryFrom, ops::RangeInclusive}; @@ -45,14 +46,13 @@ parameter_types! { pub storage PolkadotToKusamaConversionRate: FixedU128 = INITIAL_POLKADOT_TO_KUSAMA_CONVERSION_RATE; /// Fee multiplier at Polkadot. pub storage PolkadotFeeMultiplier: FixedU128 = INITIAL_POLKADOT_FEE_MULTIPLIER; + /// The only Kusama account that is allowed to send messages to Polkadot. + pub storage AllowedMessageSender: bp_kusama::AccountId = Default::default(); } /// Message payload for Kusama -> Polkadot messages. pub type ToPolkadotMessagePayload = messages::source::FromThisChainMessagePayload; -/// Message verifier for Kusama -> Polkadot messages. -pub type ToPolkadotMessageVerifier = messages::source::FromThisChainMessageVerifier; - /// Message payload for Polkadot -> Kusama messages. pub type FromPolkadotMessagePayload = messages::target::FromBridgedChainMessagePayload; @@ -67,6 +67,44 @@ pub type FromPolkadotMessageDispatch = messages::target::FromBridgedChainMessage crate::PolkadotMessagesDispatchInstance, >; +/// Error that happens when message is sent by anyone but `AllowedMessageSender`. +const NOT_ALLOWED_MESSAGE_SENDER: &str = "Cannot accept message from this account"; + +/// Message verifier for Kusama -> Polkadot messages. +#[derive(RuntimeDebug)] +pub struct ToPolkadotMessageVerifier; + +impl LaneMessageVerifier< + bp_kusama::AccountId, + ToPolkadotMessagePayload, + bp_kusama::Balance, +> for ToPolkadotMessageVerifier { + type Error = &'static str; + + fn verify_message( + submitter: &RawOrigin, + delivery_and_dispatch_fee: &bp_kusama::Balance, + lane: &LaneId, + lane_outbound_data: &OutboundLaneData, + payload: &ToPolkadotMessagePayload, + ) -> Result<(), Self::Error> { + // we only allow messages to be sent by given account + let allowed_sender = AllowedMessageSender::get(); + if *submitter != RawOrigin::Signed(allowed_sender) { + return Err(NOT_ALLOWED_MESSAGE_SENDER); + } + + // perform other checks + messages::source::FromThisChainMessageVerifier::::verify_message( + submitter, + delivery_and_dispatch_fee, + lane, + lane_outbound_data, + payload, + ) + } +} + /// Kusama <-> Polkadot message bridge. #[derive(RuntimeDebug, Clone, Copy)] pub struct WithPolkadotMessageBridge; @@ -253,6 +291,8 @@ pub enum WithPolkadotMessageBridgeParameter { PolkadotToKusamaConversionRate(FixedU128), /// Fee multiplier at the Polkadot chain. PolkadotFeeMultiplier(FixedU128), + /// The only Kusama account that is allowed to send messages to Polkadot. + AllowedMessageSender(bp_kusama::AccountId), } impl MessagesParameter for WithPolkadotMessageBridgeParameter { @@ -264,6 +304,9 @@ impl MessagesParameter for WithPolkadotMessageBridgeParameter { WithPolkadotMessageBridgeParameter::PolkadotFeeMultiplier(ref fee_multiplier) => { PolkadotFeeMultiplier::set(fee_multiplier); }, + WithPolkadotMessageBridgeParameter::AllowedMessageSender(ref message_sender) => { + AllowedMessageSender::set(message_sender); + } } } } @@ -281,6 +324,7 @@ impl Get for GetDeliveryConfirmationTransactionFee { #[cfg(test)] mod tests { + use runtime_common::RocksDbWeight; use crate::*; use super::*; @@ -293,7 +337,7 @@ mod tests { bp_kusama::ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT, bp_kusama::MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT, bp_kusama::PAY_INBOUND_DISPATCH_FEE_WEIGHT, - DbWeight::get(), + RocksDbWeight::get(), ); let max_incoming_message_proof_size = bp_polkadot::EXTRA_STORAGE_PROOF_SIZE.saturating_add( @@ -318,7 +362,45 @@ mod tests { max_incoming_inbound_lane_data_proof_size, bp_polkadot::MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE, bp_polkadot::MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE, - DbWeight::get(), + RocksDbWeight::get(), ); } + + #[test] + fn message_by_invalid_submitter_are_rejected() { + sp_io::TestExternalities::new(Default::default()).execute_with(|| { + fn message_payload(sender: bp_kusama::AccountId) -> ToPolkadotMessagePayload { + bp_message_dispatch::MessagePayload { + spec_version: 1, + weight: 100, + origin: bp_message_dispatch::CallOrigin::SourceAccount(sender), + dispatch_fee_payment: bp_runtime::messages::DispatchFeePayment::AtSourceChain, + call: vec![42], + } + } + + let invalid_sender = bp_kusama::AccountId::from([1u8; 32]); + let valid_sender = AllowedMessageSender::get(); + assert_eq!( + ToPolkadotMessageVerifier::verify_message( + &RawOrigin::Signed(invalid_sender.clone()), + &bp_kusama::Balance::MAX, + &Default::default(), + &Default::default(), + &message_payload(invalid_sender), + ), + Err(NOT_ALLOWED_MESSAGE_SENDER), + ); + assert_eq!( + ToPolkadotMessageVerifier::verify_message( + &RawOrigin::Signed(valid_sender.clone()), + &bp_kusama::Balance::MAX, + &Default::default(), + &Default::default(), + &message_payload(valid_sender), + ), + Ok(()), + ); + }); + } } diff --git a/runtime/polkadot/Cargo.toml b/runtime/polkadot/Cargo.toml index 70bd01d56e2f..3b57814ddffc 100644 --- a/runtime/polkadot/Cargo.toml +++ b/runtime/polkadot/Cargo.toml @@ -98,6 +98,7 @@ xcm-executor = { package = "xcm-executor", path = "../../xcm/xcm-executor", defa xcm-builder = { package = "xcm-builder", path = "../../xcm/xcm-builder", default-features = false } [dev-dependencies] +bp-message-dispatch = { path = "../../bridges/primitives/message-dispatch" } hex-literal = "0.3.4" tiny-keccak = "2.0.2" keyring = { package = "sp-keyring", git = "https://github.com/paritytech/substrate", branch = "master" } diff --git a/runtime/polkadot/src/kusama_messages.rs b/runtime/polkadot/src/kusama_messages.rs index f7b577f49d23..9acfe2fbfd09 100644 --- a/runtime/polkadot/src/kusama_messages.rs +++ b/runtime/polkadot/src/kusama_messages.rs @@ -19,9 +19,9 @@ use crate::Runtime; use bp_messages::{ - source_chain::TargetHeaderChain, + source_chain::{LaneMessageVerifier, TargetHeaderChain}, target_chain::{ProvedMessages, SourceHeaderChain}, - InboundLaneData, LaneId, Message, MessageNonce, Parameter as MessagesParameter, + InboundLaneData, LaneId, Message, MessageNonce, OutboundLaneData, Parameter as MessagesParameter, }; use bp_runtime::{ChainId, POLKADOT_CHAIN_ID, KUSAMA_CHAIN_ID}; use bridge_runtime_common::messages::{self, MessageBridge, MessageTransaction, ThisChainWithMessages}; @@ -32,6 +32,7 @@ use frame_support::{ weights::{DispatchClass, Weight, WeightToFeePolynomial}, RuntimeDebug, }; +use frame_system::RawOrigin; use sp_runtime::{traits::Saturating, FixedPointNumber, FixedU128}; use sp_std::{convert::TryFrom, ops::RangeInclusive}; @@ -45,14 +46,13 @@ parameter_types! { pub storage KusamaToPolkadotConversionRate: FixedU128 = INITIAL_KUSAMA_TO_POLKADOT_CONVERSION_RATE; /// Fee multiplier at Kusama. pub storage KusamaFeeMultiplier: FixedU128 = INITIAL_KUSAMA_FEE_MULTIPLIER; + /// The only Polkadot account that is allowed to send messages to Kusama. + pub storage AllowedMessageSender: bp_polkadot::AccountId = Default::default(); } /// Message payload for Polkadot -> Kusama messages. pub type ToKusamaMessagePayload = messages::source::FromThisChainMessagePayload; -/// Message verifier for Polkadot -> Kusama messages. -pub type ToKusamaMessageVerifier = messages::source::FromThisChainMessageVerifier; - /// Message payload for Kusama -> Polkadot messages. pub type FromKusamaMessagePayload = messages::target::FromBridgedChainMessagePayload; @@ -67,6 +67,44 @@ pub type FromKusamaMessageDispatch = messages::target::FromBridgedChainMessageDi crate::KusamaMessagesDispatchInstance, >; +/// Error that happens when message is sent by anyone but `AllowedMessageSender`. +const NOT_ALLOWED_MESSAGE_SENDER: &str = "Cannot accept message from this account"; + +/// Message verifier for Polkadot -> Kusama messages. +#[derive(RuntimeDebug)] +pub struct ToKusamaMessageVerifier; + +impl LaneMessageVerifier< + bp_polkadot::AccountId, + ToKusamaMessagePayload, + bp_polkadot::Balance, +> for ToKusamaMessageVerifier { + type Error = &'static str; + + fn verify_message( + submitter: &RawOrigin, + delivery_and_dispatch_fee: &bp_polkadot::Balance, + lane: &LaneId, + lane_outbound_data: &OutboundLaneData, + payload: &ToKusamaMessagePayload, + ) -> Result<(), Self::Error> { + // we only allow messages to be sent by given account + let allowed_sender = AllowedMessageSender::get(); + if *submitter != RawOrigin::Signed(allowed_sender) { + return Err(NOT_ALLOWED_MESSAGE_SENDER); + } + + // perform other checks + messages::source::FromThisChainMessageVerifier::::verify_message( + submitter, + delivery_and_dispatch_fee, + lane, + lane_outbound_data, + payload, + ) + } +} + /// Polkadot <-> Kusama message bridge. #[derive(RuntimeDebug, Clone, Copy)] pub struct WithKusamaMessageBridge; @@ -253,6 +291,8 @@ pub enum WithKusamaMessageBridgeParameter { KusamaToPolkadotConversionRate(FixedU128), /// Fee multiplier at the Kusama chain. KusamaFeeMultiplier(FixedU128), + /// The only Polkadot account that is allowed to send messages to Kusama. + AllowedMessageSender(bp_polkadot::AccountId), } impl MessagesParameter for WithKusamaMessageBridgeParameter { @@ -264,6 +304,9 @@ impl MessagesParameter for WithKusamaMessageBridgeParameter { WithKusamaMessageBridgeParameter::KusamaFeeMultiplier(ref fee_multiplier) => { KusamaFeeMultiplier::set(fee_multiplier); }, + WithKusamaMessageBridgeParameter::AllowedMessageSender(ref message_sender) => { + AllowedMessageSender::set(message_sender); + } } } } @@ -281,6 +324,7 @@ impl Get for GetDeliveryConfirmationTransactionFee { #[cfg(test)] mod tests { + use runtime_common::RocksDbWeight; use crate::*; use super::*; @@ -293,7 +337,7 @@ mod tests { bp_polkadot::ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT, bp_polkadot::MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT, bp_polkadot::PAY_INBOUND_DISPATCH_FEE_WEIGHT, - DbWeight::get(), + RocksDbWeight::get(), ); let max_incoming_message_proof_size = bp_kusama::EXTRA_STORAGE_PROOF_SIZE.saturating_add( @@ -318,7 +362,45 @@ mod tests { max_incoming_inbound_lane_data_proof_size, bp_kusama::MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE, bp_kusama::MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE, - DbWeight::get(), + RocksDbWeight::get(), ); } + + #[test] + fn message_by_invalid_submitter_are_rejected() { + sp_io::TestExternalities::new(Default::default()).execute_with(|| { + fn message_payload(sender: bp_polkadot::AccountId) -> ToKusamaMessagePayload { + bp_message_dispatch::MessagePayload { + spec_version: 1, + weight: 100, + origin: bp_message_dispatch::CallOrigin::SourceAccount(sender), + dispatch_fee_payment: bp_runtime::messages::DispatchFeePayment::AtSourceChain, + call: vec![42], + } + } + + let invalid_sender = bp_polkadot::AccountId::from([1u8; 32]); + let valid_sender = AllowedMessageSender::get(); + assert_eq!( + ToKusamaMessageVerifier::verify_message( + &RawOrigin::Signed(invalid_sender.clone()), + &bp_polkadot::Balance::MAX, + &Default::default(), + &Default::default(), + &message_payload(invalid_sender), + ), + Err(NOT_ALLOWED_MESSAGE_SENDER), + ); + assert_eq!( + ToKusamaMessageVerifier::verify_message( + &RawOrigin::Signed(valid_sender.clone()), + &bp_polkadot::Balance::MAX, + &Default::default(), + &Default::default(), + &message_payload(valid_sender), + ), + Ok(()), + ); + }); + } } From e42b0b3f68b86f3c4320e74e2dc7da66eb23f8a7 Mon Sep 17 00:00:00 2001 From: Svyatoslav Nikolsky Date: Wed, 22 Sep 2021 13:42:44 +0300 Subject: [PATCH 06/31] only dispatch balances::transfer messages --- runtime/kusama/src/lib.rs | 2 +- runtime/kusama/src/polkadot_messages.rs | 13 +++++++++++-- runtime/polkadot/src/kusama_messages.rs | 13 +++++++++++-- runtime/polkadot/src/lib.rs | 2 +- 4 files changed, 24 insertions(+), 6 deletions(-) diff --git a/runtime/kusama/src/lib.rs b/runtime/kusama/src/lib.rs index b0c577e2fd91..381041dff568 100644 --- a/runtime/kusama/src/lib.rs +++ b/runtime/kusama/src/lib.rs @@ -1459,7 +1459,7 @@ impl pallet_bridge_dispatch::Config for Runtim type Event = Event; type MessageId = (bp_messages::LaneId, bp_messages::MessageNonce); type Call = Call; - type CallFilter = frame_support::traits::Everything; + type CallFilter = polkadot_messages::FromPolkadotCallFilter; type EncodedCall = polkadot_messages::FromPolkadotEncodedCall; type SourceChainAccountId = bp_polkadot::AccountId; type TargetChainAccountPublic = sp_runtime::MultiSigner; diff --git a/runtime/kusama/src/polkadot_messages.rs b/runtime/kusama/src/polkadot_messages.rs index f933b6d5d3ee..8e0ebb0648a4 100644 --- a/runtime/kusama/src/polkadot_messages.rs +++ b/runtime/kusama/src/polkadot_messages.rs @@ -16,7 +16,7 @@ //! Over-bridge messaging support for Kusama <> Polkadot bridge. -use crate::Runtime; +use crate::{Call, Runtime}; use bp_messages::{ source_chain::{LaneMessageVerifier, TargetHeaderChain}, @@ -28,7 +28,7 @@ use bridge_runtime_common::messages::{self, MessageBridge, MessageTransaction, T use parity_scale_codec::{Decode, Encode}; use frame_support::{ parameter_types, - traits::Get, + traits::{Contains, Get}, weights::{DispatchClass, Weight, WeightToFeePolynomial}, RuntimeDebug, }; @@ -322,6 +322,15 @@ impl Get for GetDeliveryConfirmationTransactionFee { } } +/// Call filter for messages that are coming from Polkadot. +pub struct FromPolkadotCallFilter; + +impl Contains for FromPolkadotCallFilter { + fn contains(call: &Call) -> bool { + matches!(call, Call::Balances(pallet_balances::Call::transfer(..))) + } +} + #[cfg(test)] mod tests { use runtime_common::RocksDbWeight; diff --git a/runtime/polkadot/src/kusama_messages.rs b/runtime/polkadot/src/kusama_messages.rs index 9acfe2fbfd09..8518ac2cf436 100644 --- a/runtime/polkadot/src/kusama_messages.rs +++ b/runtime/polkadot/src/kusama_messages.rs @@ -16,7 +16,7 @@ //! Over-bridge messaging support for Polkadot <> Kusama bridge. -use crate::Runtime; +use crate::{Call, Runtime}; use bp_messages::{ source_chain::{LaneMessageVerifier, TargetHeaderChain}, @@ -28,7 +28,7 @@ use bridge_runtime_common::messages::{self, MessageBridge, MessageTransaction, T use parity_scale_codec::{Decode, Encode}; use frame_support::{ parameter_types, - traits::Get, + traits::{Contains, Get}, weights::{DispatchClass, Weight, WeightToFeePolynomial}, RuntimeDebug, }; @@ -322,6 +322,15 @@ impl Get for GetDeliveryConfirmationTransactionFee { } } +/// Call filter for messages that are coming from Kusama. +pub struct FromKusamaCallFilter; + +impl Contains for FromKusamaCallFilter { + fn contains(call: &Call) -> bool { + matches!(call, Call::Balances(pallet_balances::Call::transfer(..))) + } +} + #[cfg(test)] mod tests { use runtime_common::RocksDbWeight; diff --git a/runtime/polkadot/src/lib.rs b/runtime/polkadot/src/lib.rs index c908b4c88347..458e4a6a1e16 100644 --- a/runtime/polkadot/src/lib.rs +++ b/runtime/polkadot/src/lib.rs @@ -1426,7 +1426,7 @@ impl pallet_bridge_dispatch::Config for Runtime type Event = Event; type MessageId = (bp_messages::LaneId, bp_messages::MessageNonce); type Call = Call; - type CallFilter = frame_support::traits::Everything; + type CallFilter = kusama_messages::FromKusamaCallFilter; type EncodedCall = kusama_messages::FromKusamaEncodedCall; type SourceChainAccountId = bp_kusama::AccountId; type TargetChainAccountPublic = sp_runtime::MultiSigner; From 8111117b8800526d916cc3a8ae7b3db6fd57c80a Mon Sep 17 00:00:00 2001 From: Svyatoslav Nikolsky Date: Fri, 22 Oct 2021 13:37:05 +0300 Subject: [PATCH 07/31] reject all inbound messages except coming vial lane 00000000 --- runtime/kusama/src/polkadot_messages.rs | 63 +++++++++++++++++++++++-- runtime/polkadot/src/kusama_messages.rs | 63 +++++++++++++++++++++++-- 2 files changed, 118 insertions(+), 8 deletions(-) diff --git a/runtime/kusama/src/polkadot_messages.rs b/runtime/kusama/src/polkadot_messages.rs index 8e0ebb0648a4..6da1a09768f6 100644 --- a/runtime/kusama/src/polkadot_messages.rs +++ b/runtime/kusama/src/polkadot_messages.rs @@ -69,6 +69,8 @@ pub type FromPolkadotMessageDispatch = messages::target::FromBridgedChainMessage /// Error that happens when message is sent by anyone but `AllowedMessageSender`. const NOT_ALLOWED_MESSAGE_SENDER: &str = "Cannot accept message from this account"; +/// Error that happens when we are receiving incoming message via unexpected lane. +const INBOUND_LANE_DISABLED: &str = "The inbound message lane is disaled."; /// Message verifier for Kusama -> Polkadot messages. #[derive(RuntimeDebug)] @@ -277,11 +279,23 @@ impl SourceHeaderChain for Polkadot { proof: Self::MessagesProof, messages_count: u32, ) -> Result>, Self::Error> { - messages::target::verify_messages_proof::( - proof, - messages_count, - ) + messages::target::verify_messages_proof::< + WithPolkadotMessageBridge, + Runtime, + crate::PolkadotGrandpaInstance, + >(proof, messages_count).and_then(verify_inbound_messages_lane) + } +} + +/// Verify that lanes of inbound messages are enabled. +fn verify_inbound_messages_lane( + messages: ProvedMessages>, +) -> Result>, &'static str> { + let allowed_incoming_lanes = [[0, 0, 0, 0]]; + if messages.keys().any(|lane_id| !allowed_incoming_lanes.contains(lane_id)) { + return Err(INBOUND_LANE_DISABLED); } + Ok(messages) } /// Kusama <> Polkadot messages pallet parameters. @@ -333,6 +347,7 @@ impl Contains for FromPolkadotCallFilter { #[cfg(test)] mod tests { + use bp_messages::{target_chain::ProvedLaneMessages, MessageData, MessageKey}; use runtime_common::RocksDbWeight; use crate::*; use super::*; @@ -412,4 +427,44 @@ mod tests { ); }); } + + fn proved_messages(lane_id: LaneId) -> ProvedMessages> { + vec![ + ( + lane_id, + ProvedLaneMessages { + lane_state: None, + messages: vec![Message { + key: MessageKey { lane_id, nonce: 0 }, + data: MessageData { payload: vec![], fee: 0 }, + }], + }, + ) + ].into_iter().collect() + } + + #[test] + fn verify_inbound_messages_lane_succeeds() { + assert_eq!( + verify_inbound_messages_lane(proved_messages([0, 0, 0, 0])), + Ok(proved_messages([0, 0, 0, 0])), + ); + } + + #[test] + fn verify_inbound_messages_lane_fails() { + assert_eq!( + verify_inbound_messages_lane(proved_messages([0, 0, 0, 1])), + Err(INBOUND_LANE_DISABLED), + ); + + let proved_messages = proved_messages([0, 0, 0, 0]) + .into_iter() + .chain(proved_messages([0, 0, 0, 1])) + .collect(); + assert_eq!( + verify_inbound_messages_lane(proved_messages), + Err(INBOUND_LANE_DISABLED), + ); + } } diff --git a/runtime/polkadot/src/kusama_messages.rs b/runtime/polkadot/src/kusama_messages.rs index 8518ac2cf436..5f5bbec15827 100644 --- a/runtime/polkadot/src/kusama_messages.rs +++ b/runtime/polkadot/src/kusama_messages.rs @@ -69,6 +69,8 @@ pub type FromKusamaMessageDispatch = messages::target::FromBridgedChainMessageDi /// Error that happens when message is sent by anyone but `AllowedMessageSender`. const NOT_ALLOWED_MESSAGE_SENDER: &str = "Cannot accept message from this account"; +/// Error that happens when we are receiving incoming message via unexpected lane. +const INBOUND_LANE_DISABLED: &str = "The inbound message lane is disaled."; /// Message verifier for Polkadot -> Kusama messages. #[derive(RuntimeDebug)] @@ -277,11 +279,23 @@ impl SourceHeaderChain for Kusama { proof: Self::MessagesProof, messages_count: u32, ) -> Result>, Self::Error> { - messages::target::verify_messages_proof::( - proof, - messages_count, - ) + messages::target::verify_messages_proof::< + WithKusamaMessageBridge, + Runtime, + crate::KusamaGrandpaInstance, + >(proof, messages_count).and_then(verify_inbound_messages_lane) + } +} + +/// Verify that lanes of inbound messages are enabled. +fn verify_inbound_messages_lane( + messages: ProvedMessages>, +) -> Result>, &'static str> { + let allowed_incoming_lanes = [[0, 0, 0, 0]]; + if messages.keys().any(|lane_id| !allowed_incoming_lanes.contains(lane_id)) { + return Err(INBOUND_LANE_DISABLED); } + Ok(messages) } /// Polkadot <> Kusama messages pallet parameters. @@ -333,6 +347,7 @@ impl Contains for FromKusamaCallFilter { #[cfg(test)] mod tests { + use bp_messages::{target_chain::ProvedLaneMessages, MessageData, MessageKey}; use runtime_common::RocksDbWeight; use crate::*; use super::*; @@ -412,4 +427,44 @@ mod tests { ); }); } + + fn proved_messages(lane_id: LaneId) -> ProvedMessages> { + vec![ + ( + lane_id, + ProvedLaneMessages { + lane_state: None, + messages: vec![Message { + key: MessageKey { lane_id, nonce: 0 }, + data: MessageData { payload: vec![], fee: 0 }, + }], + }, + ) + ].into_iter().collect() + } + + #[test] + fn verify_inbound_messages_lane_succeeds() { + assert_eq!( + verify_inbound_messages_lane(proved_messages([0, 0, 0, 0])), + Ok(proved_messages([0, 0, 0, 0])), + ); + } + + #[test] + fn verify_inbound_messages_lane_fails() { + assert_eq!( + verify_inbound_messages_lane(proved_messages([0, 0, 0, 1])), + Err(INBOUND_LANE_DISABLED), + ); + + let proved_messages = proved_messages([0, 0, 0, 0]) + .into_iter() + .chain(proved_messages([0, 0, 0, 1])) + .collect(); + assert_eq!( + verify_inbound_messages_lane(proved_messages), + Err(INBOUND_LANE_DISABLED), + ); + } } From 6240a8442a2c8f58b258ecdfd752095357f45fc7 Mon Sep 17 00:00:00 2001 From: Svyatoslav Nikolsky Date: Thu, 27 Jan 2022 17:40:27 +0300 Subject: [PATCH 08/31] post-merge fix --- bridges/primitives/polkadot-core/src/lib.rs | 33 --------- node/service/src/chain_spec.rs | 2 +- runtime/kusama/Cargo.toml | 1 - runtime/kusama/src/lib.rs | 39 +++-------- runtime/kusama/src/polkadot_messages.rs | 78 +++++++++++++-------- runtime/polkadot/src/kusama_messages.rs | 78 +++++++++++++-------- runtime/polkadot/src/lib.rs | 39 +++-------- runtime/rococo/src/bridge_messages.rs | 4 +- runtime/rococo/src/lib.rs | 2 - 9 files changed, 119 insertions(+), 157 deletions(-) diff --git a/bridges/primitives/polkadot-core/src/lib.rs b/bridges/primitives/polkadot-core/src/lib.rs index 3a3cba6ba854..4c0a450eb719 100644 --- a/bridges/primitives/polkadot-core/src/lib.rs +++ b/bridges/primitives/polkadot-core/src/lib.rs @@ -170,39 +170,6 @@ pub const DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT: Weight = 1_500_000_000; /// transactions cheaper. pub const PAY_INBOUND_DISPATCH_FEE_WEIGHT: Weight = 600_000_000; -/// Maximal weight of single message delivery confirmation transaction on Polkadot-like chain. -/// -/// This value is a result of `pallet_bridge_messages::Pallet::receive_messages_delivery_proof` weight formula -/// computation for the case when single message is confirmed. The result then must be rounded up to account possible -/// future runtime upgrades. -pub const MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT: Weight = 2_000_000_000; - -/// Increase of delivery transaction weight on Polkadot-like chain with every additional message byte. -/// -/// This value is a result of `pallet_bridge_messages::WeightInfoExt::storage_proof_size_overhead(1)` call. The -/// result then must be rounded up to account possible future runtime upgrades. -pub const ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT: Weight = 25_000; - -/// Maximal number of bytes, included in the signed Polkadot-like transaction apart from the encoded call itself. -/// -/// Can be computed by subtracting encoded call size from raw transaction size. -pub const TX_EXTRA_BYTES: u32 = 256; - -/// Weight of single regular message delivery transaction on Polkadot-like chain. -/// -/// This value is a result of `pallet_bridge_messages::Pallet::receive_messages_proof_weight()` call -/// for the case when single message of `pallet_bridge_messages::EXPECTED_DEFAULT_MESSAGE_LENGTH` bytes is delivered. -/// The message must have dispatch weight set to zero. The result then must be rounded up to account -/// possible future runtime upgrades. -pub const DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT: Weight = 1_500_000_000; - -/// Weight of pay-dispatch-fee operation for inbound messages at Polkadot-like chain. -/// -/// This value corresponds to the result of `pallet_bridge_messages::WeightInfoExt::pay_inbound_dispatch_fee_overhead()` -/// call for your chain. Don't put too much reserve there, because it is used to **decrease** -/// `DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT` cost. So putting large reserve would make delivery transactions cheaper. -pub const PAY_INBOUND_DISPATCH_FEE_WEIGHT: Weight = 600_000_000; - /// Re-export `time_units` to make usage easier. pub use time_units::*; diff --git a/node/service/src/chain_spec.rs b/node/service/src/chain_spec.rs index 78d22d625d12..3f75a69885fe 100644 --- a/node/service/src/chain_spec.rs +++ b/node/service/src/chain_spec.rs @@ -1447,7 +1447,7 @@ pub fn kusama_testnet_genesis( config: default_parachains_host_configuration(), }, gilt: Default::default(), - paras: Default::default() + paras: Default::default(), xcm_pallet: Default::default(), bridge_polkadot_grandpa: kusama_runtime::BridgePolkadotGrandpaConfig { owner: Some(endowed_accounts[0].clone()), diff --git a/runtime/kusama/Cargo.toml b/runtime/kusama/Cargo.toml index 8ab1061ed8cf..1995bc0fe649 100644 --- a/runtime/kusama/Cargo.toml +++ b/runtime/kusama/Cargo.toml @@ -19,7 +19,6 @@ smallvec = "1.8.0" authority-discovery-primitives = { package = "sp-authority-discovery", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } babe-primitives = { package = "sp-consensus-babe", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } beefy-primitives = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } -bp-polkadot = { path = "../../bridges/primitives/chain-polkadot", default-features = false } bp-kusama = { path = "../../bridges/primitives/chain-kusama", default-features = false } bp-messages = { path = "../../bridges/primitives/messages", default-features = false } bp-polkadot = { path = "../../bridges/primitives/chain-polkadot", default-features = false } diff --git a/runtime/kusama/src/lib.rs b/runtime/kusama/src/lib.rs index 381041dff568..64f1022ae6ad 100644 --- a/runtime/kusama/src/lib.rs +++ b/runtime/kusama/src/lib.rs @@ -1404,25 +1404,25 @@ impl pallet_bridge_grandpa::Config for Runtime { type MaxRequests = MaxBridgeGrandpaRequests; type HeadersToKeep = BridgeGrandpaHeadersToKeep; - type WeightInfo = pallet_bridge_grandpa::weights::RialtoWeight; // TODO + type WeightInfo = pallet_bridge_grandpa::weights::MillauWeight; // TODO } parameter_types! { pub const MaxMessagesToPruneAtOnce: bp_messages::MessageNonce = 8; pub const MaxUnrewardedRelayerEntriesAtInboundLane: bp_messages::MessageNonce = - bp_kusama::MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE; + bp_polkadot::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX; pub const MaxUnconfirmedMessagesAtInboundLane: bp_messages::MessageNonce = - bp_kusama::MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE; + bp_polkadot::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX; pub const RootAccountForPayments: Option = None; pub const PolkadotChainId: bp_runtime::ChainId = bp_runtime::POLKADOT_CHAIN_ID; } /// Instance of the messages pallet used to relay messages to/from Polkadot chain. -pub type PolkadotMessagesInstance = (); +pub type WithPolkadotMessagesInstance = (); -impl pallet_bridge_messages::Config for Runtime { +impl pallet_bridge_messages::Config for Runtime { type Event = Event; - type WeightInfo = pallet_bridge_messages::weights::RialtoWeight; // TODO + type WeightInfo = pallet_bridge_messages::weights::MillauWeight; // TODO type Parameter = polkadot_messages::WithPolkadotMessageBridgeParameter; type MaxMessagesToPruneAtOnce = MaxMessagesToPruneAtOnce; type MaxUnrewardedRelayerEntriesAtInboundLane = MaxUnrewardedRelayerEntriesAtInboundLane; @@ -1441,10 +1441,11 @@ impl pallet_bridge_messages::Config for Runtime { type LaneMessageVerifier = polkadot_messages::ToPolkadotMessageVerifier; type MessageDeliveryAndDispatchPayment = pallet_bridge_messages::instant_payments::InstantCurrencyPayments< Runtime, + WithPolkadotMessagesInstance, pallet_balances::Pallet, polkadot_messages::GetDeliveryConfirmationTransactionFee, - RootAccountForPayments, >; + type OnMessageAccepted = (); type OnDeliveryConfirmed = (); type SourceHeaderChain = polkadot_messages::Polkadot; @@ -1457,7 +1458,7 @@ pub type PolkadotMessagesDispatchInstance = (); impl pallet_bridge_dispatch::Config for Runtime { type Event = Event; - type MessageId = (bp_messages::LaneId, bp_messages::MessageNonce); + type BridgeMessageId = (bp_messages::LaneId, bp_messages::MessageNonce); type Call = Call; type CallFilter = polkadot_messages::FromPolkadotCallFilter; type EncodedCall = polkadot_messages::FromPolkadotEncodedCall; @@ -1883,10 +1884,6 @@ sp_api::impl_runtime_apis! { let header = BridgePolkadotGrandpa::best_finalized(); (header.number, header.hash()) } - - fn is_known_header(hash: bp_polkadot::Hash) -> bool { - BridgePolkadotGrandpa::is_known_header(hash) - } } impl bp_polkadot::ToPolkadotOutboundLaneApi for Runtime { @@ -1907,29 +1904,13 @@ sp_api::impl_runtime_apis! { ) -> Vec> { bridge_runtime_common::messages_api::outbound_message_details::< Runtime, - PolkadotMessagesInstance, + WithPolkadotMessagesInstance, polkadot_messages::WithPolkadotMessageBridge, >(lane, begin, end) } - - fn latest_received_nonce(lane: bp_messages::LaneId) -> bp_messages::MessageNonce { - BridgePolkadotMessages::outbound_latest_received_nonce(lane) - } - - fn latest_generated_nonce(lane: bp_messages::LaneId) -> bp_messages::MessageNonce { - BridgePolkadotMessages::outbound_latest_generated_nonce(lane) - } } impl bp_polkadot::FromPolkadotInboundLaneApi for Runtime { - fn latest_received_nonce(lane: bp_messages::LaneId) -> bp_messages::MessageNonce { - BridgePolkadotMessages::inbound_latest_received_nonce(lane) - } - - fn latest_confirmed_nonce(lane: bp_messages::LaneId) -> bp_messages::MessageNonce { - BridgePolkadotMessages::inbound_latest_confirmed_nonce(lane) - } - fn unrewarded_relayers_state(lane: bp_messages::LaneId) -> bp_messages::UnrewardedRelayersState { BridgePolkadotMessages::inbound_unrewarded_relayers_state(lane) } diff --git a/runtime/kusama/src/polkadot_messages.rs b/runtime/kusama/src/polkadot_messages.rs index 6da1a09768f6..a5215f85bd8a 100644 --- a/runtime/kusama/src/polkadot_messages.rs +++ b/runtime/kusama/src/polkadot_messages.rs @@ -16,14 +16,14 @@ //! Over-bridge messaging support for Kusama <> Polkadot bridge. -use crate::{Call, Runtime}; +use crate::{AccountId, Call, Origin, OriginCaller, RootAccountForPayments, Runtime}; use bp_messages::{ - source_chain::{LaneMessageVerifier, TargetHeaderChain}, + source_chain::{LaneMessageVerifier, SenderOrigin, TargetHeaderChain}, target_chain::{ProvedMessages, SourceHeaderChain}, InboundLaneData, LaneId, Message, MessageNonce, OutboundLaneData, Parameter as MessagesParameter, }; -use bp_runtime::{ChainId, KUSAMA_CHAIN_ID, POLKADOT_CHAIN_ID}; +use bp_runtime::{Chain, ChainId, KUSAMA_CHAIN_ID, POLKADOT_CHAIN_ID}; use bridge_runtime_common::messages::{self, MessageBridge, MessageTransaction, ThisChainWithMessages}; use parity_scale_codec::{Decode, Encode}; use frame_support::{ @@ -32,7 +32,7 @@ use frame_support::{ weights::{DispatchClass, Weight, WeightToFeePolynomial}, RuntimeDebug, }; -use frame_system::RawOrigin; +use scale_info::TypeInfo; use sp_runtime::{traits::Saturating, FixedPointNumber, FixedU128}; use sp_std::{convert::TryFrom, ops::RangeInclusive}; @@ -47,7 +47,7 @@ parameter_types! { /// Fee multiplier at Polkadot. pub storage PolkadotFeeMultiplier: FixedU128 = INITIAL_POLKADOT_FEE_MULTIPLIER; /// The only Kusama account that is allowed to send messages to Polkadot. - pub storage AllowedMessageSender: bp_kusama::AccountId = Default::default(); + pub storage AllowedMessageSender: Option = None; } /// Message payload for Kusama -> Polkadot messages. @@ -77,6 +77,7 @@ const INBOUND_LANE_DISABLED: &str = "The inbound message lane is disaled."; pub struct ToPolkadotMessageVerifier; impl LaneMessageVerifier< + Origin, bp_kusama::AccountId, ToPolkadotMessagePayload, bp_kusama::Balance, @@ -84,7 +85,7 @@ impl LaneMessageVerifier< type Error = &'static str; fn verify_message( - submitter: &RawOrigin, + submitter: &Origin, delivery_and_dispatch_fee: &bp_kusama::Balance, lane: &LaneId, lane_outbound_data: &OutboundLaneData, @@ -92,8 +93,9 @@ impl LaneMessageVerifier< ) -> Result<(), Self::Error> { // we only allow messages to be sent by given account let allowed_sender = AllowedMessageSender::get(); - if *submitter != RawOrigin::Signed(allowed_sender) { - return Err(NOT_ALLOWED_MESSAGE_SENDER); + match allowed_sender { + Some(ref allowed_sender) if submitter.linked_account().as_ref() == Some(allowed_sender) => (), + _ => return Err(NOT_ALLOWED_MESSAGE_SENDER), } // perform other checks @@ -115,7 +117,7 @@ impl MessageBridge for WithPolkadotMessageBridge { const RELAYER_FEE_PERCENT: u32 = 10; const THIS_CHAIN_ID: ChainId = KUSAMA_CHAIN_ID; const BRIDGED_CHAIN_ID: ChainId = POLKADOT_CHAIN_ID; - const BRIDGED_MESSAGES_PALLET_NAME: &'static str = bp_polkadot::WITH_KUSAMA_MESSAGES_PALLET_NAME; + const BRIDGED_MESSAGES_PALLET_NAME: &'static str = bp_kusama::WITH_KUSAMA_MESSAGES_PALLET_NAME; type ThisChain = Kusama; type BridgedChain = Polkadot; @@ -141,13 +143,14 @@ impl messages::ChainWithMessages for Kusama { impl ThisChainWithMessages for Kusama { type Call = crate::Call; + type Origin = crate::Origin; - fn is_outbound_lane_enabled(lane: &LaneId) -> bool { + fn is_message_accepted(_submitter: &crate::Origin, lane: &LaneId) -> bool { *lane == [0, 0, 0, 0] } fn maximal_pending_messages_at_outbound_lane() -> MessageNonce { - bp_polkadot::MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE + bp_polkadot::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX } fn estimate_delivery_confirmation_transaction() -> MessageTransaction { @@ -197,13 +200,13 @@ impl messages::ChainWithMessages for Polkadot { impl messages::BridgedChainWithMessages for Polkadot { fn maximal_extrinsic_size() -> u32 { - bp_polkadot::max_extrinsic_size() + bp_polkadot::Polkadot::max_extrinsic_size() } fn message_weight_limits(_message_payload: &[u8]) -> RangeInclusive { // we don't want to relay too large messages + keep reserve for future upgrades let upper_limit = messages::target::maximal_incoming_message_dispatch_weight( - bp_polkadot::max_extrinsic_weight(), + bp_polkadot::Polkadot::max_extrinsic_weight(), ); // this bridge may be used to deliver all kind of messages, so we're not making any assumptions about @@ -298,15 +301,28 @@ fn verify_inbound_messages_lane( Ok(messages) } +impl SenderOrigin for Origin { + fn linked_account(&self) -> Option { + match self.caller { + OriginCaller::system(frame_system::RawOrigin::Signed(ref submitter)) => + Some(submitter.clone()), + OriginCaller::system(frame_system::RawOrigin::Root) | + OriginCaller::system(frame_system::RawOrigin::None) => + RootAccountForPayments::get(), + _ => None, + } + } +} + /// Kusama <> Polkadot messages pallet parameters. -#[derive(RuntimeDebug, Clone, Encode, Decode, PartialEq, Eq)] +#[derive(RuntimeDebug, Clone, Encode, Decode, PartialEq, Eq, TypeInfo)] pub enum WithPolkadotMessageBridgeParameter { /// The conversion formula we use is: `KusamaTokens = PolkadotTokens * conversion_rate`. PolkadotToKusamaConversionRate(FixedU128), /// Fee multiplier at the Polkadot chain. PolkadotFeeMultiplier(FixedU128), /// The only Kusama account that is allowed to send messages to Polkadot. - AllowedMessageSender(bp_kusama::AccountId), + AllowedMessageSender(Option), } impl MessagesParameter for WithPolkadotMessageBridgeParameter { @@ -341,7 +357,7 @@ pub struct FromPolkadotCallFilter; impl Contains for FromPolkadotCallFilter { fn contains(call: &Call) -> bool { - matches!(call, Call::Balances(pallet_balances::Call::transfer(..))) + matches!(call, Call::Balances(pallet_balances::Call::transfer { .. })) } } @@ -354,7 +370,7 @@ mod tests { #[test] fn ensure_kusama_message_lane_weights_are_correct() { - type Weights = pallet_bridge_messages::weights::RialtoWeight; // TODO: use Kusama weights + type Weights = pallet_bridge_messages::weights::MillauWeight; // TODO: use Kusama weights pallet_bridge_messages::ensure_weights_are_correct::( bp_kusama::DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT, @@ -365,27 +381,27 @@ mod tests { ); let max_incoming_message_proof_size = bp_polkadot::EXTRA_STORAGE_PROOF_SIZE.saturating_add( - messages::target::maximal_incoming_message_size(bp_kusama::max_extrinsic_size()), + messages::target::maximal_incoming_message_size(bp_kusama::Kusama::max_extrinsic_size()), ); pallet_bridge_messages::ensure_able_to_receive_message::( - bp_kusama::max_extrinsic_size(), - bp_kusama::max_extrinsic_weight(), + bp_kusama::Kusama::max_extrinsic_size(), + bp_kusama::Kusama::max_extrinsic_weight(), max_incoming_message_proof_size, - messages::target::maximal_incoming_message_dispatch_weight(bp_kusama::max_extrinsic_weight()), + messages::target::maximal_incoming_message_dispatch_weight(bp_kusama::Kusama::max_extrinsic_weight()), ); let max_incoming_inbound_lane_data_proof_size = bp_messages::InboundLaneData::<()>::encoded_size_hint( bp_kusama::MAXIMAL_ENCODED_ACCOUNT_ID_SIZE, - bp_polkadot::MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE as _, - bp_polkadot::MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE as _, + bp_polkadot::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX as _, + bp_polkadot::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX as _, ) .unwrap_or(u32::MAX); pallet_bridge_messages::ensure_able_to_receive_confirmation::( - bp_kusama::max_extrinsic_size(), - bp_kusama::max_extrinsic_weight(), + bp_kusama::Kusama::max_extrinsic_size(), + bp_kusama::Kusama::max_extrinsic_weight(), max_incoming_inbound_lane_data_proof_size, - bp_polkadot::MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE, - bp_polkadot::MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE, + bp_polkadot::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX, + bp_polkadot::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX, RocksDbWeight::get(), ); } @@ -404,10 +420,12 @@ mod tests { } let invalid_sender = bp_kusama::AccountId::from([1u8; 32]); - let valid_sender = AllowedMessageSender::get(); + let valid_sender = bp_kusama::AccountId::from([2u8; 32]); + AllowedMessageSender::set(&Some(valid_sender.clone())); + assert_eq!( ToPolkadotMessageVerifier::verify_message( - &RawOrigin::Signed(invalid_sender.clone()), + &frame_system::RawOrigin::Signed(invalid_sender.clone()).into(), &bp_kusama::Balance::MAX, &Default::default(), &Default::default(), @@ -417,7 +435,7 @@ mod tests { ); assert_eq!( ToPolkadotMessageVerifier::verify_message( - &RawOrigin::Signed(valid_sender.clone()), + &frame_system::RawOrigin::Signed(valid_sender.clone()).into(), &bp_kusama::Balance::MAX, &Default::default(), &Default::default(), diff --git a/runtime/polkadot/src/kusama_messages.rs b/runtime/polkadot/src/kusama_messages.rs index 5f5bbec15827..a3d6db2ffe2d 100644 --- a/runtime/polkadot/src/kusama_messages.rs +++ b/runtime/polkadot/src/kusama_messages.rs @@ -16,14 +16,14 @@ //! Over-bridge messaging support for Polkadot <> Kusama bridge. -use crate::{Call, Runtime}; +use crate::{AccountId, Call, Origin, OriginCaller, RootAccountForPayments, Runtime}; use bp_messages::{ - source_chain::{LaneMessageVerifier, TargetHeaderChain}, + source_chain::{LaneMessageVerifier, SenderOrigin, TargetHeaderChain}, target_chain::{ProvedMessages, SourceHeaderChain}, InboundLaneData, LaneId, Message, MessageNonce, OutboundLaneData, Parameter as MessagesParameter, }; -use bp_runtime::{ChainId, POLKADOT_CHAIN_ID, KUSAMA_CHAIN_ID}; +use bp_runtime::{Chain, ChainId, POLKADOT_CHAIN_ID, KUSAMA_CHAIN_ID}; use bridge_runtime_common::messages::{self, MessageBridge, MessageTransaction, ThisChainWithMessages}; use parity_scale_codec::{Decode, Encode}; use frame_support::{ @@ -32,7 +32,7 @@ use frame_support::{ weights::{DispatchClass, Weight, WeightToFeePolynomial}, RuntimeDebug, }; -use frame_system::RawOrigin; +use scale_info::TypeInfo; use sp_runtime::{traits::Saturating, FixedPointNumber, FixedU128}; use sp_std::{convert::TryFrom, ops::RangeInclusive}; @@ -47,7 +47,7 @@ parameter_types! { /// Fee multiplier at Kusama. pub storage KusamaFeeMultiplier: FixedU128 = INITIAL_KUSAMA_FEE_MULTIPLIER; /// The only Polkadot account that is allowed to send messages to Kusama. - pub storage AllowedMessageSender: bp_polkadot::AccountId = Default::default(); + pub storage AllowedMessageSender: Option = None; } /// Message payload for Polkadot -> Kusama messages. @@ -77,6 +77,7 @@ const INBOUND_LANE_DISABLED: &str = "The inbound message lane is disaled."; pub struct ToKusamaMessageVerifier; impl LaneMessageVerifier< + Origin, bp_polkadot::AccountId, ToKusamaMessagePayload, bp_polkadot::Balance, @@ -84,7 +85,7 @@ impl LaneMessageVerifier< type Error = &'static str; fn verify_message( - submitter: &RawOrigin, + submitter: &Origin, delivery_and_dispatch_fee: &bp_polkadot::Balance, lane: &LaneId, lane_outbound_data: &OutboundLaneData, @@ -92,8 +93,9 @@ impl LaneMessageVerifier< ) -> Result<(), Self::Error> { // we only allow messages to be sent by given account let allowed_sender = AllowedMessageSender::get(); - if *submitter != RawOrigin::Signed(allowed_sender) { - return Err(NOT_ALLOWED_MESSAGE_SENDER); + match allowed_sender { + Some(ref allowed_sender) if submitter.linked_account().as_ref() == Some(allowed_sender) => (), + _ => return Err(NOT_ALLOWED_MESSAGE_SENDER), } // perform other checks @@ -115,7 +117,7 @@ impl MessageBridge for WithKusamaMessageBridge { const RELAYER_FEE_PERCENT: u32 = 10; const THIS_CHAIN_ID: ChainId = POLKADOT_CHAIN_ID; const BRIDGED_CHAIN_ID: ChainId = KUSAMA_CHAIN_ID; - const BRIDGED_MESSAGES_PALLET_NAME: &'static str = bp_kusama::WITH_POLKADOT_MESSAGES_PALLET_NAME; + const BRIDGED_MESSAGES_PALLET_NAME: &'static str = bp_polkadot::WITH_POLKADOT_MESSAGES_PALLET_NAME; type ThisChain = Polkadot; type BridgedChain = Kusama; @@ -141,13 +143,14 @@ impl messages::ChainWithMessages for Polkadot { impl ThisChainWithMessages for Polkadot { type Call = crate::Call; + type Origin = crate::Origin; - fn is_outbound_lane_enabled(lane: &LaneId) -> bool { + fn is_message_accepted(_submitter: &crate::Origin, lane: &LaneId) -> bool { *lane == [0, 0, 0, 0] } fn maximal_pending_messages_at_outbound_lane() -> MessageNonce { - bp_kusama::MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE + bp_kusama::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX } fn estimate_delivery_confirmation_transaction() -> MessageTransaction { @@ -197,13 +200,13 @@ impl messages::ChainWithMessages for Kusama { impl messages::BridgedChainWithMessages for Kusama { fn maximal_extrinsic_size() -> u32 { - bp_kusama::max_extrinsic_size() + bp_kusama::Kusama::max_extrinsic_size() } fn message_weight_limits(_message_payload: &[u8]) -> RangeInclusive { // we don't want to relay too large messages + keep reserve for future upgrades let upper_limit = messages::target::maximal_incoming_message_dispatch_weight( - bp_kusama::max_extrinsic_weight(), + bp_kusama::Kusama::max_extrinsic_weight(), ); // this bridge may be used to deliver all kind of messages, so we're not making any assumptions about @@ -298,15 +301,28 @@ fn verify_inbound_messages_lane( Ok(messages) } +impl SenderOrigin for Origin { + fn linked_account(&self) -> Option { + match self.caller { + OriginCaller::system(frame_system::RawOrigin::Signed(ref submitter)) => + Some(submitter.clone()), + OriginCaller::system(frame_system::RawOrigin::Root) | + OriginCaller::system(frame_system::RawOrigin::None) => + RootAccountForPayments::get(), + _ => None, + } + } +} + /// Polkadot <> Kusama messages pallet parameters. -#[derive(RuntimeDebug, Clone, Encode, Decode, PartialEq, Eq)] +#[derive(RuntimeDebug, Clone, Encode, Decode, PartialEq, Eq, TypeInfo)] pub enum WithKusamaMessageBridgeParameter { /// The conversion formula we use is: `PolkadotTokens = KusamaTokens * conversion_rate`. KusamaToPolkadotConversionRate(FixedU128), /// Fee multiplier at the Kusama chain. KusamaFeeMultiplier(FixedU128), /// The only Polkadot account that is allowed to send messages to Kusama. - AllowedMessageSender(bp_polkadot::AccountId), + AllowedMessageSender(Option), } impl MessagesParameter for WithKusamaMessageBridgeParameter { @@ -341,7 +357,7 @@ pub struct FromKusamaCallFilter; impl Contains for FromKusamaCallFilter { fn contains(call: &Call) -> bool { - matches!(call, Call::Balances(pallet_balances::Call::transfer(..))) + matches!(call, Call::Balances(pallet_balances::Call::transfer { .. })) } } @@ -354,7 +370,7 @@ mod tests { #[test] fn ensure_polkadot_message_lane_weights_are_correct() { - type Weights = pallet_bridge_messages::weights::RialtoWeight; // TODO: use Polkadot weights + type Weights = pallet_bridge_messages::weights::MillauWeight; // TODO: use Polkadot weights pallet_bridge_messages::ensure_weights_are_correct::( bp_polkadot::DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT, @@ -365,27 +381,27 @@ mod tests { ); let max_incoming_message_proof_size = bp_kusama::EXTRA_STORAGE_PROOF_SIZE.saturating_add( - messages::target::maximal_incoming_message_size(bp_polkadot::max_extrinsic_size()), + messages::target::maximal_incoming_message_size(bp_polkadot::Polkadot::max_extrinsic_size()), ); pallet_bridge_messages::ensure_able_to_receive_message::( - bp_polkadot::max_extrinsic_size(), - bp_polkadot::max_extrinsic_weight(), + bp_polkadot::Polkadot::max_extrinsic_size(), + bp_polkadot::Polkadot::max_extrinsic_weight(), max_incoming_message_proof_size, - messages::target::maximal_incoming_message_dispatch_weight(bp_polkadot::max_extrinsic_weight()), + messages::target::maximal_incoming_message_dispatch_weight(bp_polkadot::Polkadot::max_extrinsic_weight()), ); let max_incoming_inbound_lane_data_proof_size = bp_messages::InboundLaneData::<()>::encoded_size_hint( bp_polkadot::MAXIMAL_ENCODED_ACCOUNT_ID_SIZE, - bp_kusama::MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE as _, - bp_kusama::MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE as _, + bp_polkadot::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX as _, + bp_polkadot::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX as _, ) .unwrap_or(u32::MAX); pallet_bridge_messages::ensure_able_to_receive_confirmation::( - bp_polkadot::max_extrinsic_size(), - bp_polkadot::max_extrinsic_weight(), + bp_polkadot::Polkadot::max_extrinsic_size(), + bp_polkadot::Polkadot::max_extrinsic_weight(), max_incoming_inbound_lane_data_proof_size, - bp_kusama::MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE, - bp_kusama::MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE, + bp_polkadot::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX, + bp_polkadot::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX, RocksDbWeight::get(), ); } @@ -404,10 +420,12 @@ mod tests { } let invalid_sender = bp_polkadot::AccountId::from([1u8; 32]); - let valid_sender = AllowedMessageSender::get(); + let valid_sender = bp_polkadot::AccountId::from([2u8; 32]); + AllowedMessageSender::set(&Some(valid_sender.clone())); + assert_eq!( ToKusamaMessageVerifier::verify_message( - &RawOrigin::Signed(invalid_sender.clone()), + &frame_system::RawOrigin::Signed(invalid_sender.clone()).into(), &bp_polkadot::Balance::MAX, &Default::default(), &Default::default(), @@ -417,7 +435,7 @@ mod tests { ); assert_eq!( ToKusamaMessageVerifier::verify_message( - &RawOrigin::Signed(valid_sender.clone()), + &frame_system::RawOrigin::Signed(valid_sender.clone()).into(), &bp_polkadot::Balance::MAX, &Default::default(), &Default::default(), diff --git a/runtime/polkadot/src/lib.rs b/runtime/polkadot/src/lib.rs index 458e4a6a1e16..7636c8d559f1 100644 --- a/runtime/polkadot/src/lib.rs +++ b/runtime/polkadot/src/lib.rs @@ -1371,25 +1371,25 @@ impl pallet_bridge_grandpa::Config for Runtime { type MaxRequests = MaxBridgeGrandpaRequests; type HeadersToKeep = BridgeGrandpaHeadersToKeep; - type WeightInfo = pallet_bridge_grandpa::weights::RialtoWeight; // TODO + type WeightInfo = pallet_bridge_grandpa::weights::MillauWeight; // TODO } parameter_types! { pub const MaxMessagesToPruneAtOnce: bp_messages::MessageNonce = 8; pub const MaxUnrewardedRelayerEntriesAtInboundLane: bp_messages::MessageNonce = - bp_polkadot::MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE; + bp_kusama::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX; pub const MaxUnconfirmedMessagesAtInboundLane: bp_messages::MessageNonce = - bp_polkadot::MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE; + bp_kusama::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX; pub const RootAccountForPayments: Option = None; pub const KusamaChainId: bp_runtime::ChainId = bp_runtime::KUSAMA_CHAIN_ID; } /// Instance of the messages pallet used to relay messages to/from Kusama chain. -pub type KusamaMessagesInstance = (); +pub type WithKusamaMessagesInstance = (); -impl pallet_bridge_messages::Config for Runtime { +impl pallet_bridge_messages::Config for Runtime { type Event = Event; - type WeightInfo = pallet_bridge_messages::weights::RialtoWeight; // TODO + type WeightInfo = pallet_bridge_messages::weights::MillauWeight; // TODO type Parameter = kusama_messages::WithKusamaMessageBridgeParameter; type MaxMessagesToPruneAtOnce = MaxMessagesToPruneAtOnce; type MaxUnrewardedRelayerEntriesAtInboundLane = MaxUnrewardedRelayerEntriesAtInboundLane; @@ -1408,10 +1408,11 @@ impl pallet_bridge_messages::Config for Runtime { type LaneMessageVerifier = kusama_messages::ToKusamaMessageVerifier; type MessageDeliveryAndDispatchPayment = pallet_bridge_messages::instant_payments::InstantCurrencyPayments< Runtime, + WithKusamaMessagesInstance, pallet_balances::Pallet, kusama_messages::GetDeliveryConfirmationTransactionFee, - RootAccountForPayments, >; + type OnMessageAccepted = (); type OnDeliveryConfirmed = (); type SourceHeaderChain = kusama_messages::Kusama; @@ -1424,7 +1425,7 @@ pub type KusamaMessagesDispatchInstance = (); impl pallet_bridge_dispatch::Config for Runtime { type Event = Event; - type MessageId = (bp_messages::LaneId, bp_messages::MessageNonce); + type BridgeMessageId = (bp_messages::LaneId, bp_messages::MessageNonce); type Call = Call; type CallFilter = kusama_messages::FromKusamaCallFilter; type EncodedCall = kusama_messages::FromKusamaEncodedCall; @@ -2028,10 +2029,6 @@ sp_api::impl_runtime_apis! { let header = BridgeKusamaGrandpa::best_finalized(); (header.number, header.hash()) } - - fn is_known_header(hash: bp_kusama::Hash) -> bool { - BridgeKusamaGrandpa::is_known_header(hash) - } } impl bp_kusama::ToKusamaOutboundLaneApi for Runtime { @@ -2052,29 +2049,13 @@ sp_api::impl_runtime_apis! { ) -> Vec> { bridge_runtime_common::messages_api::outbound_message_details::< Runtime, - KusamaMessagesInstance, + WithKusamaMessagesInstance, kusama_messages::WithKusamaMessageBridge, >(lane, begin, end) } - - fn latest_received_nonce(lane: bp_messages::LaneId) -> bp_messages::MessageNonce { - BridgeKusamaMessages::outbound_latest_received_nonce(lane) - } - - fn latest_generated_nonce(lane: bp_messages::LaneId) -> bp_messages::MessageNonce { - BridgeKusamaMessages::outbound_latest_generated_nonce(lane) - } } impl bp_kusama::FromKusamaInboundLaneApi for Runtime { - fn latest_received_nonce(lane: bp_messages::LaneId) -> bp_messages::MessageNonce { - BridgeKusamaMessages::inbound_latest_received_nonce(lane) - } - - fn latest_confirmed_nonce(lane: bp_messages::LaneId) -> bp_messages::MessageNonce { - BridgeKusamaMessages::inbound_latest_confirmed_nonce(lane) - } - fn unrewarded_relayers_state(lane: bp_messages::LaneId) -> bp_messages::UnrewardedRelayersState { BridgeKusamaMessages::inbound_unrewarded_relayers_state(lane) } diff --git a/runtime/rococo/src/bridge_messages.rs b/runtime/rococo/src/bridge_messages.rs index 3df72ba842ea..ca18aef8148f 100644 --- a/runtime/rococo/src/bridge_messages.rs +++ b/runtime/rococo/src/bridge_messages.rs @@ -305,7 +305,7 @@ mod at_rococo { const BRIDGED_CHAIN_ID: ChainId = WOCOCO_CHAIN_ID; const RELAYER_FEE_PERCENT: u32 = 10; const BRIDGED_MESSAGES_PALLET_NAME: &'static str = - bp_wococo::WITH_WOCOCO_MESSAGES_PALLET_NAME; + bp_rococo::WITH_ROCOCO_MESSAGES_PALLET_NAME; type ThisChain = RococoAtRococo; type BridgedChain = WococoAtRococo; @@ -356,7 +356,7 @@ mod at_wococo { const BRIDGED_CHAIN_ID: ChainId = ROCOCO_CHAIN_ID; const RELAYER_FEE_PERCENT: u32 = 10; const BRIDGED_MESSAGES_PALLET_NAME: &'static str = - bp_rococo::WITH_ROCOCO_MESSAGES_PALLET_NAME; + bp_wococo::WITH_WOCOCO_MESSAGES_PALLET_NAME; type ThisChain = WococoAtWococo; type BridgedChain = RococoAtWococo; diff --git a/runtime/rococo/src/lib.rs b/runtime/rococo/src/lib.rs index a63a6bb32238..b534311bca84 100644 --- a/runtime/rococo/src/lib.rs +++ b/runtime/rococo/src/lib.rs @@ -821,7 +821,6 @@ impl pallet_bridge_messages::Config for Runt type SourceHeaderChain = crate::bridge_messages::RococoAtWococo; type MessageDispatch = crate::bridge_messages::FromRococoMessageDispatch; - type BridgedChainId = RococoChainId; } // Instance that is "deployed" at Rococo chain. Responsible for sending Rococo -> Wococo messages @@ -859,7 +858,6 @@ impl pallet_bridge_messages::Config for Runt type SourceHeaderChain = crate::bridge_messages::WococoAtRococo; type MessageDispatch = crate::bridge_messages::FromWococoMessageDispatch; - type BridgedChainId = WococoChainId; } parameter_types! { From 720aa72e5c1ff1d59e3d2687b2d6cfc80cda698c Mon Sep 17 00:00:00 2001 From: Svyatoslav Nikolsky Date: Fri, 28 Jan 2022 11:14:32 +0300 Subject: [PATCH 09/31] initial council members --- node/service/src/chain_spec.rs | 16 ++++++++++++++-- runtime/kusama/src/polkadot_messages.rs | 1 + runtime/polkadot/src/kusama_messages.rs | 3 ++- 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/node/service/src/chain_spec.rs b/node/service/src/chain_spec.rs index 3f75a69885fe..d52fa980f1ba 100644 --- a/node/service/src/chain_spec.rs +++ b/node/service/src/chain_spec.rs @@ -1332,7 +1332,13 @@ pub fn polkadot_testnet_genesis( }, phragmen_election: Default::default(), democracy: polkadot::DemocracyConfig::default(), - council: polkadot::CouncilConfig { members: vec![], phantom: Default::default() }, + council: polkadot::CouncilConfig { + members: initial_authorities + .iter() + .map(|x| x.0.clone()) + .collect::>(), + phantom: Default::default() + }, technical_committee: polkadot::TechnicalCommitteeConfig { members: vec![], phantom: Default::default(), @@ -1426,7 +1432,13 @@ pub fn kusama_testnet_genesis( }, phragmen_election: Default::default(), democracy: kusama::DemocracyConfig::default(), - council: kusama::CouncilConfig { members: vec![], phantom: Default::default() }, + council: kusama::CouncilConfig { + members: initial_authorities + .iter() + .map(|x| x.0.clone()) + .collect::>(), + phantom: Default::default(), + }, technical_committee: kusama::TechnicalCommitteeConfig { members: vec![], phantom: Default::default(), diff --git a/runtime/kusama/src/polkadot_messages.rs b/runtime/kusama/src/polkadot_messages.rs index a5215f85bd8a..683ec200278d 100644 --- a/runtime/kusama/src/polkadot_messages.rs +++ b/runtime/kusama/src/polkadot_messages.rs @@ -309,6 +309,7 @@ impl SenderOrigin for Origin { OriginCaller::system(frame_system::RawOrigin::Root) | OriginCaller::system(frame_system::RawOrigin::None) => RootAccountForPayments::get(), + OriginCaller::council(_) => AllowedMessageSender::get(), // TODO: rename to council account, _ => None, } } diff --git a/runtime/polkadot/src/kusama_messages.rs b/runtime/polkadot/src/kusama_messages.rs index a3d6db2ffe2d..1a690ebc18dc 100644 --- a/runtime/polkadot/src/kusama_messages.rs +++ b/runtime/polkadot/src/kusama_messages.rs @@ -309,7 +309,8 @@ impl SenderOrigin for Origin { OriginCaller::system(frame_system::RawOrigin::Root) | OriginCaller::system(frame_system::RawOrigin::None) => RootAccountForPayments::get(), - _ => None, + OriginCaller::council(_) => AllowedMessageSender::get(), // TODO: rename to council account, + _ => None, } } } From 5fbf733cd108a5e4bd6c534ba0aa9665b29125a1 Mon Sep 17 00:00:00 2001 From: Svyatoslav Nikolsky Date: Fri, 28 Jan 2022 11:36:06 +0300 Subject: [PATCH 10/31] allow council to send messages using given account for payment --- runtime/kusama/src/polkadot_messages.rs | 6 +++--- runtime/polkadot/src/kusama_messages.rs | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/runtime/kusama/src/polkadot_messages.rs b/runtime/kusama/src/polkadot_messages.rs index 683ec200278d..b1e30223bac6 100644 --- a/runtime/kusama/src/polkadot_messages.rs +++ b/runtime/kusama/src/polkadot_messages.rs @@ -145,8 +145,8 @@ impl ThisChainWithMessages for Kusama { type Call = crate::Call; type Origin = crate::Origin; - fn is_message_accepted(_submitter: &crate::Origin, lane: &LaneId) -> bool { - *lane == [0, 0, 0, 0] + fn is_message_accepted(submitter: &crate::Origin, lane: &LaneId) -> bool { + *lane == [0, 0, 0, 0] && submitter.linked_account().is_some() } fn maximal_pending_messages_at_outbound_lane() -> MessageNonce { @@ -309,7 +309,7 @@ impl SenderOrigin for Origin { OriginCaller::system(frame_system::RawOrigin::Root) | OriginCaller::system(frame_system::RawOrigin::None) => RootAccountForPayments::get(), - OriginCaller::council(_) => AllowedMessageSender::get(), // TODO: rename to council account, + OriginCaller::Council(_) => AllowedMessageSender::get(), // TODO: rename to council account, _ => None, } } diff --git a/runtime/polkadot/src/kusama_messages.rs b/runtime/polkadot/src/kusama_messages.rs index 1a690ebc18dc..7b3d595bed1f 100644 --- a/runtime/polkadot/src/kusama_messages.rs +++ b/runtime/polkadot/src/kusama_messages.rs @@ -145,8 +145,8 @@ impl ThisChainWithMessages for Polkadot { type Call = crate::Call; type Origin = crate::Origin; - fn is_message_accepted(_submitter: &crate::Origin, lane: &LaneId) -> bool { - *lane == [0, 0, 0, 0] + fn is_message_accepted(submitter: &crate::Origin, lane: &LaneId) -> bool { + *lane == [0, 0, 0, 0] && submitter.linked_account().is_some() } fn maximal_pending_messages_at_outbound_lane() -> MessageNonce { @@ -309,7 +309,7 @@ impl SenderOrigin for Origin { OriginCaller::system(frame_system::RawOrigin::Root) | OriginCaller::system(frame_system::RawOrigin::None) => RootAccountForPayments::get(), - OriginCaller::council(_) => AllowedMessageSender::get(), // TODO: rename to council account, + OriginCaller::Council(_) => AllowedMessageSender::get(), // TODO: rename to council account, _ => None, } } From 9eec8d80a4ff5efca315617ff4890a3897c61807 Mon Sep 17 00:00:00 2001 From: Svyatoslav Nikolsky Date: Fri, 4 Feb 2022 16:44:35 +0300 Subject: [PATCH 11/31] add benchmarks to kusama --- .../src/messages_benchmarking.rs | 1 + runtime/kusama/Cargo.toml | 1 + runtime/kusama/src/lib.rs | 5 + runtime/kusama/src/polkadot_messages.rs | 146 +++++++++++++++--- 4 files changed, 128 insertions(+), 25 deletions(-) diff --git a/bridges/bin/runtime-common/src/messages_benchmarking.rs b/bridges/bin/runtime-common/src/messages_benchmarking.rs index 5e20078a2562..903cf2fc2824 100644 --- a/bridges/bin/runtime-common/src/messages_benchmarking.rs +++ b/bridges/bin/runtime-common/src/messages_benchmarking.rs @@ -107,6 +107,7 @@ where BHH: Hasher>>, AccountIdOf>: PartialEq + sp_std::fmt::Debug, AccountIdOf>: From<[u8; 32]>, + AccountIdOf>: PartialEq + sp_std::fmt::Debug, BalanceOf>: Debug + MaybeSerializeDeserialize, CallOf>: From> + GetDispatchInfo, HashOf>: Copy + Default, diff --git a/runtime/kusama/Cargo.toml b/runtime/kusama/Cargo.toml index 1995bc0fe649..5fce6a5b832c 100644 --- a/runtime/kusama/Cargo.toml +++ b/runtime/kusama/Cargo.toml @@ -201,6 +201,7 @@ std = [ "frame-election-provider-support/std", ] runtime-benchmarks = [ + "bridge-runtime-common/runtime-benchmarks", "runtime-common/runtime-benchmarks", "frame-benchmarking/runtime-benchmarks", "frame-support/runtime-benchmarks", diff --git a/runtime/kusama/src/lib.rs b/runtime/kusama/src/lib.rs index 64f1022ae6ad..3d805f93a5c6 100644 --- a/runtime/kusama/src/lib.rs +++ b/runtime/kusama/src/lib.rs @@ -1686,6 +1686,9 @@ mod benches { [pallet_treasury, Treasury] [pallet_utility, Utility] [pallet_vesting, Vesting] + // Bridges + [pallet_bridge_grandpa, BridgePolkadotGrandpa] + [pallet_bridge_messages, MessagesBench::] ); } @@ -2066,6 +2069,7 @@ sp_api::impl_runtime_apis! { use pallet_offences_benchmarking::Pallet as OffencesBench; use frame_system_benchmarking::Pallet as SystemBench; use frame_benchmarking::baseline::Pallet as Baseline; + use pallet_bridge_messages::benchmarking::Pallet as MessagesBench; let mut list = Vec::::new(); list_benchmarks!(list, extra); @@ -2087,6 +2091,7 @@ sp_api::impl_runtime_apis! { use pallet_offences_benchmarking::Pallet as OffencesBench; use frame_system_benchmarking::Pallet as SystemBench; use frame_benchmarking::baseline::Pallet as Baseline; + use pallet_bridge_messages::benchmarking::Pallet as MessagesBench; impl pallet_session_benchmarking::Config for Runtime {} impl pallet_offences_benchmarking::Config for Runtime {} diff --git a/runtime/kusama/src/polkadot_messages.rs b/runtime/kusama/src/polkadot_messages.rs index b1e30223bac6..e4c7175aebd0 100644 --- a/runtime/kusama/src/polkadot_messages.rs +++ b/runtime/kusama/src/polkadot_messages.rs @@ -16,7 +16,7 @@ //! Over-bridge messaging support for Kusama <> Polkadot bridge. -use crate::{AccountId, Call, Origin, OriginCaller, RootAccountForPayments, Runtime}; +use crate::{AccountId, Balance, Balances, Call, Origin, OriginCaller, RootAccountForPayments, Runtime}; use bp_messages::{ source_chain::{LaneMessageVerifier, SenderOrigin, TargetHeaderChain}, @@ -24,7 +24,12 @@ use bp_messages::{ InboundLaneData, LaneId, Message, MessageNonce, OutboundLaneData, Parameter as MessagesParameter, }; use bp_runtime::{Chain, ChainId, KUSAMA_CHAIN_ID, POLKADOT_CHAIN_ID}; -use bridge_runtime_common::messages::{self, MessageBridge, MessageTransaction, ThisChainWithMessages}; +use bridge_runtime_common::messages::{ + source as messages_source, target as messages_target, + BridgedChainWithMessages, ChainWithMessages, MessageBridge, + MessageTransaction, ThisChainWithMessages, + transaction_payment, +}; use parity_scale_codec::{Decode, Encode}; use frame_support::{ parameter_types, @@ -36,6 +41,27 @@ use scale_info::TypeInfo; use sp_runtime::{traits::Saturating, FixedPointNumber, FixedU128}; use sp_std::{convert::TryFrom, ops::RangeInclusive}; +#[cfg(feature = "runtime-benchmarks")] +use crate::Event; +#[cfg(feature = "runtime-benchmarks")] +use bp_polkadot::{Hasher, Header}; +#[cfg(feature = "runtime-benchmarks")] +use bridge_runtime_common::messages_benchmarking::{ + dispatch_account, + prepare_message_delivery_proof, + prepare_message_proof, + prepare_outbound_message, +}; +#[cfg(feature = "runtime-benchmarks")] +use frame_support::traits::Currency; +#[cfg(feature = "runtime-benchmarks")] +use pallet_bridge_messages::benchmarking::{ + Config as MessagesConfig, + MessageDeliveryProofParams, + MessageParams, + MessageProofParams, +}; + /// Initial value of `PolkadotToKusamaConversionRate` parameter. pub const INITIAL_POLKADOT_TO_KUSAMA_CONVERSION_RATE: FixedU128 = FixedU128::from_inner(FixedU128::DIV); /// Initial value of `PolkadotFeeMultiplier` parameter. @@ -51,16 +77,16 @@ parameter_types! { } /// Message payload for Kusama -> Polkadot messages. -pub type ToPolkadotMessagePayload = messages::source::FromThisChainMessagePayload; +pub type ToPolkadotMessagePayload = messages_source::FromThisChainMessagePayload; /// Message payload for Polkadot -> Kusama messages. -pub type FromPolkadotMessagePayload = messages::target::FromBridgedChainMessagePayload; +pub type FromPolkadotMessagePayload = messages_target::FromBridgedChainMessagePayload; /// Encoded Kusama Call as it comes from Polkadot. -pub type FromPolkadotEncodedCall = messages::target::FromBridgedChainEncodedMessageCall; +pub type FromPolkadotEncodedCall = messages_target::FromBridgedChainEncodedMessageCall; /// Call-dispatch based message dispatch for Polkadot -> Kusama messages. -pub type FromPolkadotMessageDispatch = messages::target::FromBridgedChainMessageDispatch< +pub type FromPolkadotMessageDispatch = messages_target::FromBridgedChainMessageDispatch< WithPolkadotMessageBridge, crate::Runtime, pallet_balances::Pallet, @@ -68,6 +94,7 @@ pub type FromPolkadotMessageDispatch = messages::target::FromBridgedChainMessage >; /// Error that happens when message is sent by anyone but `AllowedMessageSender`. +#[cfg(not(feature = "runtime-benchmarks"))] const NOT_ALLOWED_MESSAGE_SENDER: &str = "Cannot accept message from this account"; /// Error that happens when we are receiving incoming message via unexpected lane. const INBOUND_LANE_DISABLED: &str = "The inbound message lane is disaled."; @@ -91,15 +118,22 @@ impl LaneMessageVerifier< lane_outbound_data: &OutboundLaneData, payload: &ToPolkadotMessagePayload, ) -> Result<(), Self::Error> { - // we only allow messages to be sent by given account let allowed_sender = AllowedMessageSender::get(); - match allowed_sender { - Some(ref allowed_sender) if submitter.linked_account().as_ref() == Some(allowed_sender) => (), - _ => return Err(NOT_ALLOWED_MESSAGE_SENDER), + // for benchmarks we're still interested in this additional storage, read, but we don't + // want actual checks + #[cfg(feature = "runtime-benchmarks")] + drop(allowed_sender); + // outside of benchmarks, we only allow messages to be sent by given account + #[cfg(not(feature = "runtime-benchmarks"))] + { + match allowed_sender { + Some(ref allowed_sender) if submitter.linked_account().as_ref() == Some(allowed_sender) => (), + _ => return Err(NOT_ALLOWED_MESSAGE_SENDER), + } } // perform other checks - messages::source::FromThisChainMessageVerifier::::verify_message( + messages_source::FromThisChainMessageVerifier::::verify_message( submitter, delivery_and_dispatch_fee, lane, @@ -132,7 +166,7 @@ impl MessageBridge for WithPolkadotMessageBridge { #[derive(RuntimeDebug, Clone, Copy)] pub struct Kusama; -impl messages::ChainWithMessages for Kusama { +impl ChainWithMessages for Kusama { type Hash = bp_kusama::Hash; type AccountId = bp_kusama::AccountId; type Signer = bp_kusama::AccountPublic; @@ -175,7 +209,7 @@ impl ThisChainWithMessages for Kusama { let multiplier = FixedU128::saturating_from_rational(110, 100) .saturating_mul(pallet_transaction_payment::Pallet::::next_fee_multiplier()); let per_byte_fee = crate::TransactionByteFee::get(); - messages::transaction_payment( + transaction_payment( bp_kusama::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic, per_byte_fee, multiplier, @@ -189,7 +223,7 @@ impl ThisChainWithMessages for Kusama { #[derive(RuntimeDebug, Clone, Copy)] pub struct Polkadot; -impl messages::ChainWithMessages for Polkadot { +impl ChainWithMessages for Polkadot { type Hash = bp_polkadot::Hash; type AccountId = bp_polkadot::AccountId; type Signer = bp_polkadot::AccountPublic; @@ -198,14 +232,14 @@ impl messages::ChainWithMessages for Polkadot { type Balance = bp_polkadot::Balance; } -impl messages::BridgedChainWithMessages for Polkadot { +impl BridgedChainWithMessages for Polkadot { fn maximal_extrinsic_size() -> u32 { bp_polkadot::Polkadot::max_extrinsic_size() } fn message_weight_limits(_message_payload: &[u8]) -> RangeInclusive { // we don't want to relay too large messages + keep reserve for future upgrades - let upper_limit = messages::target::maximal_incoming_message_dispatch_weight( + let upper_limit = messages_target::maximal_incoming_message_dispatch_weight( bp_polkadot::Polkadot::max_extrinsic_weight(), ); @@ -245,7 +279,7 @@ impl messages::BridgedChainWithMessages for Polkadot { // => it is a messages module parameter let multiplier = PolkadotFeeMultiplier::get(); let per_byte_fee = bp_polkadot::TRANSACTION_BYTE_FEE; - messages::transaction_payment( + transaction_payment( bp_polkadot::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic, per_byte_fee, multiplier, @@ -257,16 +291,16 @@ impl messages::BridgedChainWithMessages for Polkadot { impl TargetHeaderChain for Polkadot { type Error = &'static str; - type MessagesDeliveryProof = messages::source::FromBridgedChainMessagesDeliveryProof; + type MessagesDeliveryProof = messages_source::FromBridgedChainMessagesDeliveryProof; fn verify_message(payload: &ToPolkadotMessagePayload) -> Result<(), Self::Error> { - messages::source::verify_chain_message::(payload) + messages_source::verify_chain_message::(payload) } fn verify_messages_delivery_proof( proof: Self::MessagesDeliveryProof, ) -> Result<(LaneId, InboundLaneData), Self::Error> { - messages::source::verify_messages_delivery_proof::< + messages_source::verify_messages_delivery_proof::< WithPolkadotMessageBridge, Runtime, crate::PolkadotGrandpaInstance, @@ -276,13 +310,13 @@ impl TargetHeaderChain for Pol impl SourceHeaderChain for Polkadot { type Error = &'static str; - type MessagesProof = messages::target::FromBridgedChainMessagesProof; + type MessagesProof = messages_target::FromBridgedChainMessagesProof; fn verify_messages_proof( proof: Self::MessagesProof, messages_count: u32, ) -> Result>, Self::Error> { - messages::target::verify_messages_proof::< + messages_target::verify_messages_proof::< WithPolkadotMessageBridge, Runtime, crate::PolkadotGrandpaInstance, @@ -346,7 +380,7 @@ impl MessagesParameter for WithPolkadotMessageBridgeParameter { pub struct GetDeliveryConfirmationTransactionFee; impl Get for GetDeliveryConfirmationTransactionFee { - fn get() -> crate::Balance { + fn get() -> Balance { ::transaction_payment( Kusama::estimate_delivery_confirmation_transaction(), ) @@ -358,10 +392,72 @@ pub struct FromPolkadotCallFilter; impl Contains for FromPolkadotCallFilter { fn contains(call: &Call) -> bool { + #[cfg(feature = "runtime-benchmarks")] + { + drop(call); + true + } + #[cfg(not(feature = "runtime-benchmarks"))] matches!(call, Call::Balances(pallet_balances::Call::transfer { .. })) } } +#[cfg(feature = "runtime-benchmarks")] +impl MessagesConfig for Runtime { + fn maximal_message_size() -> u32 { + messages_source::maximal_message_size::() + } + + fn bridged_relayer_id() -> Self::InboundRelayer { + [0u8; 32].into() + } + + fn account_balance(account: &Self::AccountId) -> Self::OutboundMessageFee { + Balances::free_balance(account) + } + + fn endow_account(account: &Self::AccountId) { + Balances::make_free_balance_be(account, Balance::MAX / 100); + } + + fn prepare_outbound_message( + params: MessageParams, + ) -> (ToPolkadotMessagePayload, Balance) { + (prepare_outbound_message::(params), Self::message_fee()) + } + + fn prepare_message_proof( + params: MessageProofParams, + ) -> (messages_target::FromBridgedChainMessagesProof, bp_messages::Weight) { + Self::endow_account(&dispatch_account::()); + prepare_message_proof::( + params, + &crate::VERSION, + Balance::MAX / 100, + ) + } + + fn prepare_message_delivery_proof( + params: MessageDeliveryProofParams, + ) -> messages_source::FromBridgedChainMessagesDeliveryProof { + prepare_message_delivery_proof::( + params, + ) + } + + fn is_message_dispatched(nonce: bp_messages::MessageNonce) -> bool { + frame_system::Pallet::::events() + .into_iter() + .map(|event_record| event_record.event) + .any(|event| matches!( + event, + Event::BridgePolkadotMessagesDispatch(pallet_bridge_dispatch::Event::::MessageDispatched( + _, ([0, 0, 0, 0], nonce_from_event), _, + )) if nonce_from_event == nonce + )) + } +} + #[cfg(test)] mod tests { use bp_messages::{target_chain::ProvedLaneMessages, MessageData, MessageKey}; @@ -382,13 +478,13 @@ mod tests { ); let max_incoming_message_proof_size = bp_polkadot::EXTRA_STORAGE_PROOF_SIZE.saturating_add( - messages::target::maximal_incoming_message_size(bp_kusama::Kusama::max_extrinsic_size()), + messages_target::maximal_incoming_message_size(bp_kusama::Kusama::max_extrinsic_size()), ); pallet_bridge_messages::ensure_able_to_receive_message::( bp_kusama::Kusama::max_extrinsic_size(), bp_kusama::Kusama::max_extrinsic_weight(), max_incoming_message_proof_size, - messages::target::maximal_incoming_message_dispatch_weight(bp_kusama::Kusama::max_extrinsic_weight()), + messages_target::maximal_incoming_message_dispatch_weight(bp_kusama::Kusama::max_extrinsic_weight()), ); let max_incoming_inbound_lane_data_proof_size = bp_messages::InboundLaneData::<()>::encoded_size_hint( From b082dd7e5ee5833c59df520514307a1c242067d5 Mon Sep 17 00:00:00 2001 From: Svyatoslav Nikolsky Date: Mon, 7 Feb 2022 12:25:48 +0300 Subject: [PATCH 12/31] add benchmarks to polkadot runtime --- runtime/polkadot/Cargo.toml | 1 + runtime/polkadot/src/kusama_messages.rs | 143 ++++++++++++++++++++---- runtime/polkadot/src/lib.rs | 5 + 3 files changed, 126 insertions(+), 23 deletions(-) diff --git a/runtime/polkadot/Cargo.toml b/runtime/polkadot/Cargo.toml index 3b57814ddffc..ce76ae3f358b 100644 --- a/runtime/polkadot/Cargo.toml +++ b/runtime/polkadot/Cargo.toml @@ -192,6 +192,7 @@ std = [ "xcm-builder/std", ] runtime-benchmarks = [ + "bridge-runtime-common/runtime-benchmarks", "runtime-common/runtime-benchmarks", "frame-benchmarking/runtime-benchmarks", "frame-support/runtime-benchmarks", diff --git a/runtime/polkadot/src/kusama_messages.rs b/runtime/polkadot/src/kusama_messages.rs index 7b3d595bed1f..cd3aadc67a01 100644 --- a/runtime/polkadot/src/kusama_messages.rs +++ b/runtime/polkadot/src/kusama_messages.rs @@ -16,7 +16,7 @@ //! Over-bridge messaging support for Polkadot <> Kusama bridge. -use crate::{AccountId, Call, Origin, OriginCaller, RootAccountForPayments, Runtime}; +use crate::{AccountId, Balance, Balances, Call, Origin, OriginCaller, RootAccountForPayments, Runtime}; use bp_messages::{ source_chain::{LaneMessageVerifier, SenderOrigin, TargetHeaderChain}, @@ -24,7 +24,12 @@ use bp_messages::{ InboundLaneData, LaneId, Message, MessageNonce, OutboundLaneData, Parameter as MessagesParameter, }; use bp_runtime::{Chain, ChainId, POLKADOT_CHAIN_ID, KUSAMA_CHAIN_ID}; -use bridge_runtime_common::messages::{self, MessageBridge, MessageTransaction, ThisChainWithMessages}; +use bridge_runtime_common::messages::{ + source as messages_source, target as messages_target, + BridgedChainWithMessages, ChainWithMessages, MessageBridge, + MessageTransaction, ThisChainWithMessages, + transaction_payment, +}; use parity_scale_codec::{Decode, Encode}; use frame_support::{ parameter_types, @@ -36,6 +41,27 @@ use scale_info::TypeInfo; use sp_runtime::{traits::Saturating, FixedPointNumber, FixedU128}; use sp_std::{convert::TryFrom, ops::RangeInclusive}; +#[cfg(feature = "runtime-benchmarks")] +use crate::Event; +#[cfg(feature = "runtime-benchmarks")] +use bp_polkadot::{Hasher, Header}; +#[cfg(feature = "runtime-benchmarks")] +use bridge_runtime_common::messages_benchmarking::{ + dispatch_account, + prepare_message_delivery_proof, + prepare_message_proof, + prepare_outbound_message, +}; +#[cfg(feature = "runtime-benchmarks")] +use frame_support::traits::Currency; +#[cfg(feature = "runtime-benchmarks")] +use pallet_bridge_messages::benchmarking::{ + Config as MessagesConfig, + MessageDeliveryProofParams, + MessageParams, + MessageProofParams, +}; + /// Initial value of `KusamaToPolkadotConversionRate` parameter. pub const INITIAL_KUSAMA_TO_POLKADOT_CONVERSION_RATE: FixedU128 = FixedU128::from_inner(FixedU128::DIV); /// Initial value of `KusamaFeeMultiplier` parameter. @@ -51,16 +77,16 @@ parameter_types! { } /// Message payload for Polkadot -> Kusama messages. -pub type ToKusamaMessagePayload = messages::source::FromThisChainMessagePayload; +pub type ToKusamaMessagePayload = messages_source::FromThisChainMessagePayload; /// Message payload for Kusama -> Polkadot messages. -pub type FromKusamaMessagePayload = messages::target::FromBridgedChainMessagePayload; +pub type FromKusamaMessagePayload = messages_target::FromBridgedChainMessagePayload; /// Encoded Polkadot Call as it comes from Kusama. -pub type FromKusamaEncodedCall = messages::target::FromBridgedChainEncodedMessageCall; +pub type FromKusamaEncodedCall = messages_target::FromBridgedChainEncodedMessageCall; /// Call-dispatch based message dispatch for Kusama -> Polkadot messages. -pub type FromKusamaMessageDispatch = messages::target::FromBridgedChainMessageDispatch< +pub type FromKusamaMessageDispatch = messages_target::FromBridgedChainMessageDispatch< WithKusamaMessageBridge, crate::Runtime, pallet_balances::Pallet, @@ -68,6 +94,7 @@ pub type FromKusamaMessageDispatch = messages::target::FromBridgedChainMessageDi >; /// Error that happens when message is sent by anyone but `AllowedMessageSender`. +#[cfg(not(feature = "runtime-benchmarks"))] const NOT_ALLOWED_MESSAGE_SENDER: &str = "Cannot accept message from this account"; /// Error that happens when we are receiving incoming message via unexpected lane. const INBOUND_LANE_DISABLED: &str = "The inbound message lane is disaled."; @@ -93,13 +120,21 @@ impl LaneMessageVerifier< ) -> Result<(), Self::Error> { // we only allow messages to be sent by given account let allowed_sender = AllowedMessageSender::get(); - match allowed_sender { - Some(ref allowed_sender) if submitter.linked_account().as_ref() == Some(allowed_sender) => (), - _ => return Err(NOT_ALLOWED_MESSAGE_SENDER), + // for benchmarks we're still interested in this additional storage, read, but we don't + // want actual checks + #[cfg(feature = "runtime-benchmarks")] + drop(allowed_sender); + // outside of benchmarks, we only allow messages to be sent by given account + #[cfg(not(feature = "runtime-benchmarks"))] + { + match allowed_sender { + Some(ref allowed_sender) if submitter.linked_account().as_ref() == Some(allowed_sender) => (), + _ => return Err(NOT_ALLOWED_MESSAGE_SENDER), + } } // perform other checks - messages::source::FromThisChainMessageVerifier::::verify_message( + messages_source::FromThisChainMessageVerifier::::verify_message( submitter, delivery_and_dispatch_fee, lane, @@ -132,7 +167,7 @@ impl MessageBridge for WithKusamaMessageBridge { #[derive(RuntimeDebug, Clone, Copy)] pub struct Polkadot; -impl messages::ChainWithMessages for Polkadot { +impl ChainWithMessages for Polkadot { type Hash = bp_polkadot::Hash; type AccountId = bp_polkadot::AccountId; type Signer = bp_polkadot::AccountPublic; @@ -175,7 +210,7 @@ impl ThisChainWithMessages for Polkadot { let multiplier = FixedU128::saturating_from_rational(110, 100) .saturating_mul(pallet_transaction_payment::Pallet::::next_fee_multiplier()); let per_byte_fee = crate::TransactionByteFee::get(); - messages::transaction_payment( + transaction_payment( bp_polkadot::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic, per_byte_fee, multiplier, @@ -189,7 +224,7 @@ impl ThisChainWithMessages for Polkadot { #[derive(RuntimeDebug, Clone, Copy)] pub struct Kusama; -impl messages::ChainWithMessages for Kusama { +impl ChainWithMessages for Kusama { type Hash = bp_kusama::Hash; type AccountId = bp_kusama::AccountId; type Signer = bp_kusama::AccountPublic; @@ -198,14 +233,14 @@ impl messages::ChainWithMessages for Kusama { type Balance = bp_kusama::Balance; } -impl messages::BridgedChainWithMessages for Kusama { +impl BridgedChainWithMessages for Kusama { fn maximal_extrinsic_size() -> u32 { bp_kusama::Kusama::max_extrinsic_size() } fn message_weight_limits(_message_payload: &[u8]) -> RangeInclusive { // we don't want to relay too large messages + keep reserve for future upgrades - let upper_limit = messages::target::maximal_incoming_message_dispatch_weight( + let upper_limit = messages_target::maximal_incoming_message_dispatch_weight( bp_kusama::Kusama::max_extrinsic_weight(), ); @@ -245,7 +280,7 @@ impl messages::BridgedChainWithMessages for Kusama { // => it is a messages module parameter let multiplier = KusamaFeeMultiplier::get(); let per_byte_fee = bp_kusama::TRANSACTION_BYTE_FEE; - messages::transaction_payment( + transaction_payment( bp_kusama::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic, per_byte_fee, multiplier, @@ -257,16 +292,16 @@ impl messages::BridgedChainWithMessages for Kusama { impl TargetHeaderChain for Kusama { type Error = &'static str; - type MessagesDeliveryProof = messages::source::FromBridgedChainMessagesDeliveryProof; + type MessagesDeliveryProof = messages_source::FromBridgedChainMessagesDeliveryProof; fn verify_message(payload: &ToKusamaMessagePayload) -> Result<(), Self::Error> { - messages::source::verify_chain_message::(payload) + messages_source::verify_chain_message::(payload) } fn verify_messages_delivery_proof( proof: Self::MessagesDeliveryProof, ) -> Result<(LaneId, InboundLaneData), Self::Error> { - messages::source::verify_messages_delivery_proof::< + messages_source::verify_messages_delivery_proof::< WithKusamaMessageBridge, Runtime, crate::KusamaGrandpaInstance, @@ -276,13 +311,13 @@ impl TargetHeaderChain for Kusama impl SourceHeaderChain for Kusama { type Error = &'static str; - type MessagesProof = messages::target::FromBridgedChainMessagesProof; + type MessagesProof = messages_target::FromBridgedChainMessagesProof; fn verify_messages_proof( proof: Self::MessagesProof, messages_count: u32, ) -> Result>, Self::Error> { - messages::target::verify_messages_proof::< + messages_target::verify_messages_proof::< WithKusamaMessageBridge, Runtime, crate::KusamaGrandpaInstance, @@ -358,10 +393,72 @@ pub struct FromKusamaCallFilter; impl Contains for FromKusamaCallFilter { fn contains(call: &Call) -> bool { + #[cfg(feature = "runtime-benchmarks")] + { + drop(call); + true + } + #[cfg(not(feature = "runtime-benchmarks"))] matches!(call, Call::Balances(pallet_balances::Call::transfer { .. })) } } +#[cfg(feature = "runtime-benchmarks")] +impl MessagesConfig for Runtime { + fn maximal_message_size() -> u32 { + messages_source::maximal_message_size::() + } + + fn bridged_relayer_id() -> Self::InboundRelayer { + [0u8; 32].into() + } + + fn account_balance(account: &Self::AccountId) -> Self::OutboundMessageFee { + Balances::free_balance(account) + } + + fn endow_account(account: &Self::AccountId) { + Balances::make_free_balance_be(account, Balance::MAX / 100); + } + + fn prepare_outbound_message( + params: MessageParams, + ) -> (ToKusamaMessagePayload, Balance) { + (prepare_outbound_message::(params), Self::message_fee()) + } + + fn prepare_message_proof( + params: MessageProofParams, + ) -> (messages_target::FromBridgedChainMessagesProof, bp_messages::Weight) { + Self::endow_account(&dispatch_account::()); + prepare_message_proof::( + params, + &crate::VERSION, + Balance::MAX / 100, + ) + } + + fn prepare_message_delivery_proof( + params: MessageDeliveryProofParams, + ) -> messages_source::FromBridgedChainMessagesDeliveryProof { + prepare_message_delivery_proof::( + params, + ) + } + + fn is_message_dispatched(nonce: bp_messages::MessageNonce) -> bool { + frame_system::Pallet::::events() + .into_iter() + .map(|event_record| event_record.event) + .any(|event| matches!( + event, + Event::BridgeKusamaMessagesDispatch(pallet_bridge_dispatch::Event::::MessageDispatched( + _, ([0, 0, 0, 0], nonce_from_event), _, + )) if nonce_from_event == nonce + )) + } +} + #[cfg(test)] mod tests { use bp_messages::{target_chain::ProvedLaneMessages, MessageData, MessageKey}; @@ -382,13 +479,13 @@ mod tests { ); let max_incoming_message_proof_size = bp_kusama::EXTRA_STORAGE_PROOF_SIZE.saturating_add( - messages::target::maximal_incoming_message_size(bp_polkadot::Polkadot::max_extrinsic_size()), + messages_target::maximal_incoming_message_size(bp_polkadot::Polkadot::max_extrinsic_size()), ); pallet_bridge_messages::ensure_able_to_receive_message::( bp_polkadot::Polkadot::max_extrinsic_size(), bp_polkadot::Polkadot::max_extrinsic_weight(), max_incoming_message_proof_size, - messages::target::maximal_incoming_message_dispatch_weight(bp_polkadot::Polkadot::max_extrinsic_weight()), + messages_target::maximal_incoming_message_dispatch_weight(bp_polkadot::Polkadot::max_extrinsic_weight()), ); let max_incoming_inbound_lane_data_proof_size = bp_messages::InboundLaneData::<()>::encoded_size_hint( diff --git a/runtime/polkadot/src/lib.rs b/runtime/polkadot/src/lib.rs index 7636c8d559f1..66e72aad1e16 100644 --- a/runtime/polkadot/src/lib.rs +++ b/runtime/polkadot/src/lib.rs @@ -1831,6 +1831,9 @@ mod benches { [pallet_treasury, Treasury] [pallet_utility, Utility] [pallet_vesting, Vesting] + // Bridges + [pallet_bridge_grandpa, BridgeKusamaGrandpa] + [pallet_bridge_messages, MessagesBench::] ); } @@ -2212,6 +2215,7 @@ sp_api::impl_runtime_apis! { use pallet_offences_benchmarking::Pallet as OffencesBench; use frame_system_benchmarking::Pallet as SystemBench; use frame_benchmarking::baseline::Pallet as Baseline; + use pallet_bridge_messages::benchmarking::Pallet as MessagesBench; let mut list = Vec::::new(); list_benchmarks!(list, extra); @@ -2233,6 +2237,7 @@ sp_api::impl_runtime_apis! { use pallet_offences_benchmarking::Pallet as OffencesBench; use frame_system_benchmarking::Pallet as SystemBench; use frame_benchmarking::baseline::Pallet as Baseline; + use pallet_bridge_messages::benchmarking::Pallet as MessagesBench; impl pallet_session_benchmarking::Config for Runtime {} impl pallet_offences_benchmarking::Config for Runtime {} From 8edb53500b30730fdd8b493bafffc7c2bfbb2ccd Mon Sep 17 00:00:00 2001 From: Svyatoslav Nikolsky Date: Wed, 9 Feb 2022 13:46:23 +0300 Subject: [PATCH 13/31] couple of useful (ignored) tests --- runtime/kusama/src/polkadot_messages.rs | 44 +++++++++++++++++++------ runtime/polkadot/src/kusama_messages.rs | 44 +++++++++++++++++++------ 2 files changed, 68 insertions(+), 20 deletions(-) diff --git a/runtime/kusama/src/polkadot_messages.rs b/runtime/kusama/src/polkadot_messages.rs index e4c7175aebd0..f94bff2d2e07 100644 --- a/runtime/kusama/src/polkadot_messages.rs +++ b/runtime/kusama/src/polkadot_messages.rs @@ -461,10 +461,27 @@ impl MessagesConfig for Runtime { #[cfg(test)] mod tests { use bp_messages::{target_chain::ProvedLaneMessages, MessageData, MessageKey}; + use bridge_runtime_common::messages::source::estimate_message_dispatch_and_delivery_fee; + use frame_support::weights::GetDispatchInfo; use runtime_common::RocksDbWeight; use crate::*; use super::*; + fn message_payload(sender: bp_kusama::AccountId) -> ToPolkadotMessagePayload { + let call = Call::Balances(pallet_balances::Call::::transfer { + dest: bp_polkadot::AccountId::from([0u8; 32]).into(), + value: 10_000_000_000, + }); + let weight = call.get_dispatch_info().weight; + bp_message_dispatch::MessagePayload { + spec_version: 4242, + weight, + origin: bp_message_dispatch::CallOrigin::SourceAccount(sender), + dispatch_fee_payment: bp_runtime::messages::DispatchFeePayment::AtSourceChain, + call: call.encode(), + } + } + #[test] fn ensure_kusama_message_lane_weights_are_correct() { type Weights = pallet_bridge_messages::weights::MillauWeight; // TODO: use Kusama weights @@ -506,16 +523,6 @@ mod tests { #[test] fn message_by_invalid_submitter_are_rejected() { sp_io::TestExternalities::new(Default::default()).execute_with(|| { - fn message_payload(sender: bp_kusama::AccountId) -> ToPolkadotMessagePayload { - bp_message_dispatch::MessagePayload { - spec_version: 1, - weight: 100, - origin: bp_message_dispatch::CallOrigin::SourceAccount(sender), - dispatch_fee_payment: bp_runtime::messages::DispatchFeePayment::AtSourceChain, - call: vec![42], - } - } - let invalid_sender = bp_kusama::AccountId::from([1u8; 32]); let valid_sender = bp_kusama::AccountId::from([2u8; 32]); AllowedMessageSender::set(&Some(valid_sender.clone())); @@ -582,4 +589,21 @@ mod tests { Err(INBOUND_LANE_DISABLED), ); } + + #[test] + #[ignore] + fn estimate_kusama_to_polkadot_message_fee() { + sp_io::TestExternalities::new(Default::default()).execute_with(|| { + PolkadotToKusamaConversionRate::set(&FixedU128::from_float(8.93751388468141)); + let fee = estimate_message_dispatch_and_delivery_fee::( + &message_payload(bp_kusama::AccountId::from([1u8; 32])), + WithPolkadotMessageBridge::RELAYER_FEE_PERCENT, + ).unwrap(); + println!( + "Message fee for balances::transfer call is: {} ({} KSM)", + fee, + FixedU128::saturating_from_rational(fee, kusama_runtime_constants::currency::UNITS).to_float(), + ); + }); + } } diff --git a/runtime/polkadot/src/kusama_messages.rs b/runtime/polkadot/src/kusama_messages.rs index cd3aadc67a01..ee186f5b52ea 100644 --- a/runtime/polkadot/src/kusama_messages.rs +++ b/runtime/polkadot/src/kusama_messages.rs @@ -462,10 +462,27 @@ impl MessagesConfig for Runtime { #[cfg(test)] mod tests { use bp_messages::{target_chain::ProvedLaneMessages, MessageData, MessageKey}; + use bridge_runtime_common::messages::source::estimate_message_dispatch_and_delivery_fee; + use frame_support::weights::GetDispatchInfo; use runtime_common::RocksDbWeight; use crate::*; use super::*; + fn message_payload(sender: bp_polkadot::AccountId) -> ToKusamaMessagePayload { + let call = Call::Balances(pallet_balances::Call::::transfer { + dest: bp_polkadot::AccountId::from([0u8; 32]).into(), + value: 10_000_000_000, + }); + let weight = call.get_dispatch_info().weight; + bp_message_dispatch::MessagePayload { + spec_version: 4242, + weight, + origin: bp_message_dispatch::CallOrigin::SourceAccount(sender), + dispatch_fee_payment: bp_runtime::messages::DispatchFeePayment::AtSourceChain, + call: call.encode(), + } + } + #[test] fn ensure_polkadot_message_lane_weights_are_correct() { type Weights = pallet_bridge_messages::weights::MillauWeight; // TODO: use Polkadot weights @@ -507,16 +524,6 @@ mod tests { #[test] fn message_by_invalid_submitter_are_rejected() { sp_io::TestExternalities::new(Default::default()).execute_with(|| { - fn message_payload(sender: bp_polkadot::AccountId) -> ToKusamaMessagePayload { - bp_message_dispatch::MessagePayload { - spec_version: 1, - weight: 100, - origin: bp_message_dispatch::CallOrigin::SourceAccount(sender), - dispatch_fee_payment: bp_runtime::messages::DispatchFeePayment::AtSourceChain, - call: vec![42], - } - } - let invalid_sender = bp_polkadot::AccountId::from([1u8; 32]); let valid_sender = bp_polkadot::AccountId::from([2u8; 32]); AllowedMessageSender::set(&Some(valid_sender.clone())); @@ -583,4 +590,21 @@ mod tests { Err(INBOUND_LANE_DISABLED), ); } + + #[test] + #[ignore] + fn estimate_polkadot_to_kusama_message_fee() { + sp_io::TestExternalities::new(Default::default()).execute_with(|| { + KusamaToPolkadotConversionRate::set(&FixedU128::from_float(0.11188793806675539)); + let fee = estimate_message_dispatch_and_delivery_fee::( + &message_payload(bp_kusama::AccountId::from([1u8; 32])), + WithKusamaMessageBridge::RELAYER_FEE_PERCENT, + ).unwrap(); + println!( + "Message fee for balances::transfer call is: {} ({} DOT)", + fee, + FixedU128::saturating_from_rational(fee, polkadot_runtime_constants::currency::UNITS).to_float(), + ); + }); + } } From c1090347296300238435f43e19c2a2a0b179d038 Mon Sep 17 00:00:00 2001 From: Svyatoslav Nikolsky Date: Wed, 9 Feb 2022 13:47:52 +0300 Subject: [PATCH 14/31] forbid message send by regular accounts (tests still need to be fixed) --- runtime/kusama/src/polkadot_messages.rs | 5 ----- runtime/polkadot/src/kusama_messages.rs | 5 ----- 2 files changed, 10 deletions(-) diff --git a/runtime/kusama/src/polkadot_messages.rs b/runtime/kusama/src/polkadot_messages.rs index f94bff2d2e07..92dbcb0646a5 100644 --- a/runtime/kusama/src/polkadot_messages.rs +++ b/runtime/kusama/src/polkadot_messages.rs @@ -338,11 +338,6 @@ fn verify_inbound_messages_lane( impl SenderOrigin for Origin { fn linked_account(&self) -> Option { match self.caller { - OriginCaller::system(frame_system::RawOrigin::Signed(ref submitter)) => - Some(submitter.clone()), - OriginCaller::system(frame_system::RawOrigin::Root) | - OriginCaller::system(frame_system::RawOrigin::None) => - RootAccountForPayments::get(), OriginCaller::Council(_) => AllowedMessageSender::get(), // TODO: rename to council account, _ => None, } diff --git a/runtime/polkadot/src/kusama_messages.rs b/runtime/polkadot/src/kusama_messages.rs index ee186f5b52ea..27005d3df1a0 100644 --- a/runtime/polkadot/src/kusama_messages.rs +++ b/runtime/polkadot/src/kusama_messages.rs @@ -339,11 +339,6 @@ fn verify_inbound_messages_lane( impl SenderOrigin for Origin { fn linked_account(&self) -> Option { match self.caller { - OriginCaller::system(frame_system::RawOrigin::Signed(ref submitter)) => - Some(submitter.clone()), - OriginCaller::system(frame_system::RawOrigin::Root) | - OriginCaller::system(frame_system::RawOrigin::None) => - RootAccountForPayments::get(), OriginCaller::Council(_) => AllowedMessageSender::get(), // TODO: rename to council account, _ => None, } From 407ae6bae993cf11ac7e32039bc82ba16fc73201 Mon Sep 17 00:00:00 2001 From: Svyatoslav Nikolsky Date: Tue, 15 Mar 2022 17:11:12 +0300 Subject: [PATCH 15/31] prepare migrations to initialize bridge --- runtime/kusama/src/lib.rs | 34 +++++++++++++++++++++++++++++++++- runtime/polkadot/src/lib.rs | 34 +++++++++++++++++++++++++++++++++- 2 files changed, 66 insertions(+), 2 deletions(-) diff --git a/runtime/kusama/src/lib.rs b/runtime/kusama/src/lib.rs index 3d805f93a5c6..8ac0dbabf6ce 100644 --- a/runtime/kusama/src/lib.rs +++ b/runtime/kusama/src/lib.rs @@ -1613,7 +1613,7 @@ pub type Executive = frame_executive::Executive< frame_system::ChainContext, Runtime, AllPalletsWithSystem, - CrowdloanIndexMigration, + (CrowdloanIndexMigration, InitializePolkadotBridge), >; /// The payload being signed in the transactions. pub type SignedPayload = generic::SignedPayload; @@ -1635,6 +1635,38 @@ impl OnRuntimeUpgrade for CrowdloanIndexMigration { } } +/// Initialize with-Polkadot bridge. +pub struct InitializePolkadotBridge; + +impl OnRuntimeUpgrade for InitializePolkadotBridge { + fn on_runtime_upgrade() -> frame_support::weights::Weight { + let with_polkadot_grandpa_pallet_owner_id = AccountId::from([0xd4, 0x35, 0x93, 0xc7, 0x15, 0xfd, 0xd3, 0x1c, 0x61, 0x14, 0x1a, 0xbd, 0x04, 0xa9, 0x9f, 0xd6, 0x82, 0x2c, 0x85, 0x58, 0x85, 0x4c, 0xcd, 0xe3, 0x9a, 0x56, 0x84, 0xe7, 0xa5, 0x6d, 0xa2, 0x7d]); // TODO: update me + pallet_bridge_grandpa::PalletOwner::::put( + with_polkadot_grandpa_pallet_owner_id, + ); + let with_polkadot_messages_pallet_owner_id = AccountId::from([0xd4, 0x35, 0x93, 0xc7, 0x15, 0xfd, 0xd3, 0x1c, 0x61, 0x14, 0x1a, 0xbd, 0x04, 0xa9, 0x9f, 0xd6, 0x82, 0x2c, 0x85, 0x58, 0x85, 0x4c, 0xcd, 0xe3, 0x9a, 0x56, 0x84, 0xe7, 0xa5, 0x6d, 0xa2, 0x7d]); // TODO: update me + pallet_bridge_messages::PalletOwner::::put( + with_polkadot_messages_pallet_owner_id, + ); + + ::DbWeight::get().writes(2) + } + + #[cfg(feature = "try-runtime")] + fn pre_upgrade() -> Result<(), &'static str> { + ensure!(pallet_bridge_grandpa::PalletOwner::::get().is_none()); + ensure!(pallet_bridge_messages::PalletOwner::::get().is_none()); + Ok(()) + } + + #[cfg(feature = "try-runtime")] + fn post_upgrade() -> Result<(), &'static str> { + ensure!(pallet_bridge_grandpa::PalletOwner::::get().is_some()); + ensure!(pallet_bridge_messages::PalletOwner::::get().is_some()); + Ok(()) + } +} + #[cfg(feature = "runtime-benchmarks")] #[macro_use] extern crate frame_benchmarking; diff --git a/runtime/polkadot/src/lib.rs b/runtime/polkadot/src/lib.rs index 66e72aad1e16..3d1cd2a2e657 100644 --- a/runtime/polkadot/src/lib.rs +++ b/runtime/polkadot/src/lib.rs @@ -1566,7 +1566,7 @@ pub type Executive = frame_executive::Executive< frame_system::ChainContext, Runtime, AllPalletsWithSystem, - (FixCouncilDepositMigration, CrowdloanIndexMigration), + (FixCouncilDepositMigration, CrowdloanIndexMigration, InitializeKusamaBridge), >; /// The payload being signed in transactions. pub type SignedPayload = generic::SignedPayload; @@ -1782,6 +1782,38 @@ impl OnRuntimeUpgrade for FixCouncilDepositMigration { } } +/// Initialize with-Kusama bridge. +pub struct InitializeKusamaBridge; + +impl OnRuntimeUpgrade for InitializeKusamaBridge { + fn on_runtime_upgrade() -> frame_support::weights::Weight { + let with_kusama_grandpa_pallet_owner_id = AccountId::from([0xd4, 0x35, 0x93, 0xc7, 0x15, 0xfd, 0xd3, 0x1c, 0x61, 0x14, 0x1a, 0xbd, 0x04, 0xa9, 0x9f, 0xd6, 0x82, 0x2c, 0x85, 0x58, 0x85, 0x4c, 0xcd, 0xe3, 0x9a, 0x56, 0x84, 0xe7, 0xa5, 0x6d, 0xa2, 0x7d]); // TODO: update me + pallet_bridge_grandpa::PalletOwner::::put( + with_kusama_grandpa_pallet_owner_id, + ); + let with_kusama_messages_pallet_owner_id = AccountId::from([0xd4, 0x35, 0x93, 0xc7, 0x15, 0xfd, 0xd3, 0x1c, 0x61, 0x14, 0x1a, 0xbd, 0x04, 0xa9, 0x9f, 0xd6, 0x82, 0x2c, 0x85, 0x58, 0x85, 0x4c, 0xcd, 0xe3, 0x9a, 0x56, 0x84, 0xe7, 0xa5, 0x6d, 0xa2, 0x7d]); // TODO: update me + pallet_bridge_messages::PalletOwner::::put( + with_kusama_messages_pallet_owner_id, + ); + + ::DbWeight::get().writes(2) + } + + #[cfg(feature = "try-runtime")] + fn pre_upgrade() -> Result<(), &'static str> { + ensure!(pallet_bridge_grandpa::PalletOwner::::get().is_none()); + ensure!(pallet_bridge_messages::PalletOwner::::get().is_none()); + Ok(()) + } + + #[cfg(feature = "try-runtime")] + fn post_upgrade() -> Result<(), &'static str> { + ensure!(pallet_bridge_grandpa::PalletOwner::::get().is_some()); + ensure!(pallet_bridge_messages::PalletOwner::::get().is_some()); + Ok(()) + } +} + #[cfg(feature = "runtime-benchmarks")] #[macro_use] extern crate frame_benchmarking; From d5c60f8c6db198487d8ff468513d2efa9a3b3509 Mon Sep 17 00:00:00 2001 From: Svyatoslav Nikolsky Date: Thu, 17 Mar 2022 12:38:53 +0300 Subject: [PATCH 16/31] post-update fix --- runtime/kusama/src/lib.rs | 11 +++-------- runtime/kusama/src/polkadot_messages.rs | 11 ++++++++--- runtime/polkadot/src/kusama_messages.rs | 11 ++++++++--- runtime/polkadot/src/lib.rs | 11 +++-------- 4 files changed, 22 insertions(+), 22 deletions(-) diff --git a/runtime/kusama/src/lib.rs b/runtime/kusama/src/lib.rs index 8ac0dbabf6ce..d4c7263ed724 100644 --- a/runtime/kusama/src/lib.rs +++ b/runtime/kusama/src/lib.rs @@ -68,7 +68,7 @@ use sp_runtime::{ OpaqueKeys, SaturatedConversion, Verify, }, transaction_validity::{TransactionPriority, TransactionSource, TransactionValidity}, - ApplyExtrinsicResult, KeyTypeId, Perbill, Percent, Permill, + ApplyExtrinsicResult, FixedU128, KeyTypeId, Perbill, Percent, Permill, }; use sp_staking::SessionIndex; #[cfg(any(feature = "std", test))] @@ -1413,7 +1413,6 @@ parameter_types! { bp_polkadot::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX; pub const MaxUnconfirmedMessagesAtInboundLane: bp_messages::MessageNonce = bp_polkadot::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX; - pub const RootAccountForPayments: Option = None; pub const PolkadotChainId: bp_runtime::ChainId = bp_runtime::POLKADOT_CHAIN_ID; } @@ -1925,10 +1924,12 @@ sp_api::impl_runtime_apis! { fn estimate_message_delivery_and_dispatch_fee( _lane_id: bp_messages::LaneId, payload: polkadot_messages::ToPolkadotMessagePayload, + polkadot_to_kusama_conversion_rate_override: Option, ) -> Option { estimate_message_dispatch_and_delivery_fee::( &payload, polkadot_messages::WithPolkadotMessageBridge::RELAYER_FEE_PERCENT, + polkadot_to_kusama_conversion_rate_override, ).ok() } @@ -1945,12 +1946,6 @@ sp_api::impl_runtime_apis! { } } - impl bp_polkadot::FromPolkadotInboundLaneApi for Runtime { - fn unrewarded_relayers_state(lane: bp_messages::LaneId) -> bp_messages::UnrewardedRelayersState { - BridgePolkadotMessages::inbound_unrewarded_relayers_state(lane) - } - } - impl fg_primitives::GrandpaApi for Runtime { fn grandpa_authorities() -> Vec<(GrandpaId, u64)> { Grandpa::grandpa_authorities() diff --git a/runtime/kusama/src/polkadot_messages.rs b/runtime/kusama/src/polkadot_messages.rs index 92dbcb0646a5..7c615ead2b1d 100644 --- a/runtime/kusama/src/polkadot_messages.rs +++ b/runtime/kusama/src/polkadot_messages.rs @@ -16,7 +16,7 @@ //! Over-bridge messaging support for Kusama <> Polkadot bridge. -use crate::{AccountId, Balance, Balances, Call, Origin, OriginCaller, RootAccountForPayments, Runtime}; +use crate::{AccountId, Balance, Call, Origin, OriginCaller, Runtime}; use bp_messages::{ source_chain::{LaneMessageVerifier, SenderOrigin, TargetHeaderChain}, @@ -156,8 +156,13 @@ impl MessageBridge for WithPolkadotMessageBridge { type ThisChain = Kusama; type BridgedChain = Polkadot; - fn bridged_balance_to_this_balance(bridged_balance: bp_polkadot::Balance) -> bp_kusama::Balance { - bp_kusama::Balance::try_from(PolkadotToKusamaConversionRate::get().saturating_mul_int(bridged_balance)) + fn bridged_balance_to_this_balance( + bridged_balance: bp_polkadot::Balance, + polkadot_to_kusama_conversion_rate_override: Option, + ) -> bp_kusama::Balance { + let conversion_rate = polkadot_to_kusama_conversion_rate_override + .unwrap_or_else(|| PolkadotToKusamaConversionRate::get()); + bp_kusama::Balance::try_from(conversion_rate.saturating_mul_int(bridged_balance)) .unwrap_or(bp_kusama::Balance::MAX) } } diff --git a/runtime/polkadot/src/kusama_messages.rs b/runtime/polkadot/src/kusama_messages.rs index 27005d3df1a0..5be723d3c679 100644 --- a/runtime/polkadot/src/kusama_messages.rs +++ b/runtime/polkadot/src/kusama_messages.rs @@ -16,7 +16,7 @@ //! Over-bridge messaging support for Polkadot <> Kusama bridge. -use crate::{AccountId, Balance, Balances, Call, Origin, OriginCaller, RootAccountForPayments, Runtime}; +use crate::{AccountId, Call, Origin, OriginCaller, Runtime}; use bp_messages::{ source_chain::{LaneMessageVerifier, SenderOrigin, TargetHeaderChain}, @@ -157,8 +157,13 @@ impl MessageBridge for WithKusamaMessageBridge { type ThisChain = Polkadot; type BridgedChain = Kusama; - fn bridged_balance_to_this_balance(bridged_balance: bp_kusama::Balance) -> bp_polkadot::Balance { - bp_polkadot::Balance::try_from(KusamaToPolkadotConversionRate::get().saturating_mul_int(bridged_balance)) + fn bridged_balance_to_this_balance( + bridged_balance: bp_kusama::Balance, + kusama_to_polkadot_conversion_rate_override: Option, + ) -> bp_polkadot::Balance { + let conversion_rate = kusama_to_polkadot_conversion_rate_override + .unwrap_or_else(|| KusamaToPolkadotConversionRate::get()); + bp_polkadot::Balance::try_from(conversion_rate.saturating_mul_int(bridged_balance)) .unwrap_or(bp_polkadot::Balance::MAX) } } diff --git a/runtime/polkadot/src/lib.rs b/runtime/polkadot/src/lib.rs index 3d1cd2a2e657..281c462c7045 100644 --- a/runtime/polkadot/src/lib.rs +++ b/runtime/polkadot/src/lib.rs @@ -69,7 +69,7 @@ use sp_runtime::{ OpaqueKeys, SaturatedConversion, Verify, Zero, }, transaction_validity::{TransactionPriority, TransactionSource, TransactionValidity}, - ApplyExtrinsicResult, KeyTypeId, Perbill, Percent, Permill, + ApplyExtrinsicResult, FixedU128, KeyTypeId, Perbill, Percent, Permill, }; use sp_staking::SessionIndex; use sp_std::{cmp::Ordering, collections::btree_map::BTreeMap, prelude::*}; @@ -1380,7 +1380,6 @@ parameter_types! { bp_kusama::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX; pub const MaxUnconfirmedMessagesAtInboundLane: bp_messages::MessageNonce = bp_kusama::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX; - pub const RootAccountForPayments: Option = None; pub const KusamaChainId: bp_runtime::ChainId = bp_runtime::KUSAMA_CHAIN_ID; } @@ -2070,10 +2069,12 @@ sp_api::impl_runtime_apis! { fn estimate_message_delivery_and_dispatch_fee( _lane_id: bp_messages::LaneId, payload: kusama_messages::ToKusamaMessagePayload, + kusama_to_polkadot_conversion_rate_override: Option, ) -> Option { estimate_message_dispatch_and_delivery_fee::( &payload, kusama_messages::WithKusamaMessageBridge::RELAYER_FEE_PERCENT, + kusama_to_polkadot_conversion_rate_override, ).ok() } @@ -2090,12 +2091,6 @@ sp_api::impl_runtime_apis! { } } - impl bp_kusama::FromKusamaInboundLaneApi for Runtime { - fn unrewarded_relayers_state(lane: bp_messages::LaneId) -> bp_messages::UnrewardedRelayersState { - BridgeKusamaMessages::inbound_unrewarded_relayers_state(lane) - } - } - impl fg_primitives::GrandpaApi for Runtime { fn grandpa_authorities() -> Vec<(GrandpaId, u64)> { Grandpa::grandpa_authorities() From 8fd7701ad3b297a761fd1403ee0f6b5997e6a130 Mon Sep 17 00:00:00 2001 From: Svyatoslav Nikolsky Date: Mon, 21 Mar 2022 16:16:35 +0300 Subject: [PATCH 17/31] fixed/updated/removed some tests --- runtime/kusama/src/polkadot_messages.rs | 54 +++++++++++++------------ runtime/polkadot/src/kusama_messages.rs | 54 +++++++++++++------------ 2 files changed, 56 insertions(+), 52 deletions(-) diff --git a/runtime/kusama/src/polkadot_messages.rs b/runtime/kusama/src/polkadot_messages.rs index 7c615ead2b1d..7605e94f8778 100644 --- a/runtime/kusama/src/polkadot_messages.rs +++ b/runtime/kusama/src/polkadot_messages.rs @@ -343,7 +343,7 @@ fn verify_inbound_messages_lane( impl SenderOrigin for Origin { fn linked_account(&self) -> Option { match self.caller { - OriginCaller::Council(_) => AllowedMessageSender::get(), // TODO: rename to council account, + OriginCaller::Council(_) => AllowedMessageSender::get(), _ => None, } } @@ -461,9 +461,7 @@ impl MessagesConfig for Runtime { #[cfg(test)] mod tests { use bp_messages::{target_chain::ProvedLaneMessages, MessageData, MessageKey}; - use bridge_runtime_common::messages::source::estimate_message_dispatch_and_delivery_fee; use frame_support::weights::GetDispatchInfo; - use runtime_common::RocksDbWeight; use crate::*; use super::*; @@ -491,7 +489,7 @@ mod tests { bp_kusama::ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT, bp_kusama::MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT, bp_kusama::PAY_INBOUND_DISPATCH_FEE_WEIGHT, - RocksDbWeight::get(), + ::DbWeight::get(), ); let max_incoming_message_proof_size = bp_polkadot::EXTRA_STORAGE_PROOF_SIZE.saturating_add( @@ -516,7 +514,7 @@ mod tests { max_incoming_inbound_lane_data_proof_size, bp_polkadot::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX, bp_polkadot::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX, - RocksDbWeight::get(), + ::DbWeight::get(), ); } @@ -524,8 +522,9 @@ mod tests { fn message_by_invalid_submitter_are_rejected() { sp_io::TestExternalities::new(Default::default()).execute_with(|| { let invalid_sender = bp_kusama::AccountId::from([1u8; 32]); - let valid_sender = bp_kusama::AccountId::from([2u8; 32]); - AllowedMessageSender::set(&Some(valid_sender.clone())); + let allowed_sender = bp_kusama::AccountId::from([2u8; 32]); + let council_member = bp_kusama::AccountId::from([3u8; 32]); + AllowedMessageSender::set(&Some(allowed_sender.clone())); assert_eq!( ToPolkadotMessageVerifier::verify_message( @@ -539,11 +538,31 @@ mod tests { ); assert_eq!( ToPolkadotMessageVerifier::verify_message( - &frame_system::RawOrigin::Signed(valid_sender.clone()).into(), + &frame_system::RawOrigin::Signed(allowed_sender.clone()).into(), &bp_kusama::Balance::MAX, &Default::default(), &Default::default(), - &message_payload(valid_sender), + &message_payload(allowed_sender), + ), + Err(NOT_ALLOWED_MESSAGE_SENDER), + ); + assert_eq!( + ToPolkadotMessageVerifier::verify_message( + &OriginCaller::Council(pallet_collective::RawOrigin::Members(1, 1)).into(), + &bp_kusama::Balance::MAX, + &Default::default(), + &Default::default(), + &message_payload(council_member.clone()), + ), + Ok(()), + ); + assert_eq!( + ToPolkadotMessageVerifier::verify_message( + &OriginCaller::Council(pallet_collective::RawOrigin::Member(council_member.clone())).into(), + &bp_kusama::Balance::MAX, + &Default::default(), + &Default::default(), + &message_payload(council_member), ), Ok(()), ); @@ -589,21 +608,4 @@ mod tests { Err(INBOUND_LANE_DISABLED), ); } - - #[test] - #[ignore] - fn estimate_kusama_to_polkadot_message_fee() { - sp_io::TestExternalities::new(Default::default()).execute_with(|| { - PolkadotToKusamaConversionRate::set(&FixedU128::from_float(8.93751388468141)); - let fee = estimate_message_dispatch_and_delivery_fee::( - &message_payload(bp_kusama::AccountId::from([1u8; 32])), - WithPolkadotMessageBridge::RELAYER_FEE_PERCENT, - ).unwrap(); - println!( - "Message fee for balances::transfer call is: {} ({} KSM)", - fee, - FixedU128::saturating_from_rational(fee, kusama_runtime_constants::currency::UNITS).to_float(), - ); - }); - } } diff --git a/runtime/polkadot/src/kusama_messages.rs b/runtime/polkadot/src/kusama_messages.rs index 5be723d3c679..7ea49ca8b83a 100644 --- a/runtime/polkadot/src/kusama_messages.rs +++ b/runtime/polkadot/src/kusama_messages.rs @@ -344,7 +344,7 @@ fn verify_inbound_messages_lane( impl SenderOrigin for Origin { fn linked_account(&self) -> Option { match self.caller { - OriginCaller::Council(_) => AllowedMessageSender::get(), // TODO: rename to council account, + OriginCaller::Council(_) => AllowedMessageSender::get(), _ => None, } } @@ -462,9 +462,7 @@ impl MessagesConfig for Runtime { #[cfg(test)] mod tests { use bp_messages::{target_chain::ProvedLaneMessages, MessageData, MessageKey}; - use bridge_runtime_common::messages::source::estimate_message_dispatch_and_delivery_fee; use frame_support::weights::GetDispatchInfo; - use runtime_common::RocksDbWeight; use crate::*; use super::*; @@ -492,7 +490,7 @@ mod tests { bp_polkadot::ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT, bp_polkadot::MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT, bp_polkadot::PAY_INBOUND_DISPATCH_FEE_WEIGHT, - RocksDbWeight::get(), + ::DbWeight::get(), ); let max_incoming_message_proof_size = bp_kusama::EXTRA_STORAGE_PROOF_SIZE.saturating_add( @@ -517,7 +515,7 @@ mod tests { max_incoming_inbound_lane_data_proof_size, bp_polkadot::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX, bp_polkadot::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX, - RocksDbWeight::get(), + ::DbWeight::get(), ); } @@ -525,8 +523,9 @@ mod tests { fn message_by_invalid_submitter_are_rejected() { sp_io::TestExternalities::new(Default::default()).execute_with(|| { let invalid_sender = bp_polkadot::AccountId::from([1u8; 32]); - let valid_sender = bp_polkadot::AccountId::from([2u8; 32]); - AllowedMessageSender::set(&Some(valid_sender.clone())); + let allowed_sender = bp_polkadot::AccountId::from([2u8; 32]); + let council_member = bp_polkadot::AccountId::from([3u8; 32]); + AllowedMessageSender::set(&Some(allowed_sender.clone())); assert_eq!( ToKusamaMessageVerifier::verify_message( @@ -540,11 +539,31 @@ mod tests { ); assert_eq!( ToKusamaMessageVerifier::verify_message( - &frame_system::RawOrigin::Signed(valid_sender.clone()).into(), + &frame_system::RawOrigin::Signed(allowed_sender.clone()).into(), &bp_polkadot::Balance::MAX, &Default::default(), &Default::default(), - &message_payload(valid_sender), + &message_payload(allowed_sender), + ), + Err(NOT_ALLOWED_MESSAGE_SENDER), + ); + assert_eq!( + ToKusamaMessageVerifier::verify_message( + &OriginCaller::Council(pallet_collective::RawOrigin::Members(1, 1)).into(), + &bp_polkadot::Balance::MAX, + &Default::default(), + &Default::default(), + &message_payload(council_member.clone()), + ), + Ok(()), + ); + assert_eq!( + ToKusamaMessageVerifier::verify_message( + &OriginCaller::Council(pallet_collective::RawOrigin::Member(council_member.clone())).into(), + &bp_polkadot::Balance::MAX, + &Default::default(), + &Default::default(), + &message_payload(council_member), ), Ok(()), ); @@ -590,21 +609,4 @@ mod tests { Err(INBOUND_LANE_DISABLED), ); } - - #[test] - #[ignore] - fn estimate_polkadot_to_kusama_message_fee() { - sp_io::TestExternalities::new(Default::default()).execute_with(|| { - KusamaToPolkadotConversionRate::set(&FixedU128::from_float(0.11188793806675539)); - let fee = estimate_message_dispatch_and_delivery_fee::( - &message_payload(bp_kusama::AccountId::from([1u8; 32])), - WithKusamaMessageBridge::RELAYER_FEE_PERCENT, - ).unwrap(); - println!( - "Message fee for balances::transfer call is: {} ({} DOT)", - fee, - FixedU128::saturating_from_rational(fee, polkadot_runtime_constants::currency::UNITS).to_float(), - ); - }); - } } From 5ef944b413b6a8d22033d3c573135ba76f533e55 Mon Sep 17 00:00:00 2001 From: Svyatoslav Nikolsky Date: Mon, 21 Mar 2022 17:14:14 +0300 Subject: [PATCH 18/31] real pallet owners account ids --- runtime/kusama/src/lib.rs | 12 ++++++++++-- runtime/polkadot/src/lib.rs | 12 ++++++++++-- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/runtime/kusama/src/lib.rs b/runtime/kusama/src/lib.rs index d4c7263ed724..3aa80776fe35 100644 --- a/runtime/kusama/src/lib.rs +++ b/runtime/kusama/src/lib.rs @@ -1639,11 +1639,19 @@ pub struct InitializePolkadotBridge; impl OnRuntimeUpgrade for InitializePolkadotBridge { fn on_runtime_upgrade() -> frame_support::weights::Weight { - let with_polkadot_grandpa_pallet_owner_id = AccountId::from([0xd4, 0x35, 0x93, 0xc7, 0x15, 0xfd, 0xd3, 0x1c, 0x61, 0x14, 0x1a, 0xbd, 0x04, 0xa9, 0x9f, 0xd6, 0x82, 0x2c, 0x85, 0x58, 0x85, 0x4c, 0xcd, 0xe3, 0x9a, 0x56, 0x84, 0xe7, 0xa5, 0x6d, 0xa2, 0x7d]); // TODO: update me + // JHCUXbnaxTgZ8XgJvzKpV14q5iZjVemLadcLoARdRXwCob2 + let with_polkadot_grandpa_pallet_owner_id = AccountId::from([ + 0xfc, 0x5a, 0x85, 0xac, 0x73, 0xea, 0x4d, 0xa6, 0xa5, 0xc1, 0x80, 0xb9, 0xde, 0x40, 0xfd, 0x96, + 0x5b, 0x1e, 0xde, 0x62, 0x2e, 0xea, 0x1d, 0xe8, 0xeb, 0xc5, 0x97, 0x6d, 0x92, 0x89, 0x39, 0x77, + ]); pallet_bridge_grandpa::PalletOwner::::put( with_polkadot_grandpa_pallet_owner_id, ); - let with_polkadot_messages_pallet_owner_id = AccountId::from([0xd4, 0x35, 0x93, 0xc7, 0x15, 0xfd, 0xd3, 0x1c, 0x61, 0x14, 0x1a, 0xbd, 0x04, 0xa9, 0x9f, 0xd6, 0x82, 0x2c, 0x85, 0x58, 0x85, 0x4c, 0xcd, 0xe3, 0x9a, 0x56, 0x84, 0xe7, 0xa5, 0x6d, 0xa2, 0x7d]); // TODO: update me + // GU7SWSBoawXon8qbgR582KLP1h3q5YtNheKQwXtojnoCqXF + let with_polkadot_messages_pallet_owner_id = AccountId::from([ + 0xac, 0x34, 0xce, 0x53, 0x4f, 0x13, 0xbd, 0xef, 0x57, 0xfa, 0x02, 0xec, 0x63, 0x8b, 0x23, 0xd8, + 0xe0, 0xf7, 0x87, 0xdd, 0x1c, 0xd9, 0x40, 0x7f, 0xb2, 0xb8, 0xe9, 0x92, 0xf2, 0x25, 0xe6, 0x2f, + ]); pallet_bridge_messages::PalletOwner::::put( with_polkadot_messages_pallet_owner_id, ); diff --git a/runtime/polkadot/src/lib.rs b/runtime/polkadot/src/lib.rs index 281c462c7045..96bee429597a 100644 --- a/runtime/polkadot/src/lib.rs +++ b/runtime/polkadot/src/lib.rs @@ -1786,11 +1786,19 @@ pub struct InitializeKusamaBridge; impl OnRuntimeUpgrade for InitializeKusamaBridge { fn on_runtime_upgrade() -> frame_support::weights::Weight { - let with_kusama_grandpa_pallet_owner_id = AccountId::from([0xd4, 0x35, 0x93, 0xc7, 0x15, 0xfd, 0xd3, 0x1c, 0x61, 0x14, 0x1a, 0xbd, 0x04, 0xa9, 0x9f, 0xd6, 0x82, 0x2c, 0x85, 0x58, 0x85, 0x4c, 0xcd, 0xe3, 0x9a, 0x56, 0x84, 0xe7, 0xa5, 0x6d, 0xa2, 0x7d]); // TODO: update me + // 12pPqadtXfkC4Jz16Lhyx33KZabx1N3ioUNkrwUQUwvvRRvT + let with_kusama_grandpa_pallet_owner_id = AccountId::from([ + 0x50, 0x61, 0xa5, 0x47, 0x7e, 0x45, 0xdc, 0x62, 0xda, 0x52, 0xc9, 0x79, 0x86, 0x64, 0xc4, 0xdf, + 0xc8, 0xaa, 0x15, 0x27, 0x96, 0x77, 0xc6, 0xa2, 0x7a, 0xd2, 0xd5, 0x07, 0x8b, 0xa7, 0x7f, 0x03, + ]); pallet_bridge_grandpa::PalletOwner::::put( with_kusama_grandpa_pallet_owner_id, ); - let with_kusama_messages_pallet_owner_id = AccountId::from([0xd4, 0x35, 0x93, 0xc7, 0x15, 0xfd, 0xd3, 0x1c, 0x61, 0x14, 0x1a, 0xbd, 0x04, 0xa9, 0x9f, 0xd6, 0x82, 0x2c, 0x85, 0x58, 0x85, 0x4c, 0xcd, 0xe3, 0x9a, 0x56, 0x84, 0xe7, 0xa5, 0x6d, 0xa2, 0x7d]); // TODO: update me + // 1jhfovJDjGJz8vR75QqwgBsXn62USqW8xpY6KZus3mmACJA + let with_kusama_messages_pallet_owner_id = AccountId::from([ + 0x20, 0x91, 0x36, 0x21, 0x33, 0xf8, 0xaf, 0x3a, 0x2d, 0xf4, 0x71, 0x34, 0xe0, 0xd2, 0xf0, 0x62, + 0x58, 0xc0, 0x68, 0x38, 0x13, 0xf4, 0x5d, 0xb8, 0xa6, 0x02, 0x87, 0xd2, 0xcd, 0xce, 0x98, 0x7e, + ]); pallet_bridge_messages::PalletOwner::::put( with_kusama_messages_pallet_owner_id, ); From b2ff6528cdb83e50b64dbcf155264970c7257cca Mon Sep 17 00:00:00 2001 From: Svyatoslav Nikolsky Date: Mon, 21 Mar 2022 19:43:17 +0300 Subject: [PATCH 19/31] another post-merge fix --- bridges/bin/runtime-common/src/messages_benchmarking.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/bridges/bin/runtime-common/src/messages_benchmarking.rs b/bridges/bin/runtime-common/src/messages_benchmarking.rs index 903cf2fc2824..5e20078a2562 100644 --- a/bridges/bin/runtime-common/src/messages_benchmarking.rs +++ b/bridges/bin/runtime-common/src/messages_benchmarking.rs @@ -107,7 +107,6 @@ where BHH: Hasher>>, AccountIdOf>: PartialEq + sp_std::fmt::Debug, AccountIdOf>: From<[u8; 32]>, - AccountIdOf>: PartialEq + sp_std::fmt::Debug, BalanceOf>: Debug + MaybeSerializeDeserialize, CallOf>: From> + GetDispatchInfo, HashOf>: Copy + Default, From deb5e10202feffff9135f282d22d4539eb15e877 Mon Sep 17 00:00:00 2001 From: Svyatoslav Nikolsky Date: Mon, 21 Mar 2022 19:49:51 +0300 Subject: [PATCH 20/31] revert council members = initial authorities --- node/service/src/chain_spec.rs | 16 ++-------------- 1 file changed, 2 insertions(+), 14 deletions(-) diff --git a/node/service/src/chain_spec.rs b/node/service/src/chain_spec.rs index d52fa980f1ba..3f75a69885fe 100644 --- a/node/service/src/chain_spec.rs +++ b/node/service/src/chain_spec.rs @@ -1332,13 +1332,7 @@ pub fn polkadot_testnet_genesis( }, phragmen_election: Default::default(), democracy: polkadot::DemocracyConfig::default(), - council: polkadot::CouncilConfig { - members: initial_authorities - .iter() - .map(|x| x.0.clone()) - .collect::>(), - phantom: Default::default() - }, + council: polkadot::CouncilConfig { members: vec![], phantom: Default::default() }, technical_committee: polkadot::TechnicalCommitteeConfig { members: vec![], phantom: Default::default(), @@ -1432,13 +1426,7 @@ pub fn kusama_testnet_genesis( }, phragmen_election: Default::default(), democracy: kusama::DemocracyConfig::default(), - council: kusama::CouncilConfig { - members: initial_authorities - .iter() - .map(|x| x.0.clone()) - .collect::>(), - phantom: Default::default(), - }, + council: kusama::CouncilConfig { members: vec![], phantom: Default::default() }, technical_committee: kusama::TechnicalCommitteeConfig { members: vec![], phantom: Default::default(), From e7ff1662718510e880c347e036fbe543cd4d20cd Mon Sep 17 00:00:00 2001 From: Svyatoslav Nikolsky Date: Tue, 22 Mar 2022 09:33:44 +0300 Subject: [PATCH 21/31] fix benchmarks --- runtime/kusama/src/polkadot_messages.rs | 11 ++++++++--- runtime/polkadot/src/kusama_messages.rs | 13 +++++++++---- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/runtime/kusama/src/polkadot_messages.rs b/runtime/kusama/src/polkadot_messages.rs index 7605e94f8778..d05edd430a98 100644 --- a/runtime/kusama/src/polkadot_messages.rs +++ b/runtime/kusama/src/polkadot_messages.rs @@ -42,7 +42,7 @@ use sp_runtime::{traits::Saturating, FixedPointNumber, FixedU128}; use sp_std::{convert::TryFrom, ops::RangeInclusive}; #[cfg(feature = "runtime-benchmarks")] -use crate::Event; +use crate::{Balances, Event}; #[cfg(feature = "runtime-benchmarks")] use bp_polkadot::{Hasher, Header}; #[cfg(feature = "runtime-benchmarks")] @@ -343,6 +343,11 @@ fn verify_inbound_messages_lane( impl SenderOrigin for Origin { fn linked_account(&self) -> Option { match self.caller { + // in benchmarks we accept messages from regular users + #[cfg(feature = "runtime-benchmarks")] + crate::OriginCaller::system(frame_system::RawOrigin::Signed(ref submitter)) => + Some(submitter.clone()), + OriginCaller::Council(_) => AllowedMessageSender::get(), _ => None, } @@ -422,7 +427,7 @@ impl MessagesConfig for Runtime { fn prepare_outbound_message( params: MessageParams, - ) -> (ToPolkadotMessagePayload, Balance) { + ) -> (ToPolkadotMessagePayload, bp_kusama::Balance) { (prepare_outbound_message::(params), Self::message_fee()) } @@ -433,7 +438,7 @@ impl MessagesConfig for Runtime { prepare_message_proof::( params, &crate::VERSION, - Balance::MAX / 100, + bp_kusama::Balance::MAX / 100, ) } diff --git a/runtime/polkadot/src/kusama_messages.rs b/runtime/polkadot/src/kusama_messages.rs index 7ea49ca8b83a..9e3214419365 100644 --- a/runtime/polkadot/src/kusama_messages.rs +++ b/runtime/polkadot/src/kusama_messages.rs @@ -42,7 +42,7 @@ use sp_runtime::{traits::Saturating, FixedPointNumber, FixedU128}; use sp_std::{convert::TryFrom, ops::RangeInclusive}; #[cfg(feature = "runtime-benchmarks")] -use crate::Event; +use crate::{Balances, Event}; #[cfg(feature = "runtime-benchmarks")] use bp_polkadot::{Hasher, Header}; #[cfg(feature = "runtime-benchmarks")] @@ -344,6 +344,11 @@ fn verify_inbound_messages_lane( impl SenderOrigin for Origin { fn linked_account(&self) -> Option { match self.caller { + // in benchmarks we accept messages from regular users + #[cfg(feature = "runtime-benchmarks")] + crate::OriginCaller::system(frame_system::RawOrigin::Signed(ref submitter)) => + Some(submitter.clone()), + OriginCaller::Council(_) => AllowedMessageSender::get(), _ => None, } @@ -418,12 +423,12 @@ impl MessagesConfig for Runtime { } fn endow_account(account: &Self::AccountId) { - Balances::make_free_balance_be(account, Balance::MAX / 100); + Balances::make_free_balance_be(account, bp_polkadot::Balance::MAX / 100); } fn prepare_outbound_message( params: MessageParams, - ) -> (ToKusamaMessagePayload, Balance) { + ) -> (ToKusamaMessagePayload, bp_polkadot::Balance) { (prepare_outbound_message::(params), Self::message_fee()) } @@ -434,7 +439,7 @@ impl MessagesConfig for Runtime { prepare_message_proof::( params, &crate::VERSION, - Balance::MAX / 100, + bp_polkadot::Balance::MAX / 100, ) } From 7a3e9f7d659f4b7495add42cd03245f955118083 Mon Sep 17 00:00:00 2001 From: Svyatoslav Nikolsky Date: Tue, 22 Mar 2022 09:36:14 +0300 Subject: [PATCH 22/31] cargo fmt --- runtime/kusama/src/lib.rs | 43 ++++--- runtime/kusama/src/polkadot_messages.rs | 112 ++++++++++--------- runtime/polkadot/src/kusama_messages.rs | 142 +++++++++++++----------- runtime/polkadot/src/lib.rs | 41 ++++--- 4 files changed, 190 insertions(+), 148 deletions(-) diff --git a/runtime/kusama/src/lib.rs b/runtime/kusama/src/lib.rs index 3aa80776fe35..eeebbf343a4a 100644 --- a/runtime/kusama/src/lib.rs +++ b/runtime/kusama/src/lib.rs @@ -45,7 +45,9 @@ use runtime_parachains::{ use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId; use beefy_primitives::crypto::AuthorityId as BeefyId; -use bridge_runtime_common::messages::{source::estimate_message_dispatch_and_delivery_fee, MessageBridge}; +use bridge_runtime_common::messages::{ + source::estimate_message_dispatch_and_delivery_fee, MessageBridge, +}; use frame_support::{ construct_runtime, parameter_types, traits::{ @@ -1438,12 +1440,13 @@ impl pallet_bridge_messages::Config for Runtime { type TargetHeaderChain = polkadot_messages::Polkadot; type LaneMessageVerifier = polkadot_messages::ToPolkadotMessageVerifier; - type MessageDeliveryAndDispatchPayment = pallet_bridge_messages::instant_payments::InstantCurrencyPayments< - Runtime, - WithPolkadotMessagesInstance, - pallet_balances::Pallet, - polkadot_messages::GetDeliveryConfirmationTransactionFee, - >; + type MessageDeliveryAndDispatchPayment = + pallet_bridge_messages::instant_payments::InstantCurrencyPayments< + Runtime, + WithPolkadotMessagesInstance, + pallet_balances::Pallet, + polkadot_messages::GetDeliveryConfirmationTransactionFee, + >; type OnMessageAccepted = (); type OnDeliveryConfirmed = (); @@ -1641,16 +1644,18 @@ impl OnRuntimeUpgrade for InitializePolkadotBridge { fn on_runtime_upgrade() -> frame_support::weights::Weight { // JHCUXbnaxTgZ8XgJvzKpV14q5iZjVemLadcLoARdRXwCob2 let with_polkadot_grandpa_pallet_owner_id = AccountId::from([ - 0xfc, 0x5a, 0x85, 0xac, 0x73, 0xea, 0x4d, 0xa6, 0xa5, 0xc1, 0x80, 0xb9, 0xde, 0x40, 0xfd, 0x96, - 0x5b, 0x1e, 0xde, 0x62, 0x2e, 0xea, 0x1d, 0xe8, 0xeb, 0xc5, 0x97, 0x6d, 0x92, 0x89, 0x39, 0x77, + 0xfc, 0x5a, 0x85, 0xac, 0x73, 0xea, 0x4d, 0xa6, 0xa5, 0xc1, 0x80, 0xb9, 0xde, 0x40, + 0xfd, 0x96, 0x5b, 0x1e, 0xde, 0x62, 0x2e, 0xea, 0x1d, 0xe8, 0xeb, 0xc5, 0x97, 0x6d, + 0x92, 0x89, 0x39, 0x77, ]); pallet_bridge_grandpa::PalletOwner::::put( with_polkadot_grandpa_pallet_owner_id, ); // GU7SWSBoawXon8qbgR582KLP1h3q5YtNheKQwXtojnoCqXF let with_polkadot_messages_pallet_owner_id = AccountId::from([ - 0xac, 0x34, 0xce, 0x53, 0x4f, 0x13, 0xbd, 0xef, 0x57, 0xfa, 0x02, 0xec, 0x63, 0x8b, 0x23, 0xd8, - 0xe0, 0xf7, 0x87, 0xdd, 0x1c, 0xd9, 0x40, 0x7f, 0xb2, 0xb8, 0xe9, 0x92, 0xf2, 0x25, 0xe6, 0x2f, + 0xac, 0x34, 0xce, 0x53, 0x4f, 0x13, 0xbd, 0xef, 0x57, 0xfa, 0x02, 0xec, 0x63, 0x8b, + 0x23, 0xd8, 0xe0, 0xf7, 0x87, 0xdd, 0x1c, 0xd9, 0x40, 0x7f, 0xb2, 0xb8, 0xe9, 0x92, + 0xf2, 0x25, 0xe6, 0x2f, ]); pallet_bridge_messages::PalletOwner::::put( with_polkadot_messages_pallet_owner_id, @@ -1661,15 +1666,23 @@ impl OnRuntimeUpgrade for InitializePolkadotBridge { #[cfg(feature = "try-runtime")] fn pre_upgrade() -> Result<(), &'static str> { - ensure!(pallet_bridge_grandpa::PalletOwner::::get().is_none()); - ensure!(pallet_bridge_messages::PalletOwner::::get().is_none()); + ensure!( + pallet_bridge_grandpa::PalletOwner::::get().is_none() + ); + ensure!(pallet_bridge_messages::PalletOwner::::get( + ) + .is_none()); Ok(()) } #[cfg(feature = "try-runtime")] fn post_upgrade() -> Result<(), &'static str> { - ensure!(pallet_bridge_grandpa::PalletOwner::::get().is_some()); - ensure!(pallet_bridge_messages::PalletOwner::::get().is_some()); + ensure!( + pallet_bridge_grandpa::PalletOwner::::get().is_some() + ); + ensure!(pallet_bridge_messages::PalletOwner::::get( + ) + .is_some()); Ok(()) } } diff --git a/runtime/kusama/src/polkadot_messages.rs b/runtime/kusama/src/polkadot_messages.rs index d05edd430a98..b4f0f858de92 100644 --- a/runtime/kusama/src/polkadot_messages.rs +++ b/runtime/kusama/src/polkadot_messages.rs @@ -21,22 +21,22 @@ use crate::{AccountId, Balance, Call, Origin, OriginCaller, Runtime}; use bp_messages::{ source_chain::{LaneMessageVerifier, SenderOrigin, TargetHeaderChain}, target_chain::{ProvedMessages, SourceHeaderChain}, - InboundLaneData, LaneId, Message, MessageNonce, OutboundLaneData, Parameter as MessagesParameter, + InboundLaneData, LaneId, Message, MessageNonce, OutboundLaneData, + Parameter as MessagesParameter, }; use bp_runtime::{Chain, ChainId, KUSAMA_CHAIN_ID, POLKADOT_CHAIN_ID}; use bridge_runtime_common::messages::{ - source as messages_source, target as messages_target, - BridgedChainWithMessages, ChainWithMessages, MessageBridge, - MessageTransaction, ThisChainWithMessages, - transaction_payment, + source as messages_source, target as messages_target, transaction_payment, + BridgedChainWithMessages, ChainWithMessages, MessageBridge, MessageTransaction, + ThisChainWithMessages, }; -use parity_scale_codec::{Decode, Encode}; use frame_support::{ parameter_types, traits::{Contains, Get}, weights::{DispatchClass, Weight, WeightToFeePolynomial}, RuntimeDebug, }; +use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; use sp_runtime::{traits::Saturating, FixedPointNumber, FixedU128}; use sp_std::{convert::TryFrom, ops::RangeInclusive}; @@ -47,23 +47,19 @@ use crate::{Balances, Event}; use bp_polkadot::{Hasher, Header}; #[cfg(feature = "runtime-benchmarks")] use bridge_runtime_common::messages_benchmarking::{ - dispatch_account, - prepare_message_delivery_proof, - prepare_message_proof, + dispatch_account, prepare_message_delivery_proof, prepare_message_proof, prepare_outbound_message, }; #[cfg(feature = "runtime-benchmarks")] use frame_support::traits::Currency; #[cfg(feature = "runtime-benchmarks")] use pallet_bridge_messages::benchmarking::{ - Config as MessagesConfig, - MessageDeliveryProofParams, - MessageParams, - MessageProofParams, + Config as MessagesConfig, MessageDeliveryProofParams, MessageParams, MessageProofParams, }; /// Initial value of `PolkadotToKusamaConversionRate` parameter. -pub const INITIAL_POLKADOT_TO_KUSAMA_CONVERSION_RATE: FixedU128 = FixedU128::from_inner(FixedU128::DIV); +pub const INITIAL_POLKADOT_TO_KUSAMA_CONVERSION_RATE: FixedU128 = + FixedU128::from_inner(FixedU128::DIV); /// Initial value of `PolkadotFeeMultiplier` parameter. pub const INITIAL_POLKADOT_FEE_MULTIPLIER: FixedU128 = FixedU128::from_inner(FixedU128::DIV); @@ -77,10 +73,12 @@ parameter_types! { } /// Message payload for Kusama -> Polkadot messages. -pub type ToPolkadotMessagePayload = messages_source::FromThisChainMessagePayload; +pub type ToPolkadotMessagePayload = + messages_source::FromThisChainMessagePayload; /// Message payload for Polkadot -> Kusama messages. -pub type FromPolkadotMessagePayload = messages_target::FromBridgedChainMessagePayload; +pub type FromPolkadotMessagePayload = + messages_target::FromBridgedChainMessagePayload; /// Encoded Kusama Call as it comes from Polkadot. pub type FromPolkadotEncodedCall = messages_target::FromBridgedChainEncodedMessageCall; @@ -103,12 +101,9 @@ const INBOUND_LANE_DISABLED: &str = "The inbound message lane is disaled."; #[derive(RuntimeDebug)] pub struct ToPolkadotMessageVerifier; -impl LaneMessageVerifier< - Origin, - bp_kusama::AccountId, - ToPolkadotMessagePayload, - bp_kusama::Balance, -> for ToPolkadotMessageVerifier { +impl LaneMessageVerifier + for ToPolkadotMessageVerifier +{ type Error = &'static str; fn verify_message( @@ -127,7 +122,9 @@ impl LaneMessageVerifier< #[cfg(not(feature = "runtime-benchmarks"))] { match allowed_sender { - Some(ref allowed_sender) if submitter.linked_account().as_ref() == Some(allowed_sender) => (), + Some(ref allowed_sender) + if submitter.linked_account().as_ref() == Some(allowed_sender) => + (), _ => return Err(NOT_ALLOWED_MESSAGE_SENDER), } } @@ -296,7 +293,8 @@ impl BridgedChainWithMessages for Polkadot { impl TargetHeaderChain for Polkadot { type Error = &'static str; - type MessagesDeliveryProof = messages_source::FromBridgedChainMessagesDeliveryProof; + type MessagesDeliveryProof = + messages_source::FromBridgedChainMessagesDeliveryProof; fn verify_message(payload: &ToPolkadotMessagePayload) -> Result<(), Self::Error> { messages_source::verify_chain_message::(payload) @@ -325,7 +323,8 @@ impl SourceHeaderChain for Polkadot { WithPolkadotMessageBridge, Runtime, crate::PolkadotGrandpaInstance, - >(proof, messages_count).and_then(verify_inbound_messages_lane) + >(proof, messages_count) + .and_then(verify_inbound_messages_lane) } } @@ -335,7 +334,7 @@ fn verify_inbound_messages_lane( ) -> Result>, &'static str> { let allowed_incoming_lanes = [[0, 0, 0, 0]]; if messages.keys().any(|lane_id| !allowed_incoming_lanes.contains(lane_id)) { - return Err(INBOUND_LANE_DISABLED); + return Err(INBOUND_LANE_DISABLED) } Ok(messages) } @@ -368,7 +367,9 @@ pub enum WithPolkadotMessageBridgeParameter { impl MessagesParameter for WithPolkadotMessageBridgeParameter { fn save(&self) { match *self { - WithPolkadotMessageBridgeParameter::PolkadotToKusamaConversionRate(ref conversion_rate) => { + WithPolkadotMessageBridgeParameter::PolkadotToKusamaConversionRate( + ref conversion_rate, + ) => { PolkadotToKusamaConversionRate::set(conversion_rate); }, WithPolkadotMessageBridgeParameter::PolkadotFeeMultiplier(ref fee_multiplier) => { @@ -376,7 +377,7 @@ impl MessagesParameter for WithPolkadotMessageBridgeParameter { }, WithPolkadotMessageBridgeParameter::AllowedMessageSender(ref message_sender) => { AllowedMessageSender::set(message_sender); - } + }, } } } @@ -465,10 +466,10 @@ impl MessagesConfig for Runtime { #[cfg(test)] mod tests { + use super::*; + use crate::*; use bp_messages::{target_chain::ProvedLaneMessages, MessageData, MessageKey}; use frame_support::weights::GetDispatchInfo; - use crate::*; - use super::*; fn message_payload(sender: bp_kusama::AccountId) -> ToPolkadotMessagePayload { let call = Call::Balances(pallet_balances::Call::::transfer { @@ -504,15 +505,18 @@ mod tests { bp_kusama::Kusama::max_extrinsic_size(), bp_kusama::Kusama::max_extrinsic_weight(), max_incoming_message_proof_size, - messages_target::maximal_incoming_message_dispatch_weight(bp_kusama::Kusama::max_extrinsic_weight()), + messages_target::maximal_incoming_message_dispatch_weight( + bp_kusama::Kusama::max_extrinsic_weight(), + ), ); - let max_incoming_inbound_lane_data_proof_size = bp_messages::InboundLaneData::<()>::encoded_size_hint( - bp_kusama::MAXIMAL_ENCODED_ACCOUNT_ID_SIZE, - bp_polkadot::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX as _, - bp_polkadot::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX as _, - ) - .unwrap_or(u32::MAX); + let max_incoming_inbound_lane_data_proof_size = + bp_messages::InboundLaneData::<()>::encoded_size_hint( + bp_kusama::MAXIMAL_ENCODED_ACCOUNT_ID_SIZE, + bp_polkadot::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX as _, + bp_polkadot::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX as _, + ) + .unwrap_or(u32::MAX); pallet_bridge_messages::ensure_able_to_receive_confirmation::( bp_kusama::Kusama::max_extrinsic_size(), bp_kusama::Kusama::max_extrinsic_weight(), @@ -563,7 +567,10 @@ mod tests { ); assert_eq!( ToPolkadotMessageVerifier::verify_message( - &OriginCaller::Council(pallet_collective::RawOrigin::Member(council_member.clone())).into(), + &OriginCaller::Council(pallet_collective::RawOrigin::Member( + council_member.clone() + )) + .into(), &bp_kusama::Balance::MAX, &Default::default(), &Default::default(), @@ -575,18 +582,18 @@ mod tests { } fn proved_messages(lane_id: LaneId) -> ProvedMessages> { - vec![ - ( - lane_id, - ProvedLaneMessages { - lane_state: None, - messages: vec![Message { - key: MessageKey { lane_id, nonce: 0 }, - data: MessageData { payload: vec![], fee: 0 }, - }], - }, - ) - ].into_iter().collect() + vec![( + lane_id, + ProvedLaneMessages { + lane_state: None, + messages: vec![Message { + key: MessageKey { lane_id, nonce: 0 }, + data: MessageData { payload: vec![], fee: 0 }, + }], + }, + )] + .into_iter() + .collect() } #[test] @@ -608,9 +615,6 @@ mod tests { .into_iter() .chain(proved_messages([0, 0, 0, 1])) .collect(); - assert_eq!( - verify_inbound_messages_lane(proved_messages), - Err(INBOUND_LANE_DISABLED), - ); + assert_eq!(verify_inbound_messages_lane(proved_messages), Err(INBOUND_LANE_DISABLED),); } } diff --git a/runtime/polkadot/src/kusama_messages.rs b/runtime/polkadot/src/kusama_messages.rs index 9e3214419365..09430f066285 100644 --- a/runtime/polkadot/src/kusama_messages.rs +++ b/runtime/polkadot/src/kusama_messages.rs @@ -21,22 +21,22 @@ use crate::{AccountId, Call, Origin, OriginCaller, Runtime}; use bp_messages::{ source_chain::{LaneMessageVerifier, SenderOrigin, TargetHeaderChain}, target_chain::{ProvedMessages, SourceHeaderChain}, - InboundLaneData, LaneId, Message, MessageNonce, OutboundLaneData, Parameter as MessagesParameter, + InboundLaneData, LaneId, Message, MessageNonce, OutboundLaneData, + Parameter as MessagesParameter, }; -use bp_runtime::{Chain, ChainId, POLKADOT_CHAIN_ID, KUSAMA_CHAIN_ID}; +use bp_runtime::{Chain, ChainId, KUSAMA_CHAIN_ID, POLKADOT_CHAIN_ID}; use bridge_runtime_common::messages::{ - source as messages_source, target as messages_target, - BridgedChainWithMessages, ChainWithMessages, MessageBridge, - MessageTransaction, ThisChainWithMessages, - transaction_payment, + source as messages_source, target as messages_target, transaction_payment, + BridgedChainWithMessages, ChainWithMessages, MessageBridge, MessageTransaction, + ThisChainWithMessages, }; -use parity_scale_codec::{Decode, Encode}; use frame_support::{ parameter_types, traits::{Contains, Get}, weights::{DispatchClass, Weight, WeightToFeePolynomial}, RuntimeDebug, }; +use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; use sp_runtime::{traits::Saturating, FixedPointNumber, FixedU128}; use sp_std::{convert::TryFrom, ops::RangeInclusive}; @@ -47,23 +47,19 @@ use crate::{Balances, Event}; use bp_polkadot::{Hasher, Header}; #[cfg(feature = "runtime-benchmarks")] use bridge_runtime_common::messages_benchmarking::{ - dispatch_account, - prepare_message_delivery_proof, - prepare_message_proof, + dispatch_account, prepare_message_delivery_proof, prepare_message_proof, prepare_outbound_message, }; #[cfg(feature = "runtime-benchmarks")] use frame_support::traits::Currency; #[cfg(feature = "runtime-benchmarks")] use pallet_bridge_messages::benchmarking::{ - Config as MessagesConfig, - MessageDeliveryProofParams, - MessageParams, - MessageProofParams, + Config as MessagesConfig, MessageDeliveryProofParams, MessageParams, MessageProofParams, }; /// Initial value of `KusamaToPolkadotConversionRate` parameter. -pub const INITIAL_KUSAMA_TO_POLKADOT_CONVERSION_RATE: FixedU128 = FixedU128::from_inner(FixedU128::DIV); +pub const INITIAL_KUSAMA_TO_POLKADOT_CONVERSION_RATE: FixedU128 = + FixedU128::from_inner(FixedU128::DIV); /// Initial value of `KusamaFeeMultiplier` parameter. pub const INITIAL_KUSAMA_FEE_MULTIPLIER: FixedU128 = FixedU128::from_inner(FixedU128::DIV); @@ -77,10 +73,12 @@ parameter_types! { } /// Message payload for Polkadot -> Kusama messages. -pub type ToKusamaMessagePayload = messages_source::FromThisChainMessagePayload; +pub type ToKusamaMessagePayload = + messages_source::FromThisChainMessagePayload; /// Message payload for Kusama -> Polkadot messages. -pub type FromKusamaMessagePayload = messages_target::FromBridgedChainMessagePayload; +pub type FromKusamaMessagePayload = + messages_target::FromBridgedChainMessagePayload; /// Encoded Polkadot Call as it comes from Kusama. pub type FromKusamaEncodedCall = messages_target::FromBridgedChainEncodedMessageCall; @@ -103,12 +101,14 @@ const INBOUND_LANE_DISABLED: &str = "The inbound message lane is disaled."; #[derive(RuntimeDebug)] pub struct ToKusamaMessageVerifier; -impl LaneMessageVerifier< - Origin, - bp_polkadot::AccountId, - ToKusamaMessagePayload, - bp_polkadot::Balance, -> for ToKusamaMessageVerifier { +impl + LaneMessageVerifier< + Origin, + bp_polkadot::AccountId, + ToKusamaMessagePayload, + bp_polkadot::Balance, + > for ToKusamaMessageVerifier +{ type Error = &'static str; fn verify_message( @@ -128,7 +128,9 @@ impl LaneMessageVerifier< #[cfg(not(feature = "runtime-benchmarks"))] { match allowed_sender { - Some(ref allowed_sender) if submitter.linked_account().as_ref() == Some(allowed_sender) => (), + Some(ref allowed_sender) + if submitter.linked_account().as_ref() == Some(allowed_sender) => + (), _ => return Err(NOT_ALLOWED_MESSAGE_SENDER), } } @@ -152,7 +154,8 @@ impl MessageBridge for WithKusamaMessageBridge { const RELAYER_FEE_PERCENT: u32 = 10; const THIS_CHAIN_ID: ChainId = POLKADOT_CHAIN_ID; const BRIDGED_CHAIN_ID: ChainId = KUSAMA_CHAIN_ID; - const BRIDGED_MESSAGES_PALLET_NAME: &'static str = bp_polkadot::WITH_POLKADOT_MESSAGES_PALLET_NAME; + const BRIDGED_MESSAGES_PALLET_NAME: &'static str = + bp_polkadot::WITH_POLKADOT_MESSAGES_PALLET_NAME; type ThisChain = Polkadot; type BridgedChain = Kusama; @@ -297,7 +300,8 @@ impl BridgedChainWithMessages for Kusama { impl TargetHeaderChain for Kusama { type Error = &'static str; - type MessagesDeliveryProof = messages_source::FromBridgedChainMessagesDeliveryProof; + type MessagesDeliveryProof = + messages_source::FromBridgedChainMessagesDeliveryProof; fn verify_message(payload: &ToKusamaMessagePayload) -> Result<(), Self::Error> { messages_source::verify_chain_message::(payload) @@ -326,7 +330,8 @@ impl SourceHeaderChain for Kusama { WithKusamaMessageBridge, Runtime, crate::KusamaGrandpaInstance, - >(proof, messages_count).and_then(verify_inbound_messages_lane) + >(proof, messages_count) + .and_then(verify_inbound_messages_lane) } } @@ -336,7 +341,7 @@ fn verify_inbound_messages_lane( ) -> Result>, &'static str> { let allowed_incoming_lanes = [[0, 0, 0, 0]]; if messages.keys().any(|lane_id| !allowed_incoming_lanes.contains(lane_id)) { - return Err(INBOUND_LANE_DISABLED); + return Err(INBOUND_LANE_DISABLED) } Ok(messages) } @@ -350,7 +355,7 @@ impl SenderOrigin for Origin { Some(submitter.clone()), OriginCaller::Council(_) => AllowedMessageSender::get(), - _ => None, + _ => None, } } } @@ -369,7 +374,9 @@ pub enum WithKusamaMessageBridgeParameter { impl MessagesParameter for WithKusamaMessageBridgeParameter { fn save(&self) { match *self { - WithKusamaMessageBridgeParameter::KusamaToPolkadotConversionRate(ref conversion_rate) => { + WithKusamaMessageBridgeParameter::KusamaToPolkadotConversionRate( + ref conversion_rate, + ) => { KusamaToPolkadotConversionRate::set(conversion_rate); }, WithKusamaMessageBridgeParameter::KusamaFeeMultiplier(ref fee_multiplier) => { @@ -377,7 +384,7 @@ impl MessagesParameter for WithKusamaMessageBridgeParameter { }, WithKusamaMessageBridgeParameter::AllowedMessageSender(ref message_sender) => { AllowedMessageSender::set(message_sender); - } + }, } } } @@ -455,21 +462,23 @@ impl MessagesConfig for Runtime { frame_system::Pallet::::events() .into_iter() .map(|event_record| event_record.event) - .any(|event| matches!( - event, - Event::BridgeKusamaMessagesDispatch(pallet_bridge_dispatch::Event::::MessageDispatched( - _, ([0, 0, 0, 0], nonce_from_event), _, - )) if nonce_from_event == nonce - )) + .any(|event| { + matches!( + event, + Event::BridgeKusamaMessagesDispatch(pallet_bridge_dispatch::Event::::MessageDispatched( + _, ([0, 0, 0, 0], nonce_from_event), _, + )) if nonce_from_event == nonce + ) + }) } } #[cfg(test)] mod tests { + use super::*; + use crate::*; use bp_messages::{target_chain::ProvedLaneMessages, MessageData, MessageKey}; use frame_support::weights::GetDispatchInfo; - use crate::*; - use super::*; fn message_payload(sender: bp_polkadot::AccountId) -> ToKusamaMessagePayload { let call = Call::Balances(pallet_balances::Call::::transfer { @@ -499,21 +508,26 @@ mod tests { ); let max_incoming_message_proof_size = bp_kusama::EXTRA_STORAGE_PROOF_SIZE.saturating_add( - messages_target::maximal_incoming_message_size(bp_polkadot::Polkadot::max_extrinsic_size()), + messages_target::maximal_incoming_message_size( + bp_polkadot::Polkadot::max_extrinsic_size(), + ), ); pallet_bridge_messages::ensure_able_to_receive_message::( bp_polkadot::Polkadot::max_extrinsic_size(), bp_polkadot::Polkadot::max_extrinsic_weight(), max_incoming_message_proof_size, - messages_target::maximal_incoming_message_dispatch_weight(bp_polkadot::Polkadot::max_extrinsic_weight()), + messages_target::maximal_incoming_message_dispatch_weight( + bp_polkadot::Polkadot::max_extrinsic_weight(), + ), ); - let max_incoming_inbound_lane_data_proof_size = bp_messages::InboundLaneData::<()>::encoded_size_hint( - bp_polkadot::MAXIMAL_ENCODED_ACCOUNT_ID_SIZE, - bp_polkadot::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX as _, - bp_polkadot::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX as _, - ) - .unwrap_or(u32::MAX); + let max_incoming_inbound_lane_data_proof_size = + bp_messages::InboundLaneData::<()>::encoded_size_hint( + bp_polkadot::MAXIMAL_ENCODED_ACCOUNT_ID_SIZE, + bp_polkadot::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX as _, + bp_polkadot::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX as _, + ) + .unwrap_or(u32::MAX); pallet_bridge_messages::ensure_able_to_receive_confirmation::( bp_polkadot::Polkadot::max_extrinsic_size(), bp_polkadot::Polkadot::max_extrinsic_weight(), @@ -564,7 +578,10 @@ mod tests { ); assert_eq!( ToKusamaMessageVerifier::verify_message( - &OriginCaller::Council(pallet_collective::RawOrigin::Member(council_member.clone())).into(), + &OriginCaller::Council(pallet_collective::RawOrigin::Member( + council_member.clone() + )) + .into(), &bp_polkadot::Balance::MAX, &Default::default(), &Default::default(), @@ -576,18 +593,18 @@ mod tests { } fn proved_messages(lane_id: LaneId) -> ProvedMessages> { - vec![ - ( - lane_id, - ProvedLaneMessages { - lane_state: None, - messages: vec![Message { - key: MessageKey { lane_id, nonce: 0 }, - data: MessageData { payload: vec![], fee: 0 }, - }], - }, - ) - ].into_iter().collect() + vec![( + lane_id, + ProvedLaneMessages { + lane_state: None, + messages: vec![Message { + key: MessageKey { lane_id, nonce: 0 }, + data: MessageData { payload: vec![], fee: 0 }, + }], + }, + )] + .into_iter() + .collect() } #[test] @@ -609,9 +626,6 @@ mod tests { .into_iter() .chain(proved_messages([0, 0, 0, 1])) .collect(); - assert_eq!( - verify_inbound_messages_lane(proved_messages), - Err(INBOUND_LANE_DISABLED), - ); + assert_eq!(verify_inbound_messages_lane(proved_messages), Err(INBOUND_LANE_DISABLED),); } } diff --git a/runtime/polkadot/src/lib.rs b/runtime/polkadot/src/lib.rs index 96bee429597a..f66c4c046c25 100644 --- a/runtime/polkadot/src/lib.rs +++ b/runtime/polkadot/src/lib.rs @@ -37,7 +37,9 @@ use runtime_parachains::{ use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId; use beefy_primitives::crypto::AuthorityId as BeefyId; -use bridge_runtime_common::messages::{source::estimate_message_dispatch_and_delivery_fee, MessageBridge}; +use bridge_runtime_common::messages::{ + source::estimate_message_dispatch_and_delivery_fee, MessageBridge, +}; use frame_support::{ construct_runtime, parameter_types, traits::{ @@ -1405,12 +1407,13 @@ impl pallet_bridge_messages::Config for Runtime { type TargetHeaderChain = kusama_messages::Kusama; type LaneMessageVerifier = kusama_messages::ToKusamaMessageVerifier; - type MessageDeliveryAndDispatchPayment = pallet_bridge_messages::instant_payments::InstantCurrencyPayments< - Runtime, - WithKusamaMessagesInstance, - pallet_balances::Pallet, - kusama_messages::GetDeliveryConfirmationTransactionFee, - >; + type MessageDeliveryAndDispatchPayment = + pallet_bridge_messages::instant_payments::InstantCurrencyPayments< + Runtime, + WithKusamaMessagesInstance, + pallet_balances::Pallet, + kusama_messages::GetDeliveryConfirmationTransactionFee, + >; type OnMessageAccepted = (); type OnDeliveryConfirmed = (); @@ -1788,16 +1791,18 @@ impl OnRuntimeUpgrade for InitializeKusamaBridge { fn on_runtime_upgrade() -> frame_support::weights::Weight { // 12pPqadtXfkC4Jz16Lhyx33KZabx1N3ioUNkrwUQUwvvRRvT let with_kusama_grandpa_pallet_owner_id = AccountId::from([ - 0x50, 0x61, 0xa5, 0x47, 0x7e, 0x45, 0xdc, 0x62, 0xda, 0x52, 0xc9, 0x79, 0x86, 0x64, 0xc4, 0xdf, - 0xc8, 0xaa, 0x15, 0x27, 0x96, 0x77, 0xc6, 0xa2, 0x7a, 0xd2, 0xd5, 0x07, 0x8b, 0xa7, 0x7f, 0x03, + 0x50, 0x61, 0xa5, 0x47, 0x7e, 0x45, 0xdc, 0x62, 0xda, 0x52, 0xc9, 0x79, 0x86, 0x64, + 0xc4, 0xdf, 0xc8, 0xaa, 0x15, 0x27, 0x96, 0x77, 0xc6, 0xa2, 0x7a, 0xd2, 0xd5, 0x07, + 0x8b, 0xa7, 0x7f, 0x03, ]); pallet_bridge_grandpa::PalletOwner::::put( with_kusama_grandpa_pallet_owner_id, ); // 1jhfovJDjGJz8vR75QqwgBsXn62USqW8xpY6KZus3mmACJA let with_kusama_messages_pallet_owner_id = AccountId::from([ - 0x20, 0x91, 0x36, 0x21, 0x33, 0xf8, 0xaf, 0x3a, 0x2d, 0xf4, 0x71, 0x34, 0xe0, 0xd2, 0xf0, 0x62, - 0x58, 0xc0, 0x68, 0x38, 0x13, 0xf4, 0x5d, 0xb8, 0xa6, 0x02, 0x87, 0xd2, 0xcd, 0xce, 0x98, 0x7e, + 0x20, 0x91, 0x36, 0x21, 0x33, 0xf8, 0xaf, 0x3a, 0x2d, 0xf4, 0x71, 0x34, 0xe0, 0xd2, + 0xf0, 0x62, 0x58, 0xc0, 0x68, 0x38, 0x13, 0xf4, 0x5d, 0xb8, 0xa6, 0x02, 0x87, 0xd2, + 0xcd, 0xce, 0x98, 0x7e, ]); pallet_bridge_messages::PalletOwner::::put( with_kusama_messages_pallet_owner_id, @@ -1808,15 +1813,21 @@ impl OnRuntimeUpgrade for InitializeKusamaBridge { #[cfg(feature = "try-runtime")] fn pre_upgrade() -> Result<(), &'static str> { - ensure!(pallet_bridge_grandpa::PalletOwner::::get().is_none()); - ensure!(pallet_bridge_messages::PalletOwner::::get().is_none()); + ensure!( + pallet_bridge_grandpa::PalletOwner::::get().is_none() + ); + ensure!(pallet_bridge_messages::PalletOwner::::get() + .is_none()); Ok(()) } #[cfg(feature = "try-runtime")] fn post_upgrade() -> Result<(), &'static str> { - ensure!(pallet_bridge_grandpa::PalletOwner::::get().is_some()); - ensure!(pallet_bridge_messages::PalletOwner::::get().is_some()); + ensure!( + pallet_bridge_grandpa::PalletOwner::::get().is_some() + ); + ensure!(pallet_bridge_messages::PalletOwner::::get() + .is_some()); Ok(()) } } From d0bc34ec001160ce677ca980e4bbcf2e8530041a Mon Sep 17 00:00:00 2001 From: Svyatoslav Nikolsky Date: Tue, 22 Mar 2022 09:52:09 +0300 Subject: [PATCH 23/31] fix tests vs benchmarks --- runtime/kusama/src/polkadot_messages.rs | 2 +- runtime/polkadot/src/kusama_messages.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/runtime/kusama/src/polkadot_messages.rs b/runtime/kusama/src/polkadot_messages.rs index b4f0f858de92..4405927b1bba 100644 --- a/runtime/kusama/src/polkadot_messages.rs +++ b/runtime/kusama/src/polkadot_messages.rs @@ -92,7 +92,7 @@ pub type FromPolkadotMessageDispatch = messages_target::FromBridgedChainMessageD >; /// Error that happens when message is sent by anyone but `AllowedMessageSender`. -#[cfg(not(feature = "runtime-benchmarks"))] +#[cfg(any(not(feature = "runtime-benchmarks"), test))] const NOT_ALLOWED_MESSAGE_SENDER: &str = "Cannot accept message from this account"; /// Error that happens when we are receiving incoming message via unexpected lane. const INBOUND_LANE_DISABLED: &str = "The inbound message lane is disaled."; diff --git a/runtime/polkadot/src/kusama_messages.rs b/runtime/polkadot/src/kusama_messages.rs index 09430f066285..114f1c66dbde 100644 --- a/runtime/polkadot/src/kusama_messages.rs +++ b/runtime/polkadot/src/kusama_messages.rs @@ -92,7 +92,7 @@ pub type FromKusamaMessageDispatch = messages_target::FromBridgedChainMessageDis >; /// Error that happens when message is sent by anyone but `AllowedMessageSender`. -#[cfg(not(feature = "runtime-benchmarks"))] +#[cfg(any(not(feature = "runtime-benchmarks"), test))] const NOT_ALLOWED_MESSAGE_SENDER: &str = "Cannot accept message from this account"; /// Error that happens when we are receiving incoming message via unexpected lane. const INBOUND_LANE_DISABLED: &str = "The inbound message lane is disaled."; From 4850b2250a0fcb57592d2c83874d39b8646b2d36 Mon Sep 17 00:00:00 2001 From: Svyatoslav Nikolsky Date: Tue, 22 Mar 2022 11:35:25 +0300 Subject: [PATCH 24/31] tests vs benchmarks again --- runtime/kusama/src/polkadot_messages.rs | 37 +++++++++++++------------ runtime/polkadot/src/kusama_messages.rs | 37 +++++++++++++------------ 2 files changed, 38 insertions(+), 36 deletions(-) diff --git a/runtime/kusama/src/polkadot_messages.rs b/runtime/kusama/src/polkadot_messages.rs index 4405927b1bba..1222382157f5 100644 --- a/runtime/kusama/src/polkadot_messages.rs +++ b/runtime/kusama/src/polkadot_messages.rs @@ -92,7 +92,7 @@ pub type FromPolkadotMessageDispatch = messages_target::FromBridgedChainMessageD >; /// Error that happens when message is sent by anyone but `AllowedMessageSender`. -#[cfg(any(not(feature = "runtime-benchmarks"), test))] +#[cfg(not(feature = "runtime-benchmarks"))] const NOT_ALLOWED_MESSAGE_SENDER: &str = "Cannot accept message from this account"; /// Error that happens when we are receiving incoming message via unexpected lane. const INBOUND_LANE_DISABLED: &str = "The inbound message lane is disaled."; @@ -347,12 +347,18 @@ impl SenderOrigin for Origin { crate::OriginCaller::system(frame_system::RawOrigin::Signed(ref submitter)) => Some(submitter.clone()), - OriginCaller::Council(_) => AllowedMessageSender::get(), - _ => None, + _ => map_council_origin(&self.caller), } } } +fn map_council_origin(origin: &OriginCaller) -> Option { + match *origin { + OriginCaller::Council(_) => AllowedMessageSender::get(), + _ => None, + } +} + /// Kusama <> Polkadot messages pallet parameters. #[derive(RuntimeDebug, Clone, Encode, Decode, PartialEq, Eq, TypeInfo)] pub enum WithPolkadotMessageBridgeParameter { @@ -536,25 +542,20 @@ mod tests { AllowedMessageSender::set(&Some(allowed_sender.clone())); assert_eq!( - ToPolkadotMessageVerifier::verify_message( - &frame_system::RawOrigin::Signed(invalid_sender.clone()).into(), - &bp_kusama::Balance::MAX, - &Default::default(), - &Default::default(), - &message_payload(invalid_sender), - ), - Err(NOT_ALLOWED_MESSAGE_SENDER), + map_council_origin(&frame_system::RawOrigin::Signed(invalid_sender.clone()).into()), + None, ); assert_eq!( - ToPolkadotMessageVerifier::verify_message( - &frame_system::RawOrigin::Signed(allowed_sender.clone()).into(), - &bp_kusama::Balance::MAX, - &Default::default(), - &Default::default(), - &message_payload(allowed_sender), + map_council_origin(&frame_system::RawOrigin::Signed(allowed_sender.clone()).into()), + None, + ); + assert_eq!( + map_council_origin( + &OriginCaller::Council(pallet_collective::RawOrigin::Members(1, 1)).into() ), - Err(NOT_ALLOWED_MESSAGE_SENDER), + Some(allowed_sender.clone()), ); + assert_eq!( ToPolkadotMessageVerifier::verify_message( &OriginCaller::Council(pallet_collective::RawOrigin::Members(1, 1)).into(), diff --git a/runtime/polkadot/src/kusama_messages.rs b/runtime/polkadot/src/kusama_messages.rs index 114f1c66dbde..4adf174d3405 100644 --- a/runtime/polkadot/src/kusama_messages.rs +++ b/runtime/polkadot/src/kusama_messages.rs @@ -92,7 +92,7 @@ pub type FromKusamaMessageDispatch = messages_target::FromBridgedChainMessageDis >; /// Error that happens when message is sent by anyone but `AllowedMessageSender`. -#[cfg(any(not(feature = "runtime-benchmarks"), test))] +#[cfg(not(feature = "runtime-benchmarks"))] const NOT_ALLOWED_MESSAGE_SENDER: &str = "Cannot accept message from this account"; /// Error that happens when we are receiving incoming message via unexpected lane. const INBOUND_LANE_DISABLED: &str = "The inbound message lane is disaled."; @@ -354,12 +354,18 @@ impl SenderOrigin for Origin { crate::OriginCaller::system(frame_system::RawOrigin::Signed(ref submitter)) => Some(submitter.clone()), - OriginCaller::Council(_) => AllowedMessageSender::get(), - _ => None, + _ => map_council_origin(&self.caller), } } } +fn map_council_origin(origin: &OriginCaller) -> Option { + match *origin { + OriginCaller::Council(_) => AllowedMessageSender::get(), + _ => None, + } +} + /// Polkadot <> Kusama messages pallet parameters. #[derive(RuntimeDebug, Clone, Encode, Decode, PartialEq, Eq, TypeInfo)] pub enum WithKusamaMessageBridgeParameter { @@ -547,25 +553,20 @@ mod tests { AllowedMessageSender::set(&Some(allowed_sender.clone())); assert_eq!( - ToKusamaMessageVerifier::verify_message( - &frame_system::RawOrigin::Signed(invalid_sender.clone()).into(), - &bp_polkadot::Balance::MAX, - &Default::default(), - &Default::default(), - &message_payload(invalid_sender), - ), - Err(NOT_ALLOWED_MESSAGE_SENDER), + map_council_origin(&frame_system::RawOrigin::Signed(invalid_sender.clone()).into()), + None, ); assert_eq!( - ToKusamaMessageVerifier::verify_message( - &frame_system::RawOrigin::Signed(allowed_sender.clone()).into(), - &bp_polkadot::Balance::MAX, - &Default::default(), - &Default::default(), - &message_payload(allowed_sender), + map_council_origin(&frame_system::RawOrigin::Signed(allowed_sender.clone()).into()), + None, + ); + assert_eq!( + map_council_origin( + &OriginCaller::Council(pallet_collective::RawOrigin::Members(1, 1)).into() ), - Err(NOT_ALLOWED_MESSAGE_SENDER), + Some(allowed_sender.clone()), ); + assert_eq!( ToKusamaMessageVerifier::verify_message( &OriginCaller::Council(pallet_collective::RawOrigin::Members(1, 1)).into(), From 5b99e16082eabdf898ccd0a76176e694c5db436e Mon Sep 17 00:00:00 2001 From: Svyatoslav Nikolsky Date: Tue, 22 Mar 2022 12:03:35 +0300 Subject: [PATCH 25/31] fix try-runtime --- runtime/kusama/src/lib.rs | 26 ++++++++++++++++---------- runtime/polkadot/src/lib.rs | 24 ++++++++++++++++-------- 2 files changed, 32 insertions(+), 18 deletions(-) diff --git a/runtime/kusama/src/lib.rs b/runtime/kusama/src/lib.rs index eeebbf343a4a..343a4f50274a 100644 --- a/runtime/kusama/src/lib.rs +++ b/runtime/kusama/src/lib.rs @@ -1666,23 +1666,29 @@ impl OnRuntimeUpgrade for InitializePolkadotBridge { #[cfg(feature = "try-runtime")] fn pre_upgrade() -> Result<(), &'static str> { - ensure!( - pallet_bridge_grandpa::PalletOwner::::get().is_none() + frame_support::ensure!( + pallet_bridge_grandpa::PalletOwner::::get().is_none(), + "Bridge grandpa pallet owner is already set", + ); + frame_support::ensure!( + pallet_bridge_messages::PalletOwner::::get() + .is_none(), + "Bridge messages pallet owner is already set", ); - ensure!(pallet_bridge_messages::PalletOwner::::get( - ) - .is_none()); Ok(()) } #[cfg(feature = "try-runtime")] fn post_upgrade() -> Result<(), &'static str> { - ensure!( - pallet_bridge_grandpa::PalletOwner::::get().is_some() + frame_support::ensure!( + pallet_bridge_grandpa::PalletOwner::::get().is_some(), + "Bridge grandpa pallet owner is not initialized during upgrade", + ); + frame_support::ensure!( + pallet_bridge_messages::PalletOwner::::get() + .is_some(), + "Bridge messages pallet owner is not initialized during upgrade", ); - ensure!(pallet_bridge_messages::PalletOwner::::get( - ) - .is_some()); Ok(()) } } diff --git a/runtime/polkadot/src/lib.rs b/runtime/polkadot/src/lib.rs index f66c4c046c25..360816b4176e 100644 --- a/runtime/polkadot/src/lib.rs +++ b/runtime/polkadot/src/lib.rs @@ -1813,21 +1813,29 @@ impl OnRuntimeUpgrade for InitializeKusamaBridge { #[cfg(feature = "try-runtime")] fn pre_upgrade() -> Result<(), &'static str> { - ensure!( - pallet_bridge_grandpa::PalletOwner::::get().is_none() + frame_support::ensure!( + pallet_bridge_grandpa::PalletOwner::::get().is_none(), + "Bridge grandpa pallet owner is already set", + ); + frame_support::ensure!( + pallet_bridge_messages::PalletOwner::::get() + .is_none(), + "Bridge messages pallet owner is already set", ); - ensure!(pallet_bridge_messages::PalletOwner::::get() - .is_none()); Ok(()) } #[cfg(feature = "try-runtime")] fn post_upgrade() -> Result<(), &'static str> { - ensure!( - pallet_bridge_grandpa::PalletOwner::::get().is_some() + frame_support::ensure!( + pallet_bridge_grandpa::PalletOwner::::get().is_some(), + "Bridge grandpa pallet owner is not initialized during upgrade", + ); + frame_support::ensure!( + pallet_bridge_messages::PalletOwner::::get() + .is_some(), + "Bridge messages pallet owner is not initialized during upgrade", ); - ensure!(pallet_bridge_messages::PalletOwner::::get() - .is_some()); Ok(()) } } From 54e94646ec641ad7df33f2e23d705f1cb74fb4db Mon Sep 17 00:00:00 2001 From: Parity Bot Date: Tue, 22 Mar 2022 10:54:09 +0000 Subject: [PATCH 26/31] cargo run --quiet --profile=production --features=runtime-benchmarks -- benchmark --chain=polkadot-dev --steps=50 --repeat=20 --pallet=pallet_bridge_messages --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --header=./file_header.txt --output=./runtime/polkadot/src/weights/ --- .../src/weights/pallet_bridge_messages.rs | 191 ++++++++++++++++++ 1 file changed, 191 insertions(+) create mode 100644 runtime/polkadot/src/weights/pallet_bridge_messages.rs diff --git a/runtime/polkadot/src/weights/pallet_bridge_messages.rs b/runtime/polkadot/src/weights/pallet_bridge_messages.rs new file mode 100644 index 000000000000..91d474aa47cd --- /dev/null +++ b/runtime/polkadot/src/weights/pallet_bridge_messages.rs @@ -0,0 +1,191 @@ +// Copyright 2017-2022 Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot 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. + +// Polkadot 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 Polkadot. If not, see . +//! Autogenerated weights for `pallet_bridge_messages` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2022-03-22, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("polkadot-dev"), DB CACHE: 1024 + +// Executed Command: +// target/production/polkadot +// benchmark +// --chain=polkadot-dev +// --steps=50 +// --repeat=20 +// --pallet=pallet_bridge_messages +// --extrinsic=* +// --execution=wasm +// --wasm-execution=compiled +// --heap-pages=4096 +// --header=./file_header.txt +// --output=./runtime/polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weight functions for `pallet_bridge_messages`. +pub struct WeightInfo(PhantomData); +impl pallet_bridge_messages::WeightInfo for WeightInfo { + // Storage: BridgeKusamaMessages PalletOperatingMode (r:1 w:0) + // Storage: BridgeKusamaMessages OutboundLanes (r:1 w:1) + // Storage: unknown [0x3a143f4abdba538105373c7cdb014a50] (r:1 w:0) + // Storage: unknown [0x90ae353245e43eb2b7d8771456afb898] (r:1 w:0) + // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0) + // Storage: unknown [0x18014d0485d5a02787c9a59d88a35a43] (r:1 w:0) + // Storage: System Account (r:2 w:2) + // Storage: BridgeKusamaMessages OutboundMessages (r:0 w:9) + fn send_minimal_message_worst_case() -> Weight { + (46_497_000 as Weight) + .saturating_add(T::DbWeight::get().reads(8 as Weight)) + .saturating_add(T::DbWeight::get().writes(12 as Weight)) + } + // Storage: BridgeKusamaMessages PalletOperatingMode (r:1 w:0) + // Storage: BridgeKusamaMessages OutboundLanes (r:1 w:1) + // Storage: unknown [0x3a143f4abdba538105373c7cdb014a50] (r:1 w:0) + // Storage: unknown [0x90ae353245e43eb2b7d8771456afb898] (r:1 w:0) + // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0) + // Storage: unknown [0x18014d0485d5a02787c9a59d88a35a43] (r:1 w:0) + // Storage: System Account (r:2 w:2) + // Storage: BridgeKusamaMessages OutboundMessages (r:0 w:9) + fn send_1_kb_message_worst_case() -> Weight { + (48_876_000 as Weight) + .saturating_add(T::DbWeight::get().reads(8 as Weight)) + .saturating_add(T::DbWeight::get().writes(12 as Weight)) + } + // Storage: BridgeKusamaMessages PalletOperatingMode (r:1 w:0) + // Storage: BridgeKusamaMessages OutboundLanes (r:1 w:1) + // Storage: unknown [0x3a143f4abdba538105373c7cdb014a50] (r:1 w:0) + // Storage: unknown [0x90ae353245e43eb2b7d8771456afb898] (r:1 w:0) + // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0) + // Storage: unknown [0x18014d0485d5a02787c9a59d88a35a43] (r:1 w:0) + // Storage: System Account (r:2 w:2) + // Storage: BridgeKusamaMessages OutboundMessages (r:0 w:9) + fn send_16_kb_message_worst_case() -> Weight { + (68_302_000 as Weight) + .saturating_add(T::DbWeight::get().reads(8 as Weight)) + .saturating_add(T::DbWeight::get().writes(12 as Weight)) + } + // Storage: BridgeKusamaMessages PalletOperatingMode (r:1 w:0) + // Storage: BridgeKusamaMessages OutboundLanes (r:1 w:0) + // Storage: System Account (r:2 w:2) + // Storage: BridgeKusamaMessages OutboundMessages (r:1 w:1) + fn maximal_increase_message_fee() -> Weight { + (3_823_025_000 as Weight) + .saturating_add(T::DbWeight::get().reads(5 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: BridgeKusamaMessages PalletOperatingMode (r:1 w:0) + // Storage: BridgeKusamaMessages OutboundLanes (r:1 w:0) + // Storage: System Account (r:2 w:2) + // Storage: BridgeKusamaMessages OutboundMessages (r:1 w:1) + fn increase_message_fee(i: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(i as Weight)) + .saturating_add(T::DbWeight::get().reads(5 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: BridgeKusamaMessages PalletOperatingMode (r:1 w:0) + // Storage: BridgeKusamaGrandpa ImportedHeaders (r:1 w:0) + // Storage: BridgeKusamaMessages InboundLanes (r:1 w:1) + // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0) + fn receive_single_message_proof() -> Weight { + (77_277_000 as Weight) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: BridgeKusamaMessages PalletOperatingMode (r:1 w:0) + // Storage: BridgeKusamaGrandpa ImportedHeaders (r:1 w:0) + // Storage: BridgeKusamaMessages InboundLanes (r:1 w:1) + // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0) + fn receive_two_messages_proof() -> Weight { + (135_427_000 as Weight) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: BridgeKusamaMessages PalletOperatingMode (r:1 w:0) + // Storage: BridgeKusamaGrandpa ImportedHeaders (r:1 w:0) + // Storage: BridgeKusamaMessages InboundLanes (r:1 w:1) + // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0) + fn receive_single_message_proof_with_outbound_lane_state() -> Weight { + (82_053_000 as Weight) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: BridgeKusamaMessages PalletOperatingMode (r:1 w:0) + // Storage: BridgeKusamaGrandpa ImportedHeaders (r:1 w:0) + // Storage: BridgeKusamaMessages InboundLanes (r:1 w:1) + // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0) + fn receive_single_message_proof_1_kb() -> Weight { + (85_125_000 as Weight) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: BridgeKusamaMessages PalletOperatingMode (r:1 w:0) + // Storage: BridgeKusamaGrandpa ImportedHeaders (r:1 w:0) + // Storage: BridgeKusamaMessages InboundLanes (r:1 w:1) + // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0) + fn receive_single_message_proof_16_kb() -> Weight { + (158_078_000 as Weight) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: BridgeKusamaMessages PalletOperatingMode (r:1 w:0) + // Storage: BridgeKusamaGrandpa ImportedHeaders (r:1 w:0) + // Storage: BridgeKusamaMessages InboundLanes (r:1 w:1) + fn receive_single_prepaid_message_proof() -> Weight { + (74_665_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: BridgeKusamaMessages PalletOperatingMode (r:1 w:0) + // Storage: BridgeKusamaGrandpa ImportedHeaders (r:1 w:0) + // Storage: BridgeKusamaMessages OutboundLanes (r:1 w:1) + // Storage: BridgeKusamaMessages OutboundMessages (r:1 w:0) + // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0) + // Storage: System Account (r:2 w:2) + fn receive_delivery_proof_for_single_message() -> Weight { + (45_864_000 as Weight) + .saturating_add(T::DbWeight::get().reads(7 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: BridgeKusamaMessages PalletOperatingMode (r:1 w:0) + // Storage: BridgeKusamaGrandpa ImportedHeaders (r:1 w:0) + // Storage: BridgeKusamaMessages OutboundLanes (r:1 w:1) + // Storage: BridgeKusamaMessages OutboundMessages (r:2 w:0) + // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0) + // Storage: System Account (r:2 w:2) + fn receive_delivery_proof_for_two_messages_by_single_relayer() -> Weight { + (49_720_000 as Weight) + .saturating_add(T::DbWeight::get().reads(8 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: BridgeKusamaMessages PalletOperatingMode (r:1 w:0) + // Storage: BridgeKusamaGrandpa ImportedHeaders (r:1 w:0) + // Storage: BridgeKusamaMessages OutboundLanes (r:1 w:1) + // Storage: BridgeKusamaMessages OutboundMessages (r:2 w:0) + // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0) + // Storage: System Account (r:3 w:3) + fn receive_delivery_proof_for_two_messages_by_two_relayers() -> Weight { + (63_160_000 as Weight) + .saturating_add(T::DbWeight::get().reads(9 as Weight)) + .saturating_add(T::DbWeight::get().writes(4 as Weight)) + } +} From 420cbf86206041d5b116ff727b275035ee1c9b94 Mon Sep 17 00:00:00 2001 From: Parity Bot Date: Tue, 22 Mar 2022 15:35:03 +0000 Subject: [PATCH 27/31] cargo run --quiet --profile=production --features=runtime-benchmarks -- benchmark --chain=polkadot-dev --steps=50 --repeat=20 --pallet=pallet_bridge_grandpa --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --header=./file_header.txt --output=./runtime/polkadot/src/weights/ --- .../src/weights/pallet_bridge_grandpa.rs | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 runtime/polkadot/src/weights/pallet_bridge_grandpa.rs diff --git a/runtime/polkadot/src/weights/pallet_bridge_grandpa.rs b/runtime/polkadot/src/weights/pallet_bridge_grandpa.rs new file mode 100644 index 000000000000..9bbaed44277f --- /dev/null +++ b/runtime/polkadot/src/weights/pallet_bridge_grandpa.rs @@ -0,0 +1,62 @@ +// Copyright 2017-2022 Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot 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. + +// Polkadot 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 Polkadot. If not, see . +//! Autogenerated weights for `pallet_bridge_grandpa` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2022-03-22, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("polkadot-dev"), DB CACHE: 1024 + +// Executed Command: +// target/production/polkadot +// benchmark +// --chain=polkadot-dev +// --steps=50 +// --repeat=20 +// --pallet=pallet_bridge_grandpa +// --extrinsic=* +// --execution=wasm +// --wasm-execution=compiled +// --heap-pages=4096 +// --header=./file_header.txt +// --output=./runtime/polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weight functions for `pallet_bridge_grandpa`. +pub struct WeightInfo(PhantomData); +impl pallet_bridge_grandpa::WeightInfo for WeightInfo { + // Storage: BridgeKusamaGrandpa IsHalted (r:1 w:0) + // Storage: BridgeKusamaGrandpa RequestCount (r:1 w:1) + // Storage: BridgeKusamaGrandpa BestFinalized (r:1 w:1) + // Storage: BridgeKusamaGrandpa ImportedHeaders (r:1 w:2) + // Storage: BridgeKusamaGrandpa CurrentAuthoritySet (r:1 w:0) + // Storage: BridgeKusamaGrandpa ImportedHashesPointer (r:1 w:1) + // Storage: BridgeKusamaGrandpa ImportedHashes (r:1 w:1) + fn submit_finality_proof(p: u32, v: u32, ) -> Weight { + (82_911_000 as Weight) + // Standard Error: 7_000 + .saturating_add((46_952_000 as Weight).saturating_mul(p as Weight)) + // Standard Error: 7_000 + .saturating_add((1_396_000 as Weight).saturating_mul(v as Weight)) + .saturating_add(T::DbWeight::get().reads(7 as Weight)) + .saturating_add(T::DbWeight::get().writes(6 as Weight)) + } +} From 012ea4111c3b46f7da26a9adaf06c3573ea9313e Mon Sep 17 00:00:00 2001 From: Parity Bot Date: Wed, 23 Mar 2022 08:56:22 +0000 Subject: [PATCH 28/31] cargo run --quiet --profile=production --features=runtime-benchmarks -- benchmark --chain=kusama-dev --steps=50 --repeat=20 --pallet=pallet_bridge_grandpa --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --header=./file_header.txt --output=./runtime/kusama/src/weights/ --- .../src/weights/pallet_bridge_grandpa.rs | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 runtime/kusama/src/weights/pallet_bridge_grandpa.rs diff --git a/runtime/kusama/src/weights/pallet_bridge_grandpa.rs b/runtime/kusama/src/weights/pallet_bridge_grandpa.rs new file mode 100644 index 000000000000..a543d6e976c8 --- /dev/null +++ b/runtime/kusama/src/weights/pallet_bridge_grandpa.rs @@ -0,0 +1,62 @@ +// Copyright 2017-2022 Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot 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. + +// Polkadot 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 Polkadot. If not, see . +//! Autogenerated weights for `pallet_bridge_grandpa` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2022-03-23, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("kusama-dev"), DB CACHE: 1024 + +// Executed Command: +// target/production/polkadot +// benchmark +// --chain=kusama-dev +// --steps=50 +// --repeat=20 +// --pallet=pallet_bridge_grandpa +// --extrinsic=* +// --execution=wasm +// --wasm-execution=compiled +// --heap-pages=4096 +// --header=./file_header.txt +// --output=./runtime/kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weight functions for `pallet_bridge_grandpa`. +pub struct WeightInfo(PhantomData); +impl pallet_bridge_grandpa::WeightInfo for WeightInfo { + // Storage: BridgePolkadotGrandpa IsHalted (r:1 w:0) + // Storage: BridgePolkadotGrandpa RequestCount (r:1 w:1) + // Storage: BridgePolkadotGrandpa BestFinalized (r:1 w:1) + // Storage: BridgePolkadotGrandpa ImportedHeaders (r:1 w:2) + // Storage: BridgePolkadotGrandpa CurrentAuthoritySet (r:1 w:0) + // Storage: BridgePolkadotGrandpa ImportedHashesPointer (r:1 w:1) + // Storage: BridgePolkadotGrandpa ImportedHashes (r:1 w:1) + fn submit_finality_proof(p: u32, v: u32, ) -> Weight { + (93_160_000 as Weight) + // Standard Error: 7_000 + .saturating_add((46_686_000 as Weight).saturating_mul(p as Weight)) + // Standard Error: 7_000 + .saturating_add((1_308_000 as Weight).saturating_mul(v as Weight)) + .saturating_add(T::DbWeight::get().reads(7 as Weight)) + .saturating_add(T::DbWeight::get().writes(6 as Weight)) + } +} From 3d5101164e1042d39ffd331da6e27065fa6041f0 Mon Sep 17 00:00:00 2001 From: Parity Bot Date: Wed, 23 Mar 2022 09:31:31 +0000 Subject: [PATCH 29/31] cargo run --quiet --profile=production --features=runtime-benchmarks -- benchmark --chain=kusama-dev --steps=50 --repeat=20 --pallet=pallet_bridge_messages --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --header=./file_header.txt --output=./runtime/kusama/src/weights/ --- .../src/weights/pallet_bridge_messages.rs | 191 ++++++++++++++++++ 1 file changed, 191 insertions(+) create mode 100644 runtime/kusama/src/weights/pallet_bridge_messages.rs diff --git a/runtime/kusama/src/weights/pallet_bridge_messages.rs b/runtime/kusama/src/weights/pallet_bridge_messages.rs new file mode 100644 index 000000000000..8d8e501eeeda --- /dev/null +++ b/runtime/kusama/src/weights/pallet_bridge_messages.rs @@ -0,0 +1,191 @@ +// Copyright 2017-2022 Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot 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. + +// Polkadot 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 Polkadot. If not, see . +//! Autogenerated weights for `pallet_bridge_messages` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2022-03-23, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("kusama-dev"), DB CACHE: 1024 + +// Executed Command: +// target/production/polkadot +// benchmark +// --chain=kusama-dev +// --steps=50 +// --repeat=20 +// --pallet=pallet_bridge_messages +// --extrinsic=* +// --execution=wasm +// --wasm-execution=compiled +// --heap-pages=4096 +// --header=./file_header.txt +// --output=./runtime/kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weight functions for `pallet_bridge_messages`. +pub struct WeightInfo(PhantomData); +impl pallet_bridge_messages::WeightInfo for WeightInfo { + // Storage: BridgePolkadotMessages PalletOperatingMode (r:1 w:0) + // Storage: BridgePolkadotMessages OutboundLanes (r:1 w:1) + // Storage: unknown [0x3a143f4abdba538105373c7cdb014a50] (r:1 w:0) + // Storage: unknown [0x8626edfd24ecc30ca2c42535541fa3a7] (r:1 w:0) + // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0) + // Storage: unknown [0x51f1dbb0462eff18ec87eafdf9569989] (r:1 w:0) + // Storage: System Account (r:2 w:2) + // Storage: BridgePolkadotMessages OutboundMessages (r:0 w:9) + fn send_minimal_message_worst_case() -> Weight { + (45_686_000 as Weight) + .saturating_add(T::DbWeight::get().reads(8 as Weight)) + .saturating_add(T::DbWeight::get().writes(12 as Weight)) + } + // Storage: BridgePolkadotMessages PalletOperatingMode (r:1 w:0) + // Storage: BridgePolkadotMessages OutboundLanes (r:1 w:1) + // Storage: unknown [0x3a143f4abdba538105373c7cdb014a50] (r:1 w:0) + // Storage: unknown [0x8626edfd24ecc30ca2c42535541fa3a7] (r:1 w:0) + // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0) + // Storage: unknown [0x51f1dbb0462eff18ec87eafdf9569989] (r:1 w:0) + // Storage: System Account (r:2 w:2) + // Storage: BridgePolkadotMessages OutboundMessages (r:0 w:9) + fn send_1_kb_message_worst_case() -> Weight { + (48_216_000 as Weight) + .saturating_add(T::DbWeight::get().reads(8 as Weight)) + .saturating_add(T::DbWeight::get().writes(12 as Weight)) + } + // Storage: BridgePolkadotMessages PalletOperatingMode (r:1 w:0) + // Storage: BridgePolkadotMessages OutboundLanes (r:1 w:1) + // Storage: unknown [0x3a143f4abdba538105373c7cdb014a50] (r:1 w:0) + // Storage: unknown [0x8626edfd24ecc30ca2c42535541fa3a7] (r:1 w:0) + // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0) + // Storage: unknown [0x51f1dbb0462eff18ec87eafdf9569989] (r:1 w:0) + // Storage: System Account (r:2 w:2) + // Storage: BridgePolkadotMessages OutboundMessages (r:0 w:9) + fn send_16_kb_message_worst_case() -> Weight { + (67_693_000 as Weight) + .saturating_add(T::DbWeight::get().reads(8 as Weight)) + .saturating_add(T::DbWeight::get().writes(12 as Weight)) + } + // Storage: BridgePolkadotMessages PalletOperatingMode (r:1 w:0) + // Storage: BridgePolkadotMessages OutboundLanes (r:1 w:0) + // Storage: System Account (r:2 w:2) + // Storage: BridgePolkadotMessages OutboundMessages (r:1 w:1) + fn maximal_increase_message_fee() -> Weight { + (3_777_465_000 as Weight) + .saturating_add(T::DbWeight::get().reads(5 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: BridgePolkadotMessages PalletOperatingMode (r:1 w:0) + // Storage: BridgePolkadotMessages OutboundLanes (r:1 w:0) + // Storage: System Account (r:2 w:2) + // Storage: BridgePolkadotMessages OutboundMessages (r:1 w:1) + fn increase_message_fee(i: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(i as Weight)) + .saturating_add(T::DbWeight::get().reads(5 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: BridgePolkadotMessages PalletOperatingMode (r:1 w:0) + // Storage: BridgePolkadotGrandpa ImportedHeaders (r:1 w:0) + // Storage: BridgePolkadotMessages InboundLanes (r:1 w:1) + // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0) + fn receive_single_message_proof() -> Weight { + (77_857_000 as Weight) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: BridgePolkadotMessages PalletOperatingMode (r:1 w:0) + // Storage: BridgePolkadotGrandpa ImportedHeaders (r:1 w:0) + // Storage: BridgePolkadotMessages InboundLanes (r:1 w:1) + // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0) + fn receive_two_messages_proof() -> Weight { + (136_688_000 as Weight) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: BridgePolkadotMessages PalletOperatingMode (r:1 w:0) + // Storage: BridgePolkadotGrandpa ImportedHeaders (r:1 w:0) + // Storage: BridgePolkadotMessages InboundLanes (r:1 w:1) + // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0) + fn receive_single_message_proof_with_outbound_lane_state() -> Weight { + (83_192_000 as Weight) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: BridgePolkadotMessages PalletOperatingMode (r:1 w:0) + // Storage: BridgePolkadotGrandpa ImportedHeaders (r:1 w:0) + // Storage: BridgePolkadotMessages InboundLanes (r:1 w:1) + // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0) + fn receive_single_message_proof_1_kb() -> Weight { + (83_735_000 as Weight) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: BridgePolkadotMessages PalletOperatingMode (r:1 w:0) + // Storage: BridgePolkadotGrandpa ImportedHeaders (r:1 w:0) + // Storage: BridgePolkadotMessages InboundLanes (r:1 w:1) + // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0) + fn receive_single_message_proof_16_kb() -> Weight { + (157_986_000 as Weight) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: BridgePolkadotMessages PalletOperatingMode (r:1 w:0) + // Storage: BridgePolkadotGrandpa ImportedHeaders (r:1 w:0) + // Storage: BridgePolkadotMessages InboundLanes (r:1 w:1) + fn receive_single_prepaid_message_proof() -> Weight { + (75_794_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: BridgePolkadotMessages PalletOperatingMode (r:1 w:0) + // Storage: BridgePolkadotGrandpa ImportedHeaders (r:1 w:0) + // Storage: BridgePolkadotMessages OutboundLanes (r:1 w:1) + // Storage: BridgePolkadotMessages OutboundMessages (r:1 w:0) + // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0) + // Storage: System Account (r:2 w:2) + fn receive_delivery_proof_for_single_message() -> Weight { + (47_675_000 as Weight) + .saturating_add(T::DbWeight::get().reads(7 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: BridgePolkadotMessages PalletOperatingMode (r:1 w:0) + // Storage: BridgePolkadotGrandpa ImportedHeaders (r:1 w:0) + // Storage: BridgePolkadotMessages OutboundLanes (r:1 w:1) + // Storage: BridgePolkadotMessages OutboundMessages (r:2 w:0) + // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0) + // Storage: System Account (r:2 w:2) + fn receive_delivery_proof_for_two_messages_by_single_relayer() -> Weight { + (50_397_000 as Weight) + .saturating_add(T::DbWeight::get().reads(8 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: BridgePolkadotMessages PalletOperatingMode (r:1 w:0) + // Storage: BridgePolkadotGrandpa ImportedHeaders (r:1 w:0) + // Storage: BridgePolkadotMessages OutboundLanes (r:1 w:1) + // Storage: BridgePolkadotMessages OutboundMessages (r:2 w:0) + // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0) + // Storage: System Account (r:3 w:3) + fn receive_delivery_proof_for_two_messages_by_two_relayers() -> Weight { + (64_457_000 as Weight) + .saturating_add(T::DbWeight::get().reads(9 as Weight)) + .saturating_add(T::DbWeight::get().writes(4 as Weight)) + } +} From 0a583df439c52e5a1db75812b52f7d4359e4f675 Mon Sep 17 00:00:00 2001 From: Svyatoslav Nikolsky Date: Thu, 7 Apr 2022 09:41:36 +0300 Subject: [PATCH 30/31] use Polkadot/Kusama weights --- runtime/kusama/src/lib.rs | 4 ++-- runtime/kusama/src/polkadot_messages.rs | 2 +- runtime/kusama/src/weights/mod.rs | 2 ++ runtime/polkadot/src/kusama_messages.rs | 2 +- runtime/polkadot/src/lib.rs | 4 ++-- runtime/polkadot/src/weights/mod.rs | 2 ++ 6 files changed, 10 insertions(+), 6 deletions(-) diff --git a/runtime/kusama/src/lib.rs b/runtime/kusama/src/lib.rs index 343a4f50274a..6e09ccc46fe6 100644 --- a/runtime/kusama/src/lib.rs +++ b/runtime/kusama/src/lib.rs @@ -1406,7 +1406,7 @@ impl pallet_bridge_grandpa::Config for Runtime { type MaxRequests = MaxBridgeGrandpaRequests; type HeadersToKeep = BridgeGrandpaHeadersToKeep; - type WeightInfo = pallet_bridge_grandpa::weights::MillauWeight; // TODO + type WeightInfo = weights::pallet_bridge_grandpa::WeightInfo; } parameter_types! { @@ -1423,7 +1423,7 @@ pub type WithPolkadotMessagesInstance = (); impl pallet_bridge_messages::Config for Runtime { type Event = Event; - type WeightInfo = pallet_bridge_messages::weights::MillauWeight; // TODO + type WeightInfo = weights::pallet_bridge_messages::MillauWeight; type Parameter = polkadot_messages::WithPolkadotMessageBridgeParameter; type MaxMessagesToPruneAtOnce = MaxMessagesToPruneAtOnce; type MaxUnrewardedRelayerEntriesAtInboundLane = MaxUnrewardedRelayerEntriesAtInboundLane; diff --git a/runtime/kusama/src/polkadot_messages.rs b/runtime/kusama/src/polkadot_messages.rs index 1222382157f5..88054c89e41a 100644 --- a/runtime/kusama/src/polkadot_messages.rs +++ b/runtime/kusama/src/polkadot_messages.rs @@ -494,7 +494,7 @@ mod tests { #[test] fn ensure_kusama_message_lane_weights_are_correct() { - type Weights = pallet_bridge_messages::weights::MillauWeight; // TODO: use Kusama weights + type Weights = crate::weights::pallet_bridge_messages::WeightInfo; pallet_bridge_messages::ensure_weights_are_correct::( bp_kusama::DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT, diff --git a/runtime/kusama/src/weights/mod.rs b/runtime/kusama/src/weights/mod.rs index 11418ee7c787..4ab258411103 100644 --- a/runtime/kusama/src/weights/mod.rs +++ b/runtime/kusama/src/weights/mod.rs @@ -19,6 +19,8 @@ pub mod frame_system; pub mod pallet_bags_list; pub mod pallet_balances; pub mod pallet_bounties; +pub mod pallet_bridge_grandpa; +pub mod pallet_bridge_messages; pub mod pallet_child_bounties; pub mod pallet_collective_council; pub mod pallet_collective_technical_committee; diff --git a/runtime/polkadot/src/kusama_messages.rs b/runtime/polkadot/src/kusama_messages.rs index 4adf174d3405..ad016e9e5401 100644 --- a/runtime/polkadot/src/kusama_messages.rs +++ b/runtime/polkadot/src/kusama_messages.rs @@ -503,7 +503,7 @@ mod tests { #[test] fn ensure_polkadot_message_lane_weights_are_correct() { - type Weights = pallet_bridge_messages::weights::MillauWeight; // TODO: use Polkadot weights + type Weights = crate::weights::pallet_bridge_messages::WeightInfo; pallet_bridge_messages::ensure_weights_are_correct::( bp_polkadot::DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT, diff --git a/runtime/polkadot/src/lib.rs b/runtime/polkadot/src/lib.rs index 360816b4176e..f3781f58bc2c 100644 --- a/runtime/polkadot/src/lib.rs +++ b/runtime/polkadot/src/lib.rs @@ -1373,7 +1373,7 @@ impl pallet_bridge_grandpa::Config for Runtime { type MaxRequests = MaxBridgeGrandpaRequests; type HeadersToKeep = BridgeGrandpaHeadersToKeep; - type WeightInfo = pallet_bridge_grandpa::weights::MillauWeight; // TODO + type WeightInfo = weights::pallet_bridge_grandpa::WeightInfo; } parameter_types! { @@ -1390,7 +1390,7 @@ pub type WithKusamaMessagesInstance = (); impl pallet_bridge_messages::Config for Runtime { type Event = Event; - type WeightInfo = pallet_bridge_messages::weights::MillauWeight; // TODO + type WeightInfo = weights::pallet_bridge_messages::WeightInfo; type Parameter = kusama_messages::WithKusamaMessageBridgeParameter; type MaxMessagesToPruneAtOnce = MaxMessagesToPruneAtOnce; type MaxUnrewardedRelayerEntriesAtInboundLane = MaxUnrewardedRelayerEntriesAtInboundLane; diff --git a/runtime/polkadot/src/weights/mod.rs b/runtime/polkadot/src/weights/mod.rs index 25b36085b736..a3b2af653333 100644 --- a/runtime/polkadot/src/weights/mod.rs +++ b/runtime/polkadot/src/weights/mod.rs @@ -19,6 +19,8 @@ pub mod frame_system; pub mod pallet_bags_list; pub mod pallet_balances; pub mod pallet_bounties; +pub mod pallet_bridge_grandpa; +pub mod pallet_bridge_messages; pub mod pallet_child_bounties; pub mod pallet_collective_council; pub mod pallet_collective_technical_committee; From 80650ff914abb70c5981536bd10064b67e04d8a3 Mon Sep 17 00:00:00 2001 From: Svyatoslav Nikolsky Date: Thu, 7 Apr 2022 09:50:29 +0300 Subject: [PATCH 31/31] some fixes for Polkadot/Kusama weights --- bridges/modules/grandpa/src/lib.rs | 3 +-- bridges/modules/messages/src/lib.rs | 4 ++-- runtime/kusama/src/lib.rs | 2 +- runtime/kusama/src/polkadot_messages.rs | 8 ++++++++ runtime/polkadot/src/kusama_messages.rs | 8 ++++++++ 5 files changed, 20 insertions(+), 5 deletions(-) diff --git a/bridges/modules/grandpa/src/lib.rs b/bridges/modules/grandpa/src/lib.rs index 947bfdc7f634..77b640fa1b38 100644 --- a/bridges/modules/grandpa/src/lib.rs +++ b/bridges/modules/grandpa/src/lib.rs @@ -36,8 +36,6 @@ // Runtime-generated enums #![allow(clippy::large_enum_variant)] -use crate::weights::WeightInfo; - use bp_header_chain::{justification::GrandpaJustification, InitializationData}; use bp_runtime::{BlockNumberOf, Chain, HashOf, HasherOf, HeaderOf}; use finality_grandpa::voter_set::VoterSet; @@ -58,6 +56,7 @@ pub mod benchmarking; // Re-export in crate namespace for `construct_runtime!` pub use pallet::*; +pub use weights::WeightInfo; /// Block number of the bridged chain. pub type BridgedBlockNumber = BlockNumberOf<>::BridgedChain>; diff --git a/bridges/modules/messages/src/lib.rs b/bridges/modules/messages/src/lib.rs index 9f5f9d438c41..b1454d6810b7 100644 --- a/bridges/modules/messages/src/lib.rs +++ b/bridges/modules/messages/src/lib.rs @@ -37,7 +37,8 @@ // Generated by `decl_event!` #![allow(clippy::unused_unit)] -pub use crate::weights_ext::{ +pub use weights::WeightInfo; +pub use weights_ext::{ ensure_able_to_receive_confirmation, ensure_able_to_receive_message, ensure_weights_are_correct, WeightInfoExt, EXPECTED_DEFAULT_MESSAGE_LENGTH, }; @@ -45,7 +46,6 @@ pub use crate::weights_ext::{ use crate::{ inbound_lane::{InboundLane, InboundLaneStorage, ReceivalResult}, outbound_lane::{OutboundLane, OutboundLaneStorage, ReceivalConfirmationResult}, - weights::WeightInfo, }; use bp_messages::{ diff --git a/runtime/kusama/src/lib.rs b/runtime/kusama/src/lib.rs index 6e09ccc46fe6..7f6fda957583 100644 --- a/runtime/kusama/src/lib.rs +++ b/runtime/kusama/src/lib.rs @@ -1423,7 +1423,7 @@ pub type WithPolkadotMessagesInstance = (); impl pallet_bridge_messages::Config for Runtime { type Event = Event; - type WeightInfo = weights::pallet_bridge_messages::MillauWeight; + type WeightInfo = weights::pallet_bridge_messages::WeightInfo; type Parameter = polkadot_messages::WithPolkadotMessageBridgeParameter; type MaxMessagesToPruneAtOnce = MaxMessagesToPruneAtOnce; type MaxUnrewardedRelayerEntriesAtInboundLane = MaxUnrewardedRelayerEntriesAtInboundLane; diff --git a/runtime/kusama/src/polkadot_messages.rs b/runtime/kusama/src/polkadot_messages.rs index 88054c89e41a..4f5efbf34d71 100644 --- a/runtime/kusama/src/polkadot_messages.rs +++ b/runtime/kusama/src/polkadot_messages.rs @@ -470,6 +470,14 @@ impl MessagesConfig for Runtime { } } +impl pallet_bridge_messages::WeightInfoExt + for crate::weights::pallet_bridge_messages::WeightInfo +{ + fn expected_extra_storage_proof_size() -> u32 { + bp_kusama::EXTRA_STORAGE_PROOF_SIZE + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/runtime/polkadot/src/kusama_messages.rs b/runtime/polkadot/src/kusama_messages.rs index ad016e9e5401..9110cb8981d7 100644 --- a/runtime/polkadot/src/kusama_messages.rs +++ b/runtime/polkadot/src/kusama_messages.rs @@ -479,6 +479,14 @@ impl MessagesConfig for Runtime { } } +impl pallet_bridge_messages::WeightInfoExt + for crate::weights::pallet_bridge_messages::WeightInfo +{ + fn expected_extra_storage_proof_size() -> u32 { + bp_kusama::EXTRA_STORAGE_PROOF_SIZE + } +} + #[cfg(test)] mod tests { use super::*;