diff --git a/bridges/bin/millau/node/src/service.rs b/bridges/bin/millau/node/src/service.rs index 10e613f596..a9d866af73 100644 --- a/bridges/bin/millau/node/src/service.rs +++ b/bridges/bin/millau/node/src/service.rs @@ -318,8 +318,6 @@ pub fn new_full(config: Configuration) -> Result { task_manager .spawn_essential_handle() .spawn_blocking("grandpa-voter", sc_finality_grandpa::run_grandpa_voter(grandpa_config)?); - } else { - sc_finality_grandpa::setup_disabled_grandpa(network)?; } network_starter.start_network(); diff --git a/bridges/bin/millau/runtime/src/lib.rs b/bridges/bin/millau/runtime/src/lib.rs index 1502e39467..fcf443e937 100644 --- a/bridges/bin/millau/runtime/src/lib.rs +++ b/bridges/bin/millau/runtime/src/lib.rs @@ -31,6 +31,7 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); pub mod rialto_messages; use codec::Decode; +use frame_system::limits; use pallet_grandpa::{fg_primitives, AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList}; use sp_api::impl_runtime_apis; use sp_consensus_aura::sr25519::AuthorityId as AuraId; @@ -50,7 +51,7 @@ use sp_version::RuntimeVersion; pub use frame_support::{ construct_runtime, parameter_types, traits::{Currency, ExistenceRequirement, Imbalance, KeyOwnerProofSystem, Randomness}, - weights::{IdentityFee, RuntimeDbWeight, Weight}, + weights::{constants::WEIGHT_PER_SECOND, DispatchClass, IdentityFee, RuntimeDbWeight, Weight}, StorageValue, }; @@ -149,19 +150,17 @@ pub fn native_version() -> NativeVersion { parameter_types! { pub const BlockHashCount: BlockNumber = 250; - pub const MaximumBlockWeight: Weight = bp_millau::MAXIMUM_BLOCK_WEIGHT; - pub const ExtrinsicBaseWeight: Weight = 10_000_000; - pub const AvailableBlockRatio: Perbill = Perbill::from_percent(bp_millau::AVAILABLE_BLOCK_RATIO); - pub MaximumExtrinsicWeight: Weight = bp_millau::MAXIMUM_EXTRINSIC_WEIGHT; - pub const MaximumBlockLength: u32 = bp_millau::MAXIMUM_BLOCK_SIZE; pub const Version: RuntimeVersion = VERSION; pub const DbWeight: RuntimeDbWeight = RuntimeDbWeight { read: 60_000_000, // ~0.06 ms = ~60 µs write: 200_000_000, // ~0.2 ms = 200 µs }; + + pub RuntimeBlockLength: limits::BlockLength = bp_millau::runtime_block_length(); + pub RuntimeBlockWeights: limits::BlockWeights = bp_millau::runtime_block_weights(); } -impl frame_system::Trait for Runtime { +impl frame_system::Config for Runtime { /// The basic call filter to use in dispatchable. type BaseCallFilter = (); /// The identifier used to distinguish between accounts. @@ -186,24 +185,6 @@ impl frame_system::Trait for Runtime { type Origin = Origin; /// Maximum number of block number to block hash mappings to keep (oldest pruned first). type BlockHashCount = BlockHashCount; - /// Maximum weight of each block. - type MaximumBlockWeight = MaximumBlockWeight; - /// The weight of database operations that the runtime can invoke. - type DbWeight = DbWeight; - /// The weight of the overhead invoked on the block import process, independent of the - /// extrinsics included in that block. - type BlockExecutionWeight = (); - /// The base weight of any extrinsic processed by the runtime, independent of the - /// logic of that extrinsic. (Signature verification, nonce increment, fee, etc...) - type ExtrinsicBaseWeight = ExtrinsicBaseWeight; - /// The maximum weight that a single extrinsic of `Normal` dispatch class can have, - /// idependent of the logic of that extrinsics. (Roughly max block weight - average on - /// initialize cost). - type MaximumExtrinsicWeight = MaximumExtrinsicWeight; - /// Maximum size of all encoded transactions (in bytes) that are allowed in one block. - type MaximumBlockLength = MaximumBlockLength; - /// Portion of the block weight that is available to all normal transactions. - type AvailableBlockRatio = AvailableBlockRatio; /// Version of the runtime. type Version = Version; /// Provides information about the pallet setup in the runtime. @@ -217,12 +198,18 @@ impl frame_system::Trait for Runtime { // TODO: update me (https://github.com/paritytech/parity-bridges-common/issues/78) /// Weight information for the extrinsics of this pallet. type SystemWeightInfo = (); + /// Block and extrinsics weights: base values and limits. + type BlockWeights = RuntimeBlockWeights; + /// The maximum length of a block (in bytes). + type BlockLength = RuntimeBlockLength; + /// The weight of database operations that the runtime can invoke. + type DbWeight = DbWeight; } -impl pallet_aura::Trait for Runtime { +impl pallet_aura::Config for Runtime { type AuthorityId = AuraId; } -impl pallet_bridge_call_dispatch::Trait for Runtime { +impl pallet_bridge_call_dispatch::Config for Runtime { type Event = Event; type MessageId = (bp_message_lane::LaneId, bp_message_lane::MessageNonce); type Call = Call; @@ -232,7 +219,7 @@ impl pallet_bridge_call_dispatch::Trait for Runtime { type AccountIdConverter = bp_millau::AccountIdConverter; } -impl pallet_grandpa::Trait for Runtime { +impl pallet_grandpa::Config for Runtime { type Event = Event; type Call = Call; type KeyOwnerProofSystem = (); @@ -248,7 +235,7 @@ parameter_types! { pub const MinimumPeriod: u64 = SLOT_DURATION / 2; } -impl pallet_timestamp::Trait for Runtime { +impl pallet_timestamp::Config for Runtime { /// A timestamp: milliseconds since the unix epoch. type Moment = u64; type OnTimestampSet = Aura; @@ -264,7 +251,7 @@ parameter_types! { pub const MaxLocks: u32 = 50; } -impl pallet_balances::Trait for Runtime { +impl pallet_balances::Config for Runtime { /// The type for recording an account's balance. type Balance = Balance; /// The ubiquitous event type. @@ -282,14 +269,14 @@ parameter_types! { pub const TransactionByteFee: Balance = 1; } -impl pallet_transaction_payment::Trait for Runtime { +impl pallet_transaction_payment::Config for Runtime { type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter; type TransactionByteFee = TransactionByteFee; type WeightToFee = IdentityFee; type FeeMultiplierUpdate = (); } -impl pallet_sudo::Trait for Runtime { +impl pallet_sudo::Config for Runtime { type Event = Event; type Call = Call; } @@ -300,9 +287,9 @@ parameter_types! { pub const Offset: BlockNumber = 0; } -impl pallet_session::Trait for Runtime { +impl pallet_session::Config for Runtime { type Event = Event; - type ValidatorId = ::AccountId; + type ValidatorId = ::AccountId; type ValidatorIdOf = (); type ShouldEndSession = pallet_session::PeriodicSessions; type NextSessionRotation = pallet_session::PeriodicSessions; @@ -314,11 +301,11 @@ impl pallet_session::Trait for Runtime { type WeightInfo = (); } -impl pallet_substrate_bridge::Trait for Runtime { +impl pallet_substrate_bridge::Config for Runtime { type BridgedChain = bp_rialto::Rialto; } -impl pallet_shift_session_manager::Trait for Runtime {} +impl pallet_shift_session_manager::Config for Runtime {} parameter_types! { pub const MaxMessagesToPruneAtOnce: bp_message_lane::MessageNonce = 8; @@ -330,7 +317,7 @@ parameter_types! { bp_millau::MAX_MESSAGES_IN_DELIVERY_TRANSACTION; } -impl pallet_message_lane::Trait for Runtime { +impl pallet_message_lane::Config for Runtime { type Event = Event; type MaxMessagesToPruneAtOnce = MaxMessagesToPruneAtOnce; type MaxUnrewardedRelayerEntriesAtInboundLane = MaxUnrewardedRelayerEntriesAtInboundLane; diff --git a/bridges/bin/millau/runtime/src/rialto_messages.rs b/bridges/bin/millau/runtime/src/rialto_messages.rs index 061137e215..a2fba5faf2 100644 --- a/bridges/bin/millau/runtime/src/rialto_messages.rs +++ b/bridges/bin/millau/runtime/src/rialto_messages.rs @@ -89,12 +89,12 @@ impl MessageBridge for WithRialtoMessageBridge { type BridgedChain = Rialto; fn maximal_extrinsic_size_on_target_chain() -> u32 { - bp_rialto::MAXIMUM_EXTRINSIC_SIZE + bp_rialto::max_extrinsic_size() } fn weight_limits_of_message_on_bridged_chain(message_payload: &[u8]) -> RangeInclusive { // we don't want to relay too large messages + keep reserve for future upgrades - let upper_limit = bp_rialto::MAXIMUM_EXTRINSIC_WEIGHT / 2; + let upper_limit = bp_rialto::max_extrinsic_weight() / 2; // given Rialto chain parameters (`TransactionByteFee`, `WeightToFee`, `FeeMultiplierUpdate`), // the minimal weight of the message may be computed as message.length() @@ -116,12 +116,12 @@ impl MessageBridge for WithRialtoMessageBridge { } fn this_weight_to_this_balance(weight: Weight) -> bp_millau::Balance { - ::WeightToFee::calc(&weight) + ::WeightToFee::calc(&weight) } fn bridged_weight_to_bridged_balance(weight: Weight) -> bp_rialto::Balance { // we're using the same weights in both chains now - ::WeightToFee::calc(&weight) as _ + ::WeightToFee::calc(&weight) as _ } fn this_balance_to_bridged_balance(this_balance: bp_millau::Balance) -> bp_rialto::Balance { diff --git a/bridges/bin/rialto/node/src/service.rs b/bridges/bin/rialto/node/src/service.rs index bd4c587618..57415b7344 100644 --- a/bridges/bin/rialto/node/src/service.rs +++ b/bridges/bin/rialto/node/src/service.rs @@ -317,8 +317,6 @@ pub fn new_full(config: Configuration) -> Result { task_manager .spawn_essential_handle() .spawn_blocking("grandpa-voter", sc_finality_grandpa::run_grandpa_voter(grandpa_config)?); - } else { - sc_finality_grandpa::setup_disabled_grandpa(network)?; } network_starter.start_network(); diff --git a/bridges/bin/rialto/runtime/src/exchange.rs b/bridges/bin/rialto/runtime/src/exchange.rs index 1e68ce83f7..12fbadf012 100644 --- a/bridges/bin/rialto/runtime/src/exchange.rs +++ b/bridges/bin/rialto/runtime/src/exchange.rs @@ -128,7 +128,7 @@ impl MaybeLockFundsTransaction for EthTransaction { /// Prepares everything required to bench claim of funds locked by given transaction. #[cfg(feature = "runtime-benchmarks")] -pub(crate) fn prepare_environment_for_claim, I: frame_support::traits::Instance>( +pub(crate) fn prepare_environment_for_claim, I: frame_support::traits::Instance>( transactions: &[(RawTransaction, RawTransactionReceipt)], ) -> bp_eth_poa::H256 { use bp_eth_poa::compute_merkle_root; diff --git a/bridges/bin/rialto/runtime/src/lib.rs b/bridges/bin/rialto/runtime/src/lib.rs index 57b041f649..04534d4802 100644 --- a/bridges/bin/rialto/runtime/src/lib.rs +++ b/bridges/bin/rialto/runtime/src/lib.rs @@ -37,6 +37,7 @@ pub mod millau_messages; pub mod rialto_poa; use codec::Decode; +use frame_system::limits; use pallet_grandpa::{fg_primitives, AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList}; use sp_api::impl_runtime_apis; use sp_consensus_aura::sr25519::AuthorityId as AuraId; @@ -56,7 +57,7 @@ use sp_version::RuntimeVersion; pub use frame_support::{ construct_runtime, parameter_types, traits::{Currency, ExistenceRequirement, Imbalance, KeyOwnerProofSystem, Randomness}, - weights::{IdentityFee, RuntimeDbWeight, Weight}, + weights::{constants::WEIGHT_PER_SECOND, DispatchClass, IdentityFee, RuntimeDbWeight, Weight}, StorageValue, }; @@ -157,19 +158,17 @@ pub fn native_version() -> NativeVersion { parameter_types! { pub const BlockHashCount: BlockNumber = 250; - pub const MaximumBlockWeight: Weight = bp_rialto::MAXIMUM_BLOCK_WEIGHT; - pub const ExtrinsicBaseWeight: Weight = 10_000_000; - pub const AvailableBlockRatio: Perbill = Perbill::from_percent(bp_rialto::AVAILABLE_BLOCK_RATIO); - pub MaximumExtrinsicWeight: Weight = bp_rialto::MAXIMUM_EXTRINSIC_WEIGHT; - pub const MaximumBlockLength: u32 = bp_rialto::MAXIMUM_BLOCK_SIZE; pub const Version: RuntimeVersion = VERSION; pub const DbWeight: RuntimeDbWeight = RuntimeDbWeight { read: 60_000_000, // ~0.06 ms = ~60 µs write: 200_000_000, // ~0.2 ms = 200 µs }; + + pub RuntimeBlockLength: limits::BlockLength = bp_rialto::runtime_block_length(); + pub RuntimeBlockWeights: limits::BlockWeights = bp_rialto::runtime_block_weights(); } -impl frame_system::Trait for Runtime { +impl frame_system::Config for Runtime { /// The basic call filter to use in dispatchable. type BaseCallFilter = (); /// The identifier used to distinguish between accounts. @@ -194,24 +193,6 @@ impl frame_system::Trait for Runtime { type Origin = Origin; /// Maximum number of block number to block hash mappings to keep (oldest pruned first). type BlockHashCount = BlockHashCount; - /// Maximum weight of each block. - type MaximumBlockWeight = MaximumBlockWeight; - /// The weight of database operations that the runtime can invoke. - type DbWeight = DbWeight; - /// The weight of the overhead invoked on the block import process, independent of the - /// extrinsics included in that block. - type BlockExecutionWeight = (); - /// The base weight of any extrinsic processed by the runtime, independent of the - /// logic of that extrinsic. (Signature verification, nonce increment, fee, etc...) - type ExtrinsicBaseWeight = ExtrinsicBaseWeight; - /// The maximum weight that a single extrinsic of `Normal` dispatch class can have, - /// idependent of the logic of that extrinsics. (Roughly max block weight - average on - /// initialize cost). - type MaximumExtrinsicWeight = MaximumExtrinsicWeight; - /// Maximum size of all encoded transactions (in bytes) that are allowed in one block. - type MaximumBlockLength = MaximumBlockLength; - /// Portion of the block weight that is available to all normal transactions. - type AvailableBlockRatio = AvailableBlockRatio; /// Version of the runtime. type Version = Version; /// Provides information about the pallet setup in the runtime. @@ -225,14 +206,20 @@ impl frame_system::Trait for Runtime { // TODO: update me (https://github.com/paritytech/parity-bridges-common/issues/78) /// Weight information for the extrinsics of this pallet. type SystemWeightInfo = (); + /// Block and extrinsics weights: base values and limits. + type BlockWeights = RuntimeBlockWeights; + /// The maximum length of a block (in bytes). + type BlockLength = RuntimeBlockLength; + /// The weight of database operations that the runtime can invoke. + type DbWeight = DbWeight; } -impl pallet_aura::Trait for Runtime { +impl pallet_aura::Config for Runtime { type AuthorityId = AuraId; } type RialtoPoA = pallet_bridge_eth_poa::Instance1; -impl pallet_bridge_eth_poa::Trait for Runtime { +impl pallet_bridge_eth_poa::Config for Runtime { type AuraConfiguration = rialto_poa::BridgeAuraConfiguration; type FinalityVotesCachingInterval = rialto_poa::FinalityVotesCachingInterval; type ValidatorsConfiguration = rialto_poa::BridgeValidatorsConfiguration; @@ -242,7 +229,7 @@ impl pallet_bridge_eth_poa::Trait for Runtime { } type Kovan = pallet_bridge_eth_poa::Instance2; -impl pallet_bridge_eth_poa::Trait for Runtime { +impl pallet_bridge_eth_poa::Config for Runtime { type AuraConfiguration = kovan::BridgeAuraConfiguration; type FinalityVotesCachingInterval = kovan::FinalityVotesCachingInterval; type ValidatorsConfiguration = kovan::BridgeValidatorsConfiguration; @@ -252,7 +239,7 @@ impl pallet_bridge_eth_poa::Trait for Runtime { } type RialtoCurrencyExchange = pallet_bridge_currency_exchange::Instance1; -impl pallet_bridge_currency_exchange::Trait for Runtime { +impl pallet_bridge_currency_exchange::Config for Runtime { type OnTransactionSubmitted = (); type PeerBlockchain = rialto_poa::RialtoBlockchain; type PeerMaybeLockFundsTransaction = exchange::EthTransaction; @@ -263,7 +250,7 @@ impl pallet_bridge_currency_exchange::Trait for Runtime } type KovanCurrencyExchange = pallet_bridge_currency_exchange::Instance2; -impl pallet_bridge_currency_exchange::Trait for Runtime { +impl pallet_bridge_currency_exchange::Config for Runtime { type OnTransactionSubmitted = (); type PeerBlockchain = kovan::KovanBlockchain; type PeerMaybeLockFundsTransaction = exchange::EthTransaction; @@ -273,7 +260,7 @@ impl pallet_bridge_currency_exchange::Trait for Runtime { type DepositInto = DepositInto; } -impl pallet_bridge_call_dispatch::Trait for Runtime { +impl pallet_bridge_call_dispatch::Config for Runtime { type Event = Event; type MessageId = (bp_message_lane::LaneId, bp_message_lane::MessageNonce); type Call = Call; @@ -340,7 +327,7 @@ impl bp_currency_exchange::DepositInto for DepositInto { } } -impl pallet_grandpa::Trait for Runtime { +impl pallet_grandpa::Config for Runtime { type Event = Event; type Call = Call; type KeyOwnerProofSystem = (); @@ -356,7 +343,7 @@ parameter_types! { pub const MinimumPeriod: u64 = SLOT_DURATION / 2; } -impl pallet_timestamp::Trait for Runtime { +impl pallet_timestamp::Config for Runtime { /// A timestamp: milliseconds since the unix epoch. type Moment = u64; type OnTimestampSet = Aura; @@ -372,7 +359,7 @@ parameter_types! { pub const MaxLocks: u32 = 50; } -impl pallet_balances::Trait for Runtime { +impl pallet_balances::Config for Runtime { /// The type for recording an account's balance. type Balance = Balance; /// The ubiquitous event type. @@ -390,14 +377,14 @@ parameter_types! { pub const TransactionByteFee: Balance = 1; } -impl pallet_transaction_payment::Trait for Runtime { +impl pallet_transaction_payment::Config for Runtime { type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter; type TransactionByteFee = TransactionByteFee; type WeightToFee = IdentityFee; type FeeMultiplierUpdate = (); } -impl pallet_sudo::Trait for Runtime { +impl pallet_sudo::Config for Runtime { type Event = Event; type Call = Call; } @@ -407,9 +394,9 @@ parameter_types! { pub const Offset: BlockNumber = 0; } -impl pallet_session::Trait for Runtime { +impl pallet_session::Config for Runtime { type Event = Event; - type ValidatorId = ::AccountId; + type ValidatorId = ::AccountId; type ValidatorIdOf = (); type ShouldEndSession = pallet_session::PeriodicSessions; type NextSessionRotation = pallet_session::PeriodicSessions; @@ -421,11 +408,11 @@ impl pallet_session::Trait for Runtime { type WeightInfo = (); } -impl pallet_substrate_bridge::Trait for Runtime { +impl pallet_substrate_bridge::Config for Runtime { type BridgedChain = bp_millau::Millau; } -impl pallet_shift_session_manager::Trait for Runtime {} +impl pallet_shift_session_manager::Config for Runtime {} parameter_types! { pub const MaxMessagesToPruneAtOnce: bp_message_lane::MessageNonce = 8; @@ -438,7 +425,7 @@ parameter_types! { } pub(crate) type WithMillauMessageLaneInstance = pallet_message_lane::DefaultInstance; -impl pallet_message_lane::Trait for Runtime { +impl pallet_message_lane::Config for Runtime { type Event = Event; type MaxMessagesToPruneAtOnce = MaxMessagesToPruneAtOnce; type MaxUnrewardedRelayerEntriesAtInboundLane = MaxUnrewardedRelayerEntriesAtInboundLane; @@ -777,18 +764,18 @@ impl_runtime_apis! { use pallet_bridge_currency_exchange::benchmarking::{ Module as BridgeCurrencyExchangeBench, - Trait as BridgeCurrencyExchangeTrait, + Config as BridgeCurrencyExchangeConfig, ProofParams as BridgeCurrencyExchangeProofParams, }; - impl BridgeCurrencyExchangeTrait for Runtime { + impl BridgeCurrencyExchangeConfig for Runtime { fn make_proof( proof_params: BridgeCurrencyExchangeProofParams, ) -> crate::exchange::EthereumTransactionInclusionProof { use bp_currency_exchange::DepositInto; if proof_params.recipient_exists { - >::DepositInto::deposit_into( + >::DepositInto::deposit_into( proof_params.recipient.clone(), ExistentialDeposit::get(), ).unwrap(); @@ -817,11 +804,11 @@ impl_runtime_apis! { use pallet_message_lane::benchmarking::{ Module as MessageLaneBench, - Trait as MessageLaneTrait, + Config as MessageLaneConfig, MessageParams as MessageLaneMessageParams, }; - impl MessageLaneTrait for Runtime { + impl MessageLaneConfig for Runtime { fn endow_account(account: &Self::AccountId) { pallet_balances::Module::::make_free_balance_be( account, @@ -923,7 +910,7 @@ mod tests { let initial_amount = as Currency>::free_balance(&existing_account); let additional_amount = 10_000; - >::DepositInto::deposit_into( + >::DepositInto::deposit_into( existing_account.clone(), additional_amount, ) @@ -942,7 +929,7 @@ mod tests { let initial_amount = 0; let additional_amount = ExistentialDeposit::get() + 10_000; let new_account: AccountId = [42u8; 32].into(); - >::DepositInto::deposit_into( + >::DepositInto::deposit_into( new_account.clone(), additional_amount, ) diff --git a/bridges/bin/rialto/runtime/src/millau_messages.rs b/bridges/bin/rialto/runtime/src/millau_messages.rs index 680fcb747f..77139b2bb6 100644 --- a/bridges/bin/rialto/runtime/src/millau_messages.rs +++ b/bridges/bin/rialto/runtime/src/millau_messages.rs @@ -89,12 +89,12 @@ impl MessageBridge for WithMillauMessageBridge { type BridgedChain = Millau; fn maximal_extrinsic_size_on_target_chain() -> u32 { - bp_millau::MAXIMUM_EXTRINSIC_SIZE + bp_millau::max_extrinsic_size() } fn weight_limits_of_message_on_bridged_chain(message_payload: &[u8]) -> RangeInclusive { // we don't want to relay too large messages + keep reserve for future upgrades - let upper_limit = bp_millau::MAXIMUM_EXTRINSIC_WEIGHT / 2; + let upper_limit = bp_millau::max_extrinsic_weight() / 2; // given Millau chain parameters (`TransactionByteFee`, `WeightToFee`, `FeeMultiplierUpdate`), // the minimal weight of the message may be computed as message.length() @@ -116,12 +116,12 @@ impl MessageBridge for WithMillauMessageBridge { } fn this_weight_to_this_balance(weight: Weight) -> bp_rialto::Balance { - ::WeightToFee::calc(&weight) + ::WeightToFee::calc(&weight) } fn bridged_weight_to_bridged_balance(weight: Weight) -> bp_millau::Balance { // we're using the same weights in both chains now - ::WeightToFee::calc(&weight) as _ + ::WeightToFee::calc(&weight) as _ } fn this_balance_to_bridged_balance(this_balance: bp_rialto::Balance) -> bp_millau::Balance { diff --git a/bridges/bin/runtime-common/src/messages.rs b/bridges/bin/runtime-common/src/messages.rs index 0c7d4ff4be..3ec1fb7284 100644 --- a/bridges/bin/runtime-common/src/messages.rs +++ b/bridges/bin/runtime-common/src/messages.rs @@ -202,7 +202,7 @@ pub mod source { } // The maximal size of extrinsic at Substrate-based chain depends on the - // `frame_system::Trait::MaximumBlockLength` and `frame_system::Trait::AvailableBlockRatio` + // `frame_system::Config::MaximumBlockLength` and `frame_system::Config::AvailableBlockRatio` // constants. This check is here to be sure that the lane won't stuck because message is too // large to fit into delivery transaction. // @@ -261,10 +261,10 @@ pub mod source { proof: FromBridgedChainMessagesDeliveryProof, ) -> Result, &'static str> where - ThisRuntime: pallet_substrate_bridge::Trait, - ThisRuntime: pallet_message_lane::Trait>>, + ThisRuntime: pallet_substrate_bridge::Config, + ThisRuntime: pallet_message_lane::Config>>, HashOf>: - Into::BridgedChain>>, + Into::BridgedChain>>, { let (bridged_header_hash, bridged_storage_proof, lane) = proof; pallet_substrate_bridge::Module::::parse_finalized_storage_proof( @@ -359,7 +359,7 @@ pub mod target { for FromBridgedChainMessageDispatch where ThisCallDispatchInstance: frame_support::traits::Instance, - ThisRuntime: pallet_bridge_call_dispatch::Trait, + ThisRuntime: pallet_bridge_call_dispatch::Config, pallet_bridge_call_dispatch::Module: bp_message_dispatch::MessageDispatch< (LaneId, MessageNonce), @@ -396,10 +396,10 @@ pub mod target { max_messages: MessageNonce, ) -> Result>>>, &'static str> where - ThisRuntime: pallet_substrate_bridge::Trait, - ThisRuntime: pallet_message_lane::Trait>>, + ThisRuntime: pallet_substrate_bridge::Config, + ThisRuntime: pallet_message_lane::Config>>, HashOf>: - Into::BridgedChain>>, + Into::BridgedChain>>, { verify_messages_proof_with_parser::( proof, @@ -459,7 +459,7 @@ pub mod target { where H: Hasher, B: MessageBridge, - ThisRuntime: pallet_message_lane::Trait>>, + ThisRuntime: pallet_message_lane::Config>>, { fn read_raw_outbound_lane_data(&self, lane_id: &LaneId) -> Option> { let storage_outbound_lane_data_key = pallet_message_lane::storage_keys::outbound_lane_data_key::< diff --git a/bridges/modules/call-dispatch/src/lib.rs b/bridges/modules/call-dispatch/src/lib.rs index 19c728162e..09e4970265 100644 --- a/bridges/modules/call-dispatch/src/lib.rs +++ b/bridges/modules/call-dispatch/src/lib.rs @@ -95,9 +95,9 @@ pub struct MessagePayload: frame_system::Trait { +pub trait Config: frame_system::Config { /// The overarching event type. - type Event: From> + Into<::Event>; + type Event: From> + Into<::Event>; /// Id of the message. Whenever message is passed to the dispatch module, it emits /// event with this id + dispatch result. Could be e.g. (LaneId, MessageNonce) if /// it comes from message-lane module. @@ -113,7 +113,7 @@ pub trait Trait: frame_system::Trait { type Call: Parameter + GetDispatchInfo + Dispatchable< - Origin = ::Origin, + Origin = ::Origin, PostInfo = frame_support::dispatch::PostDispatchInfo, >; /// A type which can be turned into an AccountId from a 256-bit hash. @@ -123,12 +123,12 @@ pub trait Trait: frame_system::Trait { } decl_storage! { - trait Store for Module, I: Instance = DefaultInstance> as CallDispatch {} + trait Store for Module, I: Instance = DefaultInstance> as CallDispatch {} } decl_event!( pub enum Event where - >::MessageId + >::MessageId { /// Message has been rejected by dispatcher because of spec version mismatch. /// Last two arguments are: expected and passed spec version. @@ -147,18 +147,18 @@ decl_event!( decl_module! { /// Call Dispatch FRAME Pallet. - pub struct Module, I: Instance = DefaultInstance> for enum Call where origin: T::Origin { + pub struct Module, I: Instance = DefaultInstance> for enum Call where origin: T::Origin { /// Deposit one of this module's events by using the default implementation. fn deposit_event() = default; } } -impl, I: Instance> MessageDispatch for Module { +impl, I: Instance> MessageDispatch for Module { type Message = MessagePayload< T::SourceChainAccountId, T::TargetChainAccountPublic, T::TargetChainSignature, - >::Call, + >::Call, >; fn dispatch_weight(message: &Self::Message) -> Weight { @@ -168,7 +168,7 @@ impl, I: Instance> MessageDispatch for Module { fn dispatch(bridge: InstanceId, id: T::MessageId, message: Self::Message) { // verify spec version // (we want it to be the same, because otherwise we may decode Call improperly) - let expected_version = ::Version::get().spec_version; + let expected_version = ::Version::get().spec_version; if message.spec_version != expected_version { frame_support::debug::trace!( "Message {:?}/{:?}: spec_version mismatch. Expected {:?}, got {:?}", @@ -384,7 +384,7 @@ mod tests { pub const AvailableBlockRatio: Perbill = Perbill::one(); } - impl frame_system::Trait for TestRuntime { + impl frame_system::Config for TestRuntime { type Origin = Origin; type Index = u64; type Call = Call; @@ -396,13 +396,6 @@ mod tests { type Header = Header; type Event = TestEvent; type BlockHashCount = BlockHashCount; - type MaximumBlockWeight = MaximumBlockWeight; - type DbWeight = (); - type BlockExecutionWeight = (); - type ExtrinsicBaseWeight = (); - type MaximumExtrinsicWeight = (); - type AvailableBlockRatio = AvailableBlockRatio; - type MaximumBlockLength = MaximumBlockLength; type Version = (); type PalletInfo = (); type AccountData = (); @@ -410,9 +403,12 @@ mod tests { type OnKilledAccount = (); type BaseCallFilter = (); type SystemWeightInfo = (); + type BlockWeights = (); + type BlockLength = (); + type DbWeight = (); } - impl Trait for TestRuntime { + impl Config for TestRuntime { type Event = TestEvent; type MessageId = MessageId; type SourceChainAccountId = AccountId; @@ -435,7 +431,7 @@ mod tests { fn prepare_message( origin: CallOrigin, call: Call, - ) -> as MessageDispatch<::MessageId>>::Message { + ) -> as MessageDispatch<::MessageId>>::Message { MessagePayload { spec_version: TEST_SPEC_VERSION, weight: TEST_WEIGHT, @@ -446,20 +442,20 @@ mod tests { fn prepare_root_message( call: Call, - ) -> as MessageDispatch<::MessageId>>::Message { + ) -> as MessageDispatch<::MessageId>>::Message { prepare_message(CallOrigin::SourceRoot, call) } fn prepare_target_message( call: Call, - ) -> as MessageDispatch<::MessageId>>::Message { + ) -> as MessageDispatch<::MessageId>>::Message { let origin = CallOrigin::TargetAccount(1, TestAccountPublic(1), TestSignature(1)); prepare_message(origin, call) } fn prepare_source_message( call: Call, - ) -> as MessageDispatch<::MessageId>>::Message { + ) -> as MessageDispatch<::MessageId>>::Message { let origin = CallOrigin::SourceAccount(1); prepare_message(origin, call) } diff --git a/bridges/modules/currency-exchange/src/benchmarking.rs b/bridges/modules/currency-exchange/src/benchmarking.rs index 189dac8407..73304ff40b 100644 --- a/bridges/modules/currency-exchange/src/benchmarking.rs +++ b/bridges/modules/currency-exchange/src/benchmarking.rs @@ -18,7 +18,7 @@ //! So we are giving runtime opportunity to prepare environment and construct proof //! before invoking module calls. -use super::{BaseHeaderChain, Call, Instance, Module as CurrencyExchangeModule, Trait as CurrencyExchangeTrait}; +use super::{BaseHeaderChain, Call, Config as CurrencyExchangeConfig, Instance, Module as CurrencyExchangeModule}; use sp_std::prelude::*; use frame_benchmarking::{account, benchmarks_instance}; @@ -29,7 +29,7 @@ const WORST_TX_SIZE_FACTOR: u32 = 1000; const WORST_PROOF_SIZE_FACTOR: u32 = 1000; /// Module we're benchmarking here. -pub struct Module, I: Instance>(CurrencyExchangeModule); +pub struct Module, I: Instance>(CurrencyExchangeModule); /// Proof benchmarking parameters. pub struct ProofParams { @@ -45,12 +45,12 @@ pub struct ProofParams { pub proof_size_factor: u32, } -/// Trait that must be implemented by runtime. -pub trait Trait: CurrencyExchangeTrait { +/// Config that must be implemented by runtime. +pub trait Config: CurrencyExchangeConfig { /// Prepare proof for importing exchange transaction. fn make_proof( proof_params: ProofParams, - ) -> <>::PeerBlockchain as BaseHeaderChain>::TransactionInclusionProof; + ) -> <>::PeerBlockchain as BaseHeaderChain>::TransactionInclusionProof; } benchmarks_instance! { diff --git a/bridges/modules/currency-exchange/src/lib.rs b/bridges/modules/currency-exchange/src/lib.rs index 036f3b564c..4ff88e7b03 100644 --- a/bridges/modules/currency-exchange/src/lib.rs +++ b/bridges/modules/currency-exchange/src/lib.rs @@ -35,7 +35,7 @@ pub trait OnTransactionSubmitted { } /// The module configuration trait -pub trait Trait: frame_system::Trait { +pub trait Config: frame_system::Config { /// Handler for transaction submission result. type OnTransactionSubmitted: OnTransactionSubmitted; /// Represents the blockchain that we'll be exchanging currency with. @@ -61,7 +61,7 @@ pub trait Trait: frame_system::Trait { } decl_error! { - pub enum Error for Module, I: Instance> { + pub enum Error for Module, I: Instance> { /// Invalid peer blockchain transaction provided. InvalidTransaction, /// Peer transaction has invalid amount. @@ -84,12 +84,12 @@ decl_error! { } decl_module! { - pub struct Module, I: Instance = DefaultInstance> for enum Call where origin: T::Origin { + pub struct Module, I: Instance = DefaultInstance> for enum Call where origin: T::Origin { /// Imports lock fund transaction of the peer blockchain. #[weight = 0] // TODO: update me (https://github.com/paritytech/parity-bridges-common/issues/78) pub fn import_peer_transaction( origin, - proof: <>::PeerBlockchain as BaseHeaderChain>::TransactionInclusionProof, + proof: <>::PeerBlockchain as BaseHeaderChain>::TransactionInclusionProof, ) -> DispatchResult { let submitter = frame_system::ensure_signed(origin)?; @@ -125,13 +125,13 @@ decl_module! { } decl_storage! { - trait Store for Module, I: Instance = DefaultInstance> as Bridge { + trait Store for Module, I: Instance = DefaultInstance> as Bridge { /// All transfers that have already been claimed. Transfers: map hasher(blake2_128_concat) ::Id => (); } } -impl, I: Instance> Module { +impl, I: Instance> Module { /// Returns true if currency exchange module is able to import given transaction proof in /// its current state. pub fn filter_transaction_proof(proof: &::TransactionInclusionProof) -> bool { @@ -149,7 +149,7 @@ impl, I: Instance> Module { } } -impl, I: Instance> From for Error { +impl, I: Instance> From for Error { fn from(error: ExchangeError) -> Self { match error { ExchangeError::InvalidTransaction => Error::InvalidTransaction, @@ -168,7 +168,7 @@ impl OnTransactionSubmitted for () { } /// Exchange deposit details. -struct DepositDetails, I: Instance> { +struct DepositDetails, I: Instance> { /// Transfer id. pub transfer_id: ::Id, /// Transfer recipient. @@ -179,16 +179,16 @@ struct DepositDetails, I: Instance> { /// Verify and parse transaction proof, preparing everything required for importing /// this transaction proof. -fn prepare_deposit_details, I: Instance>( - proof: &<>::PeerBlockchain as BaseHeaderChain>::TransactionInclusionProof, +fn prepare_deposit_details, I: Instance>( + proof: &<>::PeerBlockchain as BaseHeaderChain>::TransactionInclusionProof, ) -> Result, Error> { // ensure that transaction is included in finalized block that we know of - let transaction = >::PeerBlockchain::verify_transaction_inclusion_proof(proof) + let transaction = >::PeerBlockchain::verify_transaction_inclusion_proof(proof) .ok_or(Error::::UnfinalizedTransaction)?; // parse transaction let transaction = - >::PeerMaybeLockFundsTransaction::parse(&transaction).map_err(Error::::from)?; + >::PeerMaybeLockFundsTransaction::parse(&transaction).map_err(Error::::from)?; let transfer_id = transaction.id; ensure!( !Transfers::::contains_key(&transfer_id), @@ -325,7 +325,7 @@ mod tests { pub const AvailableBlockRatio: Perbill = Perbill::one(); } - impl frame_system::Trait for TestRuntime { + impl frame_system::Config for TestRuntime { type Origin = Origin; type Index = u64; type Call = (); @@ -337,13 +337,6 @@ mod tests { type Header = Header; type Event = (); type BlockHashCount = BlockHashCount; - type MaximumBlockWeight = MaximumBlockWeight; - type DbWeight = (); - type BlockExecutionWeight = (); - type ExtrinsicBaseWeight = (); - type MaximumExtrinsicWeight = (); - type AvailableBlockRatio = AvailableBlockRatio; - type MaximumBlockLength = MaximumBlockLength; type Version = (); type PalletInfo = (); type AccountData = (); @@ -351,9 +344,12 @@ mod tests { type OnKilledAccount = (); type BaseCallFilter = (); type SystemWeightInfo = (); + type BlockWeights = (); + type BlockLength = (); + type DbWeight = (); } - impl Trait for TestRuntime { + impl Config for TestRuntime { type OnTransactionSubmitted = DummyTransactionSubmissionHandler; type PeerBlockchain = DummyBlockchain; type PeerMaybeLockFundsTransaction = DummyTransaction; diff --git a/bridges/modules/ethereum/src/benchmarking.rs b/bridges/modules/ethereum/src/benchmarking.rs index 2dd58d6648..35a202f3f2 100644 --- a/bridges/modules/ethereum/src/benchmarking.rs +++ b/bridges/modules/ethereum/src/benchmarking.rs @@ -218,7 +218,7 @@ benchmarks_instance! { } } -fn initialize_bench, I: Instance>(num_validators: usize) -> AuraHeader { +fn initialize_bench, I: Instance>(num_validators: usize) -> AuraHeader { // Initialize storage with some initial header let initial_header = build_genesis_header(&validator(0)); let initial_difficulty = initial_header.difficulty; diff --git a/bridges/modules/ethereum/src/lib.rs b/bridges/modules/ethereum/src/lib.rs index 75062f7639..70ebbe624c 100644 --- a/bridges/modules/ethereum/src/lib.rs +++ b/bridges/modules/ethereum/src/lib.rs @@ -370,7 +370,7 @@ impl OnHeadersSubmitted for () { } /// The module configuration trait. -pub trait Trait: frame_system::Trait { +pub trait Config: frame_system::Config { /// Aura configuration. type AuraConfiguration: Get; /// Validators configuration. @@ -393,7 +393,7 @@ pub trait Trait: frame_system::Trait { } decl_module! { - pub struct Module, I: Instance = DefaultInstance> for enum Call where origin: T::Origin { + pub struct Module, I: Instance = DefaultInstance> for enum Call where origin: T::Origin { /// Import single Aura header. Requires transaction to be **UNSIGNED**. #[weight = 0] // TODO: update me (https://github.com/paritytech/parity-bridges-common/issues/78) pub fn import_unsigned_header(origin, header: AuraHeader, receipts: Option>) { @@ -457,7 +457,7 @@ decl_module! { } decl_storage! { - trait Store for Module, I: Instance = DefaultInstance> as Bridge { + trait Store for Module, I: Instance = DefaultInstance> as Bridge { /// Best known block. BestBlock: (HeaderId, U256); /// Best finalized block. @@ -505,7 +505,7 @@ decl_storage! { } } -impl, I: Instance> Module { +impl, I: Instance> Module { /// Returns number and hash of the best block known to the bridge module. /// The caller should only submit `import_header` transaction that makes /// (or leads to making) other header the best one. @@ -542,7 +542,7 @@ impl, I: Instance> Module { } } -impl, I: Instance> frame_support::unsigned::ValidateUnsigned for Module { +impl, I: Instance> frame_support::unsigned::ValidateUnsigned for Module { type Call = Call; fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity { @@ -584,7 +584,7 @@ impl, I: Instance> frame_support::unsigned::ValidateUnsigned for Mod #[derive(Default)] pub struct BridgeStorage(sp_std::marker::PhantomData<(T, I)>); -impl, I: Instance> BridgeStorage { +impl, I: Instance> BridgeStorage { /// Create new BridgeStorage. pub fn new() -> Self { BridgeStorage(sp_std::marker::PhantomData::<(T, I)>::default()) @@ -683,7 +683,7 @@ impl, I: Instance> BridgeStorage { } } -impl, I: Instance> Storage for BridgeStorage { +impl, I: Instance> Storage for BridgeStorage { type Submitter = T::AccountId; fn best_block(&self) -> (HeaderId, U256) { @@ -863,7 +863,7 @@ impl, I: Instance> Storage for BridgeStorage { /// Initialize storage. #[cfg(any(feature = "std", feature = "runtime-benchmarks"))] -pub(crate) fn initialize_storage, I: Instance>( +pub(crate) fn initialize_storage, I: Instance>( initial_header: &AuraHeader, initial_difficulty: U256, initial_validators: &[Address], @@ -1263,7 +1263,7 @@ pub(crate) mod tests { fn finality_votes_are_cached() { run_test(TOTAL_VALIDATORS, |ctx| { let mut storage = BridgeStorage::::new(); - let interval = ::FinalityVotesCachingInterval::get().unwrap(); + let interval = ::FinalityVotesCachingInterval::get().unwrap(); // for all headers with number < interval, cache entry is not created for i in 1..interval { diff --git a/bridges/modules/ethereum/src/mock.rs b/bridges/modules/ethereum/src/mock.rs index 1255cc6719..e6d105070f 100644 --- a/bridges/modules/ethereum/src/mock.rs +++ b/bridges/modules/ethereum/src/mock.rs @@ -18,7 +18,7 @@ pub use crate::test_utils::{insert_header, validator_utils::*, validators_change pub use bp_eth_poa::signatures::secret_to_address; use crate::validators::{ValidatorsConfiguration, ValidatorsSource}; -use crate::{AuraConfiguration, ChainTime, GenesisConfig, PruningStrategy, Trait}; +use crate::{AuraConfiguration, ChainTime, Config, GenesisConfig, PruningStrategy}; use bp_eth_poa::{Address, AuraHeader, H256, U256}; use frame_support::{impl_outer_origin, parameter_types, weights::Weight}; use secp256k1::SecretKey; @@ -44,7 +44,7 @@ parameter_types! { pub const AvailableBlockRatio: Perbill = Perbill::one(); } -impl frame_system::Trait for TestRuntime { +impl frame_system::Config for TestRuntime { type Origin = Origin; type Index = u64; type Call = (); @@ -56,13 +56,6 @@ impl frame_system::Trait for TestRuntime { type Header = SubstrateHeader; type Event = (); type BlockHashCount = BlockHashCount; - type MaximumBlockWeight = MaximumBlockWeight; - type DbWeight = (); - type BlockExecutionWeight = (); - type ExtrinsicBaseWeight = (); - type MaximumExtrinsicWeight = (); - type AvailableBlockRatio = AvailableBlockRatio; - type MaximumBlockLength = MaximumBlockLength; type Version = (); type PalletInfo = (); type AccountData = (); @@ -70,6 +63,9 @@ impl frame_system::Trait for TestRuntime { type OnKilledAccount = (); type BaseCallFilter = (); type SystemWeightInfo = (); + type BlockWeights = (); + type BlockLength = (); + type DbWeight = (); } parameter_types! { @@ -78,7 +74,7 @@ parameter_types! { pub TestValidatorsConfiguration: ValidatorsConfiguration = test_validators_config(); } -impl Trait for TestRuntime { +impl Config for TestRuntime { type AuraConfiguration = TestAuraConfiguration; type ValidatorsConfiguration = TestValidatorsConfiguration; type FinalityVotesCachingInterval = TestFinalityVotesCachingInterval; diff --git a/bridges/modules/ethereum/src/test_utils.rs b/bridges/modules/ethereum/src/test_utils.rs index b669856fdb..e1e145f3d1 100644 --- a/bridges/modules/ethereum/src/test_utils.rs +++ b/bridges/modules/ethereum/src/test_utils.rs @@ -27,7 +27,7 @@ use crate::finality::FinalityVotes; use crate::validators::CHANGE_EVENT_HASH; use crate::verification::calculate_score; -use crate::{HeaderToImport, Storage, Trait}; +use crate::{Config, HeaderToImport, Storage}; use bp_eth_poa::{ rlp_encode, @@ -73,7 +73,7 @@ impl HeaderBuilder { } /// Creates default header on top of parent with given hash. - pub fn with_parent_hash_on_runtime, I: crate::Instance>(parent_hash: H256) -> Self { + pub fn with_parent_hash_on_runtime, I: crate::Instance>(parent_hash: H256) -> Self { use crate::Headers; use frame_support::StorageMap; @@ -82,7 +82,7 @@ impl HeaderBuilder { } /// Creates default header on top of parent with given number. First parent is selected. - pub fn with_parent_number_on_runtime, I: crate::Instance>(parent_number: u64) -> Self { + pub fn with_parent_number_on_runtime, I: crate::Instance>(parent_number: u64) -> Self { use crate::HeadersByNumber; use frame_support::StorageMap; diff --git a/bridges/modules/message-lane/src/benchmarking.rs b/bridges/modules/message-lane/src/benchmarking.rs index ce1d4eb19c..e56038a555 100644 --- a/bridges/modules/message-lane/src/benchmarking.rs +++ b/bridges/modules/message-lane/src/benchmarking.rs @@ -31,7 +31,7 @@ pub const WORST_MESSAGE_SIZE_FACTOR: u32 = 1000; const SEED: u32 = 0; /// Module we're benchmarking here. -pub struct Module, I: crate::Instance>(crate::Module); +pub struct Module, I: crate::Instance>(crate::Module); /// Benchmark-specific message parameters. pub struct MessageParams { @@ -44,7 +44,7 @@ pub struct MessageParams { } /// Trait that must be implemented by runtime. -pub trait Trait: crate::Trait { +pub trait Config: crate::Config { /// Create given account and give it enough balance for test purposes. fn endow_account(account: &Self::AccountId); /// Prepare message to send over lane. @@ -83,7 +83,7 @@ fn bench_lane_id() -> LaneId { *b"test" } -fn send_regular_message, I: Instance>() { +fn send_regular_message, I: Instance>() { let mut outbound_lane = crate::outbound_lane::(bench_lane_id()); outbound_lane.send_message(MessageData { payload: vec![], @@ -91,7 +91,7 @@ fn send_regular_message, I: Instance>() { }); } -fn confirm_message_delivery, I: Instance>(nonce: MessageNonce) { +fn confirm_message_delivery, I: Instance>(nonce: MessageNonce) { let mut outbound_lane = crate::outbound_lane::(bench_lane_id()); assert!(outbound_lane.confirm_delivery(nonce).is_some()); } diff --git a/bridges/modules/message-lane/src/inbound_lane.rs b/bridges/modules/message-lane/src/inbound_lane.rs index 3a21a10223..10ec2f54a2 100644 --- a/bridges/modules/message-lane/src/inbound_lane.rs +++ b/bridges/modules/message-lane/src/inbound_lane.rs @@ -282,7 +282,7 @@ mod tests { fn fails_to_receive_messages_above_unrewarded_relayer_entries_limit_per_lane() { run_test(|| { let mut lane = inbound_lane::(TEST_LANE_ID); - let max_nonce = ::MaxUnrewardedRelayerEntriesAtInboundLane::get(); + let max_nonce = ::MaxUnrewardedRelayerEntriesAtInboundLane::get(); for current_nonce in 1..max_nonce + 1 { assert!(lane.receive_message::( TEST_RELAYER_A + current_nonce, @@ -315,7 +315,7 @@ mod tests { fn fails_to_receive_messages_above_unconfirmed_messages_limit_per_lane() { run_test(|| { let mut lane = inbound_lane::(TEST_LANE_ID); - let max_nonce = ::MaxUnconfirmedMessagesAtInboundLane::get(); + let max_nonce = ::MaxUnconfirmedMessagesAtInboundLane::get(); for current_nonce in 1..=max_nonce { assert!(lane.receive_message::( TEST_RELAYER_A, diff --git a/bridges/modules/message-lane/src/lib.rs b/bridges/modules/message-lane/src/lib.rs index 1c8553b8bb..77bfc72f2c 100644 --- a/bridges/modules/message-lane/src/lib.rs +++ b/bridges/modules/message-lane/src/lib.rs @@ -69,11 +69,11 @@ const DELIVERY_OVERHEAD_WEIGHT: Weight = 0; const SINGLE_MESSAGE_DELIVERY_WEIGHT: Weight = 0; /// The module configuration trait -pub trait Trait: frame_system::Trait { +pub trait Config: frame_system::Config { // General types /// They overarching event type. - type Event: From> + Into<::Event>; + type Event: From> + Into<::Event>; /// Maximal number of messages that may be pruned during maintenance. Maintenance occurs /// whenever new message is sent. The reason is that if you want to use lane, you should /// be ready to pay for its maintenance. @@ -133,17 +133,17 @@ pub trait Trait: frame_system::Trait { type MessageDispatch: MessageDispatch; } -/// Shortcut to messages proof type for Trait. +/// Shortcut to messages proof type for Config. type MessagesProofOf = - <>::SourceHeaderChain as SourceHeaderChain<>::InboundMessageFee>>::MessagesProof; -/// Shortcut to messages delivery proof type for Trait. -type MessagesDeliveryProofOf = <>::TargetHeaderChain as TargetHeaderChain< - >::OutboundPayload, - ::AccountId, + <>::SourceHeaderChain as SourceHeaderChain<>::InboundMessageFee>>::MessagesProof; +/// Shortcut to messages delivery proof type for Config. +type MessagesDeliveryProofOf = <>::TargetHeaderChain as TargetHeaderChain< + >::OutboundPayload, + ::AccountId, >>::MessagesDeliveryProof; decl_error! { - pub enum Error for Module, I: Instance> { + pub enum Error for Module, I: Instance> { /// All pallet operations are halted. Halted, /// Message has been treated as invalid by chain verifier. @@ -162,7 +162,7 @@ decl_error! { } decl_storage! { - trait Store for Module, I: Instance = DefaultInstance> as MessageLane { + trait Store for Module, I: Instance = DefaultInstance> as MessageLane { /// Optional pallet owner. /// /// Pallet owner has a right to halt all pallet operations and then resume it. If it is @@ -192,7 +192,7 @@ decl_storage! { decl_event!( pub enum Event where - ::AccountId, + ::AccountId, { /// Message has been accepted and is waiting to be delivered. MessageAccepted(LaneId, MessageNonce), @@ -204,7 +204,7 @@ decl_event!( ); decl_module! { - pub struct Module, I: Instance = DefaultInstance> for enum Call where origin: T::Origin { + pub struct Module, I: Instance = DefaultInstance> for enum Call where origin: T::Origin { /// Deposit one of this module's events by using the default implementation. fn deposit_event() = default; @@ -443,7 +443,7 @@ decl_module! { nonce, }).expect("message was just confirmed; we never prune unconfirmed messages; qed"); - >::MessageDeliveryAndDispatchPayment::pay_relayer_reward( + >::MessageDeliveryAndDispatchPayment::pay_relayer_reward( &confirmation_relayer, &relayer, &message_data.fee, @@ -464,7 +464,7 @@ decl_module! { } } -impl, I: Instance> Module { +impl, I: Instance> Module { /// Get payload of given outbound message. pub fn outbound_message_payload(lane: LaneId, nonce: MessageNonce) -> Option { OutboundMessages::::get(MessageKey { lane_id: lane, nonce }).map(|message_data| message_data.payload) @@ -521,7 +521,7 @@ pub mod storage_keys { use sp_core::storage::StorageKey; /// Storage key of the outbound message in the runtime storage. - pub fn message_key, I: Instance>(lane: &LaneId, nonce: MessageNonce) -> StorageKey { + pub fn message_key, I: Instance>(lane: &LaneId, nonce: MessageNonce) -> StorageKey { let message_key = MessageKey { lane_id: *lane, nonce }; let raw_storage_key = OutboundMessages::::storage_map_final_key(message_key); StorageKey(raw_storage_key) @@ -533,13 +533,13 @@ pub mod storage_keys { } /// Storage key of the inbound message lane state in the runtime storage. - pub fn inbound_lane_data_key, I: Instance>(lane: &LaneId) -> StorageKey { + pub fn inbound_lane_data_key, I: Instance>(lane: &LaneId) -> StorageKey { StorageKey(InboundLanes::::storage_map_final_key(*lane)) } } /// Ensure that the origin is either root, or `ModuleOwner`. -fn ensure_owner_or_root, I: Instance>(origin: T::Origin) -> Result<(), BadOrigin> { +fn ensure_owner_or_root, I: Instance>(origin: T::Origin) -> Result<(), BadOrigin> { match origin.into() { Ok(RawOrigin::Root) => Ok(()), Ok(RawOrigin::Signed(ref signer)) if Some(signer) == Module::::module_owner().as_ref() => Ok(()), @@ -548,7 +548,7 @@ fn ensure_owner_or_root, I: Instance>(origin: T::Origin) -> Result<( } /// Ensure that the pallet is in operational mode (not halted). -fn ensure_operational, I: Instance>() -> Result<(), Error> { +fn ensure_operational, I: Instance>() -> Result<(), Error> { if IsHalted::::get() { Err(Error::::Halted) } else { @@ -557,7 +557,7 @@ fn ensure_operational, I: Instance>() -> Result<(), Error> { } /// Creates new inbound lane object, backed by runtime storage. -fn inbound_lane, I: Instance>(lane_id: LaneId) -> InboundLane> { +fn inbound_lane, I: Instance>(lane_id: LaneId) -> InboundLane> { InboundLane::new(RuntimeInboundLaneStorage { lane_id, cached_data: RefCell::new(None), @@ -566,7 +566,7 @@ fn inbound_lane, I: Instance>(lane_id: LaneId) -> InboundLane, I: Instance>(lane_id: LaneId) -> OutboundLane> { +fn outbound_lane, I: Instance>(lane_id: LaneId) -> OutboundLane> { OutboundLane::new(RuntimeOutboundLaneStorage { lane_id, _phantom: Default::default(), @@ -574,13 +574,13 @@ fn outbound_lane, I: Instance>(lane_id: LaneId) -> OutboundLane, I = DefaultInstance> { +struct RuntimeInboundLaneStorage, I = DefaultInstance> { lane_id: LaneId, cached_data: RefCell>>, _phantom: PhantomData, } -impl, I: Instance> InboundLaneStorage for RuntimeInboundLaneStorage { +impl, I: Instance> InboundLaneStorage for RuntimeInboundLaneStorage { type MessageFee = T::InboundMessageFee; type Relayer = T::InboundRelayer; @@ -625,7 +625,7 @@ struct RuntimeOutboundLaneStorage { _phantom: PhantomData<(T, I)>, } -impl, I: Instance> OutboundLaneStorage for RuntimeOutboundLaneStorage { +impl, I: Instance> OutboundLaneStorage for RuntimeOutboundLaneStorage { type MessageFee = T::OutboundMessageFee; fn id(&self) -> LaneId { @@ -691,7 +691,7 @@ fn verify_and_decode_messages_proof, Fee, Dispatch /// /// This account stores all the fees paid by submitters. Relayers are able to claim these /// funds as at their convenience. -fn relayer_fund_account_id, I: Instance>() -> T::AccountId { +fn relayer_fund_account_id, I: Instance>() -> T::AccountId { use sp_runtime::traits::Convert; let encoded_id = bp_runtime::derive_relayer_fund_account_id(bp_runtime::NO_INSTANCE_ID); T::AccountIdConverter::convert(encoded_id) diff --git a/bridges/modules/message-lane/src/mock.rs b/bridges/modules/message-lane/src/mock.rs index cdf29938d8..2c3418b98f 100644 --- a/bridges/modules/message-lane/src/mock.rs +++ b/bridges/modules/message-lane/src/mock.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Parity Bridges Common. If not, see . -use crate::Trait; +use crate::Config; use bp_message_lane::{ source_chain::{LaneMessageVerifier, MessageDeliveryAndDispatchPayment, Sender, TargetHeaderChain}, @@ -69,7 +69,7 @@ parameter_types! { pub const AvailableBlockRatio: Perbill = Perbill::one(); } -impl frame_system::Trait for TestRuntime { +impl frame_system::Config for TestRuntime { type Origin = Origin; type Index = u64; type Call = (); @@ -81,13 +81,6 @@ impl frame_system::Trait for TestRuntime { type Header = SubstrateHeader; type Event = TestEvent; type BlockHashCount = BlockHashCount; - type MaximumBlockWeight = MaximumBlockWeight; - type DbWeight = (); - type BlockExecutionWeight = (); - type ExtrinsicBaseWeight = (); - type MaximumExtrinsicWeight = MaximumBlockWeight; - type AvailableBlockRatio = AvailableBlockRatio; - type MaximumBlockLength = MaximumBlockLength; type Version = (); type PalletInfo = (); type AccountData = (); @@ -95,6 +88,9 @@ impl frame_system::Trait for TestRuntime { type OnKilledAccount = (); type BaseCallFilter = (); type SystemWeightInfo = (); + type BlockWeights = (); + type BlockLength = (); + type DbWeight = (); } parameter_types! { @@ -104,7 +100,7 @@ parameter_types! { pub const MaxMessagesInDeliveryTransaction: u64 = 128; } -impl Trait for TestRuntime { +impl Config for TestRuntime { type Event = TestEvent; type MaxMessagesToPruneAtOnce = MaxMessagesToPruneAtOnce; type MaxUnrewardedRelayerEntriesAtInboundLane = MaxUnrewardedRelayerEntriesAtInboundLane; diff --git a/bridges/modules/shift-session-manager/src/lib.rs b/bridges/modules/shift-session-manager/src/lib.rs index 918c2513f4..88928986f0 100644 --- a/bridges/modules/shift-session-manager/src/lib.rs +++ b/bridges/modules/shift-session-manager/src/lib.rs @@ -23,21 +23,21 @@ use frame_support::{decl_module, decl_storage}; use sp_std::prelude::*; /// The module configuration trait. -pub trait Trait: pallet_session::Trait {} +pub trait Config: pallet_session::Config {} decl_module! { /// Shift session manager pallet. - pub struct Module for enum Call where origin: T::Origin {} + pub struct Module for enum Call where origin: T::Origin {} } decl_storage! { - trait Store for Module as ShiftSessionManager { + trait Store for Module as ShiftSessionManager { /// Validators of first two sessions. InitialValidators: Option>; } } -impl pallet_session::SessionManager for Module { +impl pallet_session::SessionManager for Module { fn end_session(_: sp_staking::SessionIndex) {} fn start_session(_: sp_staking::SessionIndex) {} fn new_session(session_index: sp_staking::SessionIndex) -> Option> { @@ -61,7 +61,7 @@ impl pallet_session::SessionManager for Module { } } -impl Module { +impl Module { /// Select validators for session. fn select_validators( session_index: sp_staking::SessionIndex, @@ -112,7 +112,7 @@ mod tests { pub const AvailableBlockRatio: Perbill = Perbill::one(); } - impl frame_system::Trait for TestRuntime { + impl frame_system::Config for TestRuntime { type Origin = Origin; type Index = u64; type Call = (); @@ -124,13 +124,6 @@ mod tests { type Header = Header; type Event = (); type BlockHashCount = BlockHashCount; - type MaximumBlockWeight = MaximumBlockWeight; - type DbWeight = (); - type BlockExecutionWeight = (); - type ExtrinsicBaseWeight = (); - type MaximumExtrinsicWeight = (); - type AvailableBlockRatio = AvailableBlockRatio; - type MaximumBlockLength = MaximumBlockLength; type Version = (); type PalletInfo = (); type AccountData = (); @@ -138,6 +131,9 @@ mod tests { type OnKilledAccount = (); type BaseCallFilter = (); type SystemWeightInfo = (); + type BlockWeights = (); + type BlockLength = (); + type DbWeight = (); } parameter_types! { @@ -145,9 +141,9 @@ mod tests { pub const Offset: u64 = 0; } - impl pallet_session::Trait for TestRuntime { + impl pallet_session::Config for TestRuntime { type Event = (); - type ValidatorId = ::AccountId; + type ValidatorId = ::AccountId; type ValidatorIdOf = ConvertInto; type ShouldEndSession = pallet_session::PeriodicSessions; type NextSessionRotation = pallet_session::PeriodicSessions; @@ -158,7 +154,7 @@ mod tests { type WeightInfo = (); } - impl Trait for TestRuntime {} + impl Config for TestRuntime {} pub struct TestSessionHandler; impl pallet_session::SessionHandler for TestSessionHandler { diff --git a/bridges/modules/substrate/src/lib.rs b/bridges/modules/substrate/src/lib.rs index 58bf3ea05d..aa01c32964 100644 --- a/bridges/modules/substrate/src/lib.rs +++ b/bridges/modules/substrate/src/lib.rs @@ -60,13 +60,13 @@ mod mock; mod fork_tests; /// Block number of the bridged chain. -pub(crate) type BridgedBlockNumber = BlockNumberOf<::BridgedChain>; +pub(crate) type BridgedBlockNumber = BlockNumberOf<::BridgedChain>; /// Block hash of the bridged chain. -pub(crate) type BridgedBlockHash = HashOf<::BridgedChain>; +pub(crate) type BridgedBlockHash = HashOf<::BridgedChain>; /// Hasher of the bridged chain. -pub(crate) type BridgedBlockHasher = HasherOf<::BridgedChain>; +pub(crate) type BridgedBlockHasher = HasherOf<::BridgedChain>; /// Header of the bridged chain. -pub(crate) type BridgedHeader = HeaderOf<::BridgedChain>; +pub(crate) type BridgedHeader = HeaderOf<::BridgedChain>; /// A convenience type identifying headers. #[derive(RuntimeDebug, PartialEq)] @@ -77,13 +77,13 @@ pub struct HeaderId { pub hash: H::Hash, } -pub trait Trait: frame_system::Trait { +pub trait Config: frame_system::Config { /// Chain that we are bridging here. type BridgedChain: Chain; } decl_storage! { - trait Store for Module as SubstrateBridge { + trait Store for Module as SubstrateBridge { /// The number of the highest block(s) we know of. BestHeight: BridgedBlockNumber; /// Hash of the header at the highest known height. @@ -137,7 +137,7 @@ decl_storage! { } decl_error! { - pub enum Error for Module { + pub enum Error for Module { /// This header has failed basic verification. InvalidHeader, /// This header has not been finalized. @@ -156,7 +156,7 @@ decl_error! { } decl_module! { - pub struct Module for enum Call where origin: T::Origin { + pub struct Module for enum Call where origin: T::Origin { type Error = Error; /// Import a signed Substrate header into the runtime. @@ -277,7 +277,7 @@ decl_module! { } } -impl Module { +impl Module { /// Get the highest header(s) that the pallet knows of. pub fn best_headers() -> Vec<(BridgedBlockNumber, BridgedBlockHash)> { PalletStorage::::new() @@ -353,7 +353,7 @@ impl Module { } /// Ensure that the origin is either root, or `ModuleOwner`. -fn ensure_owner_or_root(origin: T::Origin) -> Result<(), BadOrigin> { +fn ensure_owner_or_root(origin: T::Origin) -> Result<(), BadOrigin> { match origin.into() { Ok(RawOrigin::Root) => Ok(()), Ok(RawOrigin::Signed(ref signer)) if Some(signer) == >::module_owner().as_ref() => Ok(()), @@ -362,7 +362,7 @@ fn ensure_owner_or_root(origin: T::Origin) -> Result<(), BadOrigin> { } /// Ensure that the pallet is in operational mode (not halted). -fn ensure_operational() -> Result<(), Error> { +fn ensure_operational() -> Result<(), Error> { if IsHalted::get() { Err(>::Halted) } else { @@ -372,7 +372,7 @@ fn ensure_operational() -> Result<(), Error> { /// Since this writes to storage with no real checks this should only be used in functions that were /// called by a trusted origin. -fn initialize_bridge(init_params: InitializationData>) { +fn initialize_bridge(init_params: InitializationData>) { let InitializationData { header, authority_list, @@ -488,7 +488,7 @@ impl PalletStorage { } } -impl BridgeStorage for PalletStorage { +impl BridgeStorage for PalletStorage { type Header = BridgedHeader; fn write_header(&mut self, header: &ImportedHeader>) { diff --git a/bridges/modules/substrate/src/mock.rs b/bridges/modules/substrate/src/mock.rs index 88ed2ed469..7c2b5429ed 100644 --- a/bridges/modules/substrate/src/mock.rs +++ b/bridges/modules/substrate/src/mock.rs @@ -20,7 +20,7 @@ #![cfg(test)] -use crate::Trait; +use crate::Config; use bp_runtime::Chain; use frame_support::{impl_outer_origin, parameter_types, weights::Weight}; use sp_runtime::{ @@ -45,7 +45,7 @@ parameter_types! { pub const AvailableBlockRatio: Perbill = Perbill::one(); } -impl frame_system::Trait for TestRuntime { +impl frame_system::Config for TestRuntime { type Origin = Origin; type Index = u64; type Call = (); @@ -57,13 +57,6 @@ impl frame_system::Trait for TestRuntime { type Header = Header; type Event = (); type BlockHashCount = BlockHashCount; - type MaximumBlockWeight = MaximumBlockWeight; - type DbWeight = (); - type BlockExecutionWeight = (); - type ExtrinsicBaseWeight = (); - type MaximumExtrinsicWeight = (); - type AvailableBlockRatio = AvailableBlockRatio; - type MaximumBlockLength = MaximumBlockLength; type Version = (); type PalletInfo = (); type AccountData = (); @@ -71,9 +64,12 @@ impl frame_system::Trait for TestRuntime { type OnKilledAccount = (); type BaseCallFilter = (); type SystemWeightInfo = (); + type DbWeight = (); + type BlockWeights = (); + type BlockLength = (); } -impl Trait for TestRuntime { +impl Config for TestRuntime { type BridgedChain = TestBridgedChain; } @@ -81,10 +77,10 @@ impl Trait for TestRuntime { pub struct TestBridgedChain; impl Chain for TestBridgedChain { - type BlockNumber = ::BlockNumber; - type Hash = ::Hash; - type Hasher = ::Hashing; - type Header = ::Header; + type BlockNumber = ::BlockNumber; + type Hash = ::Hash; + type Hasher = ::Hashing; + type Header = ::Header; } pub fn run_test(test: impl FnOnce() -> T) -> T { diff --git a/bridges/modules/substrate/src/storage_proof.rs b/bridges/modules/substrate/src/storage_proof.rs index 820a84737f..4b908dde15 100644 --- a/bridges/modules/substrate/src/storage_proof.rs +++ b/bridges/modules/substrate/src/storage_proof.rs @@ -65,7 +65,7 @@ pub enum Error { StorageValueUnavailable, } -impl From for crate::Error { +impl From for crate::Error { fn from(error: Error) -> Self { match error { Error::StorageRootMismatch => crate::Error::StorageRootMismatch, diff --git a/bridges/primitives/millau/Cargo.toml b/bridges/primitives/millau/Cargo.toml index 1c22da3cd9..d512fc632a 100644 --- a/bridges/primitives/millau/Cargo.toml +++ b/bridges/primitives/millau/Cargo.toml @@ -22,6 +22,7 @@ serde = { version = "1.0.101", optional = true, features = ["derive"] } # Substrate Based Dependencies frame-support = { git = "https://github.com/paritytech/substrate.git", branch = "master" , default-features = false } +frame-system = { git = "https://github.com/paritytech/substrate.git", branch = "master" , default-features = false } sp-api = { git = "https://github.com/paritytech/substrate.git", branch = "master" , default-features = false } sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "master" , default-features = false } sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "master" , default-features = false } @@ -36,6 +37,7 @@ std = [ "bp-runtime/std", "fixed-hash/std", "frame-support/std", + "frame-system/std", "hash256-std-hasher/std", "impl-codec/std", "impl-serde", diff --git a/bridges/primitives/millau/src/lib.rs b/bridges/primitives/millau/src/lib.rs index 148a19be0f..5b74ec54c1 100644 --- a/bridges/primitives/millau/src/lib.rs +++ b/bridges/primitives/millau/src/lib.rs @@ -24,11 +24,14 @@ mod millau_hash; use bp_message_lane::{LaneId, MessageNonce, UnrewardedRelayersState}; use bp_runtime::Chain; -use frame_support::{weights::Weight, RuntimeDebug}; +use frame_support::{ + weights::{constants::WEIGHT_PER_MILLIS, DispatchClass, Weight}, + RuntimeDebug, +}; use sp_core::Hasher as HasherT; use sp_runtime::{ traits::{IdentifyAccount, Verify}, - MultiSignature, MultiSigner, + MultiSignature, MultiSigner, Perbill, }; use sp_std::prelude::*; use sp_trie::{trie_types::Layout, TrieConfiguration}; @@ -68,23 +71,25 @@ impl sp_runtime::traits::Hash for BlakeTwoAndKeccak256 { } } -/// Maximal weight of single Millau block. -pub const MAXIMUM_BLOCK_WEIGHT: Weight = 10_000_000_000; -/// Portion of block reserved for regular transactions. -pub const AVAILABLE_BLOCK_RATIO: u32 = 75; -/// Maximal weight of single Millau extrinsic (65% of maximum block weight = 75% for regular -/// transactions minus 10% for initialization). -pub const MAXIMUM_EXTRINSIC_WEIGHT: Weight = MAXIMUM_BLOCK_WEIGHT / 100 * (AVAILABLE_BLOCK_RATIO as Weight - 10); -/// Maximal size of Millau block. -pub const MAXIMUM_BLOCK_SIZE: u32 = 2 * 1024 * 1024; -/// Maximal size of single normal Millau extrinsic (75% of maximal block size). -pub const MAXIMUM_EXTRINSIC_SIZE: u32 = MAXIMUM_BLOCK_SIZE / 100 * AVAILABLE_BLOCK_RATIO; +/// Maximum weight of single Millau block. +/// +/// This represents 0.1 seconds of compute assuming a target block time of six seconds. +pub const MAXIMUM_BLOCK_WEIGHT: Weight = 10 * WEIGHT_PER_MILLIS; + +/// Represents the average portion of a block's weight that will be used by an +/// `on_initialize()` runtime call. +pub const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10); + +/// Represents the portion of a block that will be used by Normal extrinsics. +pub const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75); // TODO: may need to be updated after https://github.com/paritytech/parity-bridges-common/issues/78 /// Maximal number of messages in single delivery transaction. pub const MAX_MESSAGES_IN_DELIVERY_TRANSACTION: MessageNonce = 1024; + /// Maximal number of unrewarded relayer entries at inbound lane. pub const MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE: MessageNonce = 1024; + /// Maximal number of unconfirmed messages at inbound lane. pub const MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE: MessageNonce = 1024; @@ -155,6 +160,44 @@ impl sp_runtime::traits::Convert for AccountIdConverte hash.to_fixed_bytes().into() } } + +/// Get a struct which defines the weight limits and values used during extrinsic execution. +pub fn runtime_block_weights() -> frame_system::limits::BlockWeights { + frame_system::limits::BlockWeights::builder() + // Allowance for Normal class + .for_class(DispatchClass::Normal, |weights| { + weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT); + }) + // Allowance for Operational class + .for_class(DispatchClass::Operational, |weights| { + weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT); + // Extra reserved space for Operational class + weights.reserved = Some(MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT); + }) + // By default Mandatory class is not limited at all. + // This parameter is used to derive maximal size of a single extrinsic. + .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO) + .build_or_panic() +} + +/// Get the maximum weight (compute time) that a Normal extrinsic on the Millau chain can use. +pub fn max_extrinsic_weight() -> Weight { + runtime_block_weights() + .get(DispatchClass::Normal) + .max_extrinsic + .unwrap_or(Weight::MAX) +} + +/// Get a struct which tracks the length in bytes for each extrinsic class in a Millau block. +pub fn runtime_block_length() -> frame_system::limits::BlockLength { + frame_system::limits::BlockLength::max_with_normal_ratio(2 * 1024 * 1024, NORMAL_DISPATCH_RATIO) +} + +/// Get the maximum length in bytes that a Normal extrinsic on the Millau chain requires. +pub fn max_extrinsic_size() -> u32 { + *runtime_block_length().max.get(DispatchClass::Normal) +} + sp_api::decl_runtime_apis! { /// API for querying information about Millau headers from the Bridge Pallet instance. /// diff --git a/bridges/primitives/millau/src/millau_hash.rs b/bridges/primitives/millau/src/millau_hash.rs index 521b8997ad..e917329d2c 100644 --- a/bridges/primitives/millau/src/millau_hash.rs +++ b/bridges/primitives/millau/src/millau_hash.rs @@ -18,7 +18,7 @@ use parity_util_mem::MallocSizeOf; use sp_runtime::traits::CheckEqual; // `sp_core::H512` can't be used, because it doesn't implement `CheckEqual`, which is required -// by `frame_system::Trait::Hash`. +// by `frame_system::Config::Hash`. fixed_hash::construct_fixed_hash! { /// Hash type used in Millau chain. diff --git a/bridges/primitives/rialto/Cargo.toml b/bridges/primitives/rialto/Cargo.toml index 53305d7ed8..6d12dd0b0a 100644 --- a/bridges/primitives/rialto/Cargo.toml +++ b/bridges/primitives/rialto/Cargo.toml @@ -16,6 +16,7 @@ bp-runtime = { path = "../runtime", default-features = false } # Substrate Based Dependencies frame-support = { git = "https://github.com/paritytech/substrate.git", branch = "master" , default-features = false } +frame-system = { git = "https://github.com/paritytech/substrate.git", branch = "master" , default-features = false } sp-api = { git = "https://github.com/paritytech/substrate.git", branch = "master" , default-features = false } sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "master" , default-features = false } sp-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "master" , default-features = false } @@ -27,6 +28,7 @@ std = [ "bp-message-lane/std", "bp-runtime/std", "frame-support/std", + "frame-system/std", "sp-api/std", "sp-core/std", "sp-runtime/std", diff --git a/bridges/primitives/rialto/src/lib.rs b/bridges/primitives/rialto/src/lib.rs index f91f1689b9..26599786c2 100644 --- a/bridges/primitives/rialto/src/lib.rs +++ b/bridges/primitives/rialto/src/lib.rs @@ -22,31 +22,36 @@ use bp_message_lane::{LaneId, MessageNonce, UnrewardedRelayersState}; use bp_runtime::Chain; -use frame_support::{weights::Weight, RuntimeDebug}; +use frame_support::{ + weights::{constants::WEIGHT_PER_SECOND, DispatchClass, Weight}, + RuntimeDebug, +}; use sp_core::Hasher as HasherT; use sp_runtime::{ traits::{BlakeTwo256, Convert, IdentifyAccount, Verify}, - MultiSignature, MultiSigner, + MultiSignature, MultiSigner, Perbill, }; use sp_std::prelude::*; /// Maximal weight of single Rialto block. -pub const MAXIMUM_BLOCK_WEIGHT: Weight = 2_000_000_000_000; -/// Portion of block reserved for regular transactions. -pub const AVAILABLE_BLOCK_RATIO: u32 = 75; -/// Maximal weight of single Rialto extrinsic (65% of maximum block weight = 75% for regular -/// transactions minus 10% for initialization). -pub const MAXIMUM_EXTRINSIC_WEIGHT: Weight = MAXIMUM_BLOCK_WEIGHT / 100 * (AVAILABLE_BLOCK_RATIO as Weight - 10); -/// Maximal size of Rialto block. -pub const MAXIMUM_BLOCK_SIZE: u32 = 5 * 1024 * 1024; -/// Maximal size of single normal Rialto extrinsic (75% of maximal block size). -pub const MAXIMUM_EXTRINSIC_SIZE: u32 = MAXIMUM_BLOCK_SIZE / 100 * AVAILABLE_BLOCK_RATIO; +/// +/// This represents two seconds of compute assuming a target block time of six seconds. +pub const MAXIMUM_BLOCK_WEIGHT: Weight = 2 * WEIGHT_PER_SECOND; + +/// Represents the average portion of a block's weight that will be used by an +/// `on_initialize()` runtime call. +pub const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10); + +/// Represents the portion of a block that will be used by Normal extrinsics. +pub const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75); // TODO: may need to be updated after https://github.com/paritytech/parity-bridges-common/issues/78 /// Maximal number of messages in single delivery transaction. pub const MAX_MESSAGES_IN_DELIVERY_TRANSACTION: MessageNonce = 128; + /// Maximal number of unrewarded relayer entries at inbound lane. pub const MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE: MessageNonce = 128; + /// Maximal number of unconfirmed messages at inbound lane. pub const MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE: MessageNonce = 128; @@ -131,6 +136,43 @@ pub fn derive_account_from_millau_id(id: bp_runtime::SourceAccount) - AccountIdConverter::convert(encoded_id) } +/// Get a struct which defines the weight limits and values used during extrinsic execution. +pub fn runtime_block_weights() -> frame_system::limits::BlockWeights { + frame_system::limits::BlockWeights::builder() + // Allowance for Normal class + .for_class(DispatchClass::Normal, |weights| { + weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT); + }) + // Allowance for Operational class + .for_class(DispatchClass::Operational, |weights| { + weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT); + // Extra reserved space for Operational class + weights.reserved = Some(MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT); + }) + // By default Mandatory class is not limited at all. + // This parameter is used to derive maximal size of a single extrinsic. + .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO) + .build_or_panic() +} + +/// Get the maximum weight (compute time) that a Normal extrinsic on the Millau chain can use. +pub fn max_extrinsic_weight() -> Weight { + runtime_block_weights() + .get(DispatchClass::Normal) + .max_extrinsic + .unwrap_or(Weight::MAX) +} + +/// Get a struct which tracks the length in bytes for each extrinsic class in a Millau block. +pub fn runtime_block_length() -> frame_system::limits::BlockLength { + frame_system::limits::BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO) +} + +/// Get the maximum length in bytes that a Normal extrinsic on the Millau chain requires. +pub fn max_extrinsic_size() -> u32 { + *runtime_block_length().max.get(DispatchClass::Normal) +} + sp_api::decl_runtime_apis! { /// API for querying information about Rialto headers from the Bridge Pallet instance. /// diff --git a/bridges/relays/substrate-client/src/chain.rs b/bridges/relays/substrate-client/src/chain.rs index 37ce156a0e..f309c3f775 100644 --- a/bridges/relays/substrate-client/src/chain.rs +++ b/bridges/relays/substrate-client/src/chain.rs @@ -56,7 +56,7 @@ pub trait Chain: ChainBase { type Call: Dispatchable + Debug; } -/// Substrate-based chain with `frame_system::Trait::AccountData` set to +/// Substrate-based chain with `frame_system::Config::AccountData` set to /// the `pallet_balances::AccountData`. pub trait ChainWithBalances: Chain { /// Balance of an account in native tokens. diff --git a/bridges/relays/substrate/src/millau_messages_to_rialto.rs b/bridges/relays/substrate/src/millau_messages_to_rialto.rs index 736e278771..268a20beb7 100644 --- a/bridges/relays/substrate/src/millau_messages_to_rialto.rs +++ b/bridges/relays/substrate/src/millau_messages_to_rialto.rs @@ -132,9 +132,9 @@ pub fn run( max_messages_in_single_batch: bp_rialto::MAX_MESSAGES_IN_DELIVERY_TRANSACTION, // TODO: subtract base weight of delivery from this when it'll be known // https://github.com/paritytech/parity-bridges-common/issues/78 - max_messages_weight_in_single_batch: bp_rialto::MAXIMUM_EXTRINSIC_WEIGHT, + max_messages_weight_in_single_batch: bp_rialto::max_extrinsic_weight(), // 2/3 is reserved for proofs and tx overhead - max_messages_size_in_single_batch: bp_rialto::MAXIMUM_EXTRINSIC_SIZE as usize / 3, + max_messages_size_in_single_batch: bp_rialto::max_extrinsic_size() as usize / 3, }, }, MillauSourceClient::new(millau_client, lane.clone(), lane_id, RIALTO_BRIDGE_INSTANCE), diff --git a/bridges/relays/substrate/src/rialto_messages_to_millau.rs b/bridges/relays/substrate/src/rialto_messages_to_millau.rs index 2f869a122a..0615810612 100644 --- a/bridges/relays/substrate/src/rialto_messages_to_millau.rs +++ b/bridges/relays/substrate/src/rialto_messages_to_millau.rs @@ -132,9 +132,9 @@ pub fn run( max_messages_in_single_batch: bp_millau::MAX_MESSAGES_IN_DELIVERY_TRANSACTION, // TODO: subtract base weight of delivery from this when it'll be known // https://github.com/paritytech/parity-bridges-common/issues/78 - max_messages_weight_in_single_batch: bp_millau::MAXIMUM_EXTRINSIC_WEIGHT, + max_messages_weight_in_single_batch: bp_millau::max_extrinsic_weight(), // 2/3 is reserved for proofs and tx overhead - max_messages_size_in_single_batch: bp_millau::MAXIMUM_EXTRINSIC_SIZE as usize / 3, + max_messages_size_in_single_batch: bp_millau::max_extrinsic_size() as usize / 3, }, }, RialtoSourceClient::new(rialto_client, lane.clone(), lane_id, MILLAU_BRIDGE_INSTANCE),