difftreelog
feat(collator-selection) opal only
in: master
10 files changed
node/cli/src/chain_spec.rsdiffbeforeafterboth--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -24,7 +24,7 @@
use serde_json::map::Map;
use up_common::types::opaque::*;
-use up_common::constants::EXISTENTIAL_DEPOSIT;
+use up_common::constants::CANDIDACY_BOND;
#[cfg(feature = "unique-runtime")]
pub use unique_runtime as default_runtime;
@@ -151,6 +151,7 @@
AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()
}
+#[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))]
macro_rules! testnet_genesis {
(
$runtime:path,
@@ -191,7 +192,7 @@
.cloned()
.map(|(acc, _)| acc)
.collect(),
- candidacy_bond: EXISTENTIAL_DEPOSIT * 16,
+ candidacy_bond: CANDIDACY_BOND,
..Default::default()
},
session: SessionConfig {
@@ -207,9 +208,6 @@
.collect(),
},
aura: Default::default(),
- /*aura: AuraConfig {
- authorities: $initial_authorities,
- },*/
aura_ext: Default::default(),
evm: EVMConfig {
accounts: BTreeMap::new(),
@@ -219,6 +217,56 @@
}};
}
+#[cfg(any(feature = "unique-runtime", feature = "quartz-runtime"))]
+macro_rules! testnet_genesis {
+ (
+ $runtime:path,
+ $root_key:expr,
+ $initial_invulnerables:expr,
+ $endowed_accounts:expr,
+ $id:expr
+ ) => {{
+ use $runtime::*;
+
+ GenesisConfig {
+ system: SystemConfig {
+ code: WASM_BINARY
+ .expect("WASM binary was not build, please build it!")
+ .to_vec(),
+ },
+ balances: BalancesConfig {
+ balances: $endowed_accounts
+ .iter()
+ .cloned()
+ // 1e13 UNQ
+ .map(|k| (k, 1 << 100))
+ .collect(),
+ },
+ treasury: Default::default(),
+ tokens: TokensConfig { balances: vec![] },
+ sudo: SudoConfig {
+ key: Some($root_key),
+ },
+ vesting: VestingConfig { vesting: vec![] },
+ parachain_info: ParachainInfoConfig {
+ parachain_id: $id.into(),
+ },
+ parachain_system: Default::default(),
+ aura: AuraConfig {
+ authorities: $initial_invulnerables
+ .into_iter()
+ .map(|(_, aura)| aura)
+ .collect(),
+ },
+ aura_ext: Default::default(),
+ evm: EVMConfig {
+ accounts: BTreeMap::new(),
+ },
+ ethereum: EthereumConfig {},
+ }
+ }};
+}
+
pub fn development_config() -> DefaultChainSpec {
let mut properties = Map::new();
properties.insert("tokenSymbol".into(), default_runtime::TOKEN_SYMBOL.into());
primitives/common/src/constants.rsdiffbeforeafterboth--- a/primitives/common/src/constants.rs
+++ b/primitives/common/src/constants.rs
@@ -41,7 +41,10 @@
pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;
pub const UNIQUE: Balance = 100 * CENTIUNIQUE;
+/// Minimum balance required to create or keep an account open.
pub const EXISTENTIAL_DEPOSIT: u128 = 0;
+/// Amount of Balance reserved for candidate registration.
+pub const CANDIDACY_BOND: u128 = EXISTENTIAL_DEPOSIT;
// Targeting 0.1 UNQ per transfer
pub const WEIGHT_TO_FEE_COEFF: u32 = /*<weight2fee>*/207_163_598/*</weight2fee>*/;
runtime/common/config/pallets/collator_selection.rsdiffbeforeafterboth--- /dev/null
+++ b/runtime/common/config/pallets/collator_selection.rs
@@ -0,0 +1,78 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network 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.
+
+// Unique Network 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 Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+use frame_support::{parameter_types, PalletId};
+use frame_system::EnsureRoot;
+use crate::{
+ AccountId, BlockNumber, Runtime, RuntimeEvent, Balances, Aura, Session, SessionKeys,
+ CollatorSelection,
+};
+use up_common::constants::*;
+
+parameter_types! {
+ pub const SessionPeriod: BlockNumber = HOURS;
+ pub const SessionOffset: BlockNumber = 0;
+}
+
+impl pallet_session::Config for Runtime {
+ type RuntimeEvent = RuntimeEvent;
+ type ValidatorId = <Self as frame_system::Config>::AccountId;
+ // we don't have stash and controller, thus we don't need the convert as well.
+ type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
+ type ShouldEndSession = pallet_session::PeriodicSessions<SessionPeriod, SessionOffset>;
+ type NextSessionRotation = pallet_session::PeriodicSessions<SessionPeriod, SessionOffset>;
+ type SessionManager = CollatorSelection;
+ // Essentially just Aura, but lets be pedantic.
+ type SessionHandler = <SessionKeys as sp_runtime::traits::OpaqueKeys>::KeyTypeIdProviders;
+ type Keys = SessionKeys;
+ type WeightInfo = pallet_session::weights::SubstrateWeight<Self>; // ();
+}
+
+parameter_types! {
+ pub const UncleGenerations: u32 = 0;
+}
+
+impl pallet_authorship::Config for Runtime {
+ type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Aura>;
+ type UncleGenerations = UncleGenerations;
+ type FilterUncle = ();
+ type EventHandler = CollatorSelection;
+}
+
+parameter_types! {
+ pub const PotId: PalletId = PalletId(*b"PotStake");
+ pub const MaxCandidates: u32 = 1000;
+ pub const MinCandidates: u32 = 5;
+ pub const MaxInvulnerables: u32 = 100;
+}
+
+impl pallet_collator_selection::Config for Runtime {
+ type RuntimeEvent = RuntimeEvent;
+ type Currency = Balances;
+ // We allow root only to execute privileged collator selection operations.
+ type UpdateOrigin = EnsureRoot<AccountId>;
+ type PotId = PotId;
+ type MaxCandidates = MaxCandidates;
+ type MinCandidates = MinCandidates;
+ type MaxInvulnerables = MaxInvulnerables;
+ // todo:collator kick threshold should be in storage and configured only by root -- or rather UpdateOrigin
+ // Should be a multiple of session or things will get inconsistent.
+ type KickThreshold = SessionPeriod;
+ type ValidatorId = <Self as frame_system::Config>::AccountId;
+ type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
+ type ValidatorRegistration = Session;
+ type WeightInfo = ();
+}
runtime/common/config/pallets/mod.rsdiffbeforeafterboth--- a/runtime/common/config/pallets/mod.rs
+++ b/runtime/common/config/pallets/mod.rs
@@ -46,6 +46,9 @@
#[cfg(feature = "app-promotion")]
pub mod app_promotion;
+#[cfg(feature = "collator-selection")]
+pub mod collator_selection;
+
parameter_types! {
pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account_truncating();
pub const CollectionCreationPrice: Balance = 2 * UNIQUE;
runtime/common/config/substrate.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617use frame_support::{18 traits::{Everything, ConstU32, NeverEnsureOrigin},19 weights::{20 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight},21 ConstantMultiplier,22 },23 dispatch::DispatchClass,24 parameter_types, PalletId,25};26use sp_runtime::{27 generic,28 traits::{BlakeTwo256, AccountIdLookup},29 Perbill, Permill, Percent,30};31use frame_system::{32 limits::{BlockLength, BlockWeights},33 EnsureRoot,34};35use crate::{36 runtime_common::DealWithFees, Runtime, RuntimeEvent, RuntimeCall, RuntimeOrigin, PalletInfo,37 System, Balances, Treasury, SS58Prefix, Aura, Session, SessionKeys, CollatorSelection, Version,38};39use up_common::{types::*, constants::*};4041parameter_types! {42 pub const BlockHashCount: BlockNumber = 2400;43 pub RuntimeBlockLength: BlockLength =44 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);45 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);46 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;47 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()48 .base_block(BlockExecutionWeight::get())49 .for_class(DispatchClass::all(), |weights| {50 weights.base_extrinsic = ExtrinsicBaseWeight::get();51 })52 .for_class(DispatchClass::Normal, |weights| {53 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);54 })55 .for_class(DispatchClass::Operational, |weights| {56 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);57 // Operational transactions have some extra reserved space, so that they58 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.59 weights.reserved = Some(60 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT61 );62 })63 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)64 .build_or_panic();65}6667impl frame_system::Config for Runtime {68 /// The data to be stored in an account.69 type AccountData = pallet_balances::AccountData<Balance>;70 /// The identifier used to distinguish between accounts.71 type AccountId = AccountId;72 /// The basic call filter to use in dispatchable.73 type BaseCallFilter = Everything;74 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).75 type BlockHashCount = BlockHashCount;76 /// The maximum length of a block (in bytes).77 type BlockLength = RuntimeBlockLength;78 /// The index type for blocks.79 type BlockNumber = BlockNumber;80 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.81 type BlockWeights = RuntimeBlockWeights;82 /// The aggregated dispatch type that is available for extrinsics.83 type RuntimeCall = RuntimeCall;84 /// The weight of database operations that the runtime can invoke.85 type DbWeight = RocksDbWeight;86 /// The ubiquitous event type.87 type RuntimeEvent = RuntimeEvent;88 /// The type for hashing blocks and tries.89 type Hash = Hash;90 /// The hashing algorithm used.91 type Hashing = BlakeTwo256;92 /// The header type.93 type Header = generic::Header<BlockNumber, BlakeTwo256>;94 /// The index type for storing how many extrinsics an account has signed.95 type Index = Index;96 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.97 type Lookup = AccountIdLookup<AccountId, ()>;98 /// What to do if an account is fully reaped from the system.99 type OnKilledAccount = ();100 /// What to do if a new account is created.101 type OnNewAccount = ();102 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;103 /// The ubiquitous origin type.104 type RuntimeOrigin = RuntimeOrigin;105 /// This type is being generated by `construct_runtime!`.106 type PalletInfo = PalletInfo;107 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.108 type SS58Prefix = SS58Prefix;109 /// Weight information for the extrinsics of this pallet.110 type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;111 /// Version of the runtime.112 type Version = Version;113 type MaxConsumers = ConstU32<16>;114}115116impl pallet_randomness_collective_flip::Config for Runtime {}117118parameter_types! {119 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;120}121122impl pallet_timestamp::Config for Runtime {123 /// A timestamp: milliseconds since the unix epoch.124 type Moment = u64;125 type OnTimestampSet = ();126 type MinimumPeriod = MinimumPeriod;127 type WeightInfo = ();128}129130parameter_types! {131 // pub const ExistentialDeposit: u128 = 500;132 pub const ExistentialDeposit: u128 = EXISTENTIAL_DEPOSIT;133 pub const MaxLocks: u32 = 50;134 pub const MaxReserves: u32 = 50;135}136137impl pallet_balances::Config for Runtime {138 type MaxLocks = MaxLocks;139 type MaxReserves = MaxReserves;140 type ReserveIdentifier = [u8; 16];141 /// The type for recording an account's balance.142 type Balance = Balance;143 /// The ubiquitous event type.144 type RuntimeEvent = RuntimeEvent;145 type DustRemoval = Treasury;146 type ExistentialDeposit = ExistentialDeposit;147 type AccountStore = System;148 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;149}150151parameter_types! {152 /// This value increases the priority of `Operational` transactions by adding153 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.154 pub const OperationalFeeMultiplier: u8 = 5;155}156157impl pallet_transaction_payment::Config for Runtime {158 type RuntimeEvent = RuntimeEvent;159 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;160 type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;161 type OperationalFeeMultiplier = OperationalFeeMultiplier;162 type WeightToFee = pallet_configuration::WeightToFee<Self, Balance>;163 type FeeMultiplierUpdate = ();164}165166parameter_types! {167 pub const ProposalBond: Permill = Permill::from_percent(5);168 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;169 pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;170 pub const SpendPeriod: BlockNumber = 5 * MINUTES;171 pub const Burn: Permill = Permill::from_percent(0);172 pub const TipCountdown: BlockNumber = 1 * DAYS;173 pub const TipFindersFee: Percent = Percent::from_percent(20);174 pub const TipReportDepositBase: Balance = 1 * UNIQUE;175 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;176 pub const BountyDepositBase: Balance = 1 * UNIQUE;177 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;178 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");179 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;180 pub const MaximumReasonLength: u32 = 16384;181 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);182 pub const BountyValueMinimum: Balance = 5 * UNIQUE;183 pub const MaxApprovals: u32 = 100;184}185186impl pallet_treasury::Config for Runtime {187 type PalletId = TreasuryModuleId;188 type Currency = Balances;189 type ApproveOrigin = EnsureRoot<AccountId>;190 type RejectOrigin = EnsureRoot<AccountId>;191 type SpendOrigin = NeverEnsureOrigin<u128>;192 type RuntimeEvent = RuntimeEvent;193 type OnSlash = ();194 type ProposalBond = ProposalBond;195 type ProposalBondMinimum = ProposalBondMinimum;196 type ProposalBondMaximum = ProposalBondMaximum;197 type SpendPeriod = SpendPeriod;198 type Burn = Burn;199 type BurnDestination = ();200 type SpendFunds = ();201 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;202 type MaxApprovals = MaxApprovals;203}204205impl pallet_sudo::Config for Runtime {206 type RuntimeEvent = RuntimeEvent;207 type RuntimeCall = RuntimeCall;208}209210parameter_types! {211 pub const MaxAuthorities: u32 = 100_000;212}213214impl pallet_aura::Config for Runtime {215 type AuthorityId = AuraId;216 type DisabledValidators = ();217 type MaxAuthorities = MaxAuthorities;218}219220parameter_types! {221 pub const SessionPeriod: BlockNumber = HOURS;222 pub const SessionOffset: BlockNumber = 0;223}224225impl pallet_session::Config for Runtime {226 type RuntimeEvent = RuntimeEvent;227 type ValidatorId = <Self as frame_system::Config>::AccountId;228 // we don't have stash and controller, thus we don't need the convert as well.229 type ValidatorIdOf = pallet_collator_selection::IdentityCollator;230 type ShouldEndSession = pallet_session::PeriodicSessions<SessionPeriod, SessionOffset>;231 type NextSessionRotation = pallet_session::PeriodicSessions<SessionPeriod, SessionOffset>;232 type SessionManager = CollatorSelection;233 // Essentially just Aura, but lets be pedantic.234 type SessionHandler = <SessionKeys as sp_runtime::traits::OpaqueKeys>::KeyTypeIdProviders;235 type Keys = SessionKeys;236 type WeightInfo = pallet_session::weights::SubstrateWeight<Self>; // ();237}238239parameter_types! {240 pub const UncleGenerations: u32 = 0;241}242243impl pallet_authorship::Config for Runtime {244 type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Aura>;245 type UncleGenerations = UncleGenerations;246 type FilterUncle = ();247 type EventHandler = CollatorSelection;248}249250parameter_types! {251 pub const PotId: PalletId = PalletId(*b"PotStake");252 pub const MaxCandidates: u32 = 1000;253 pub const MinCandidates: u32 = 5;254 pub const MaxInvulnerables: u32 = 100;255}256257impl pallet_collator_selection::Config for Runtime {258 type RuntimeEvent = RuntimeEvent;259 type Currency = Balances;260 // We allow root only to execute privileged collator selection operations.261 type UpdateOrigin = EnsureRoot<AccountId>;262 type PotId = PotId;263 type MaxCandidates = MaxCandidates;264 type MinCandidates = MinCandidates;265 type MaxInvulnerables = MaxInvulnerables;266 // Should be a multiple of session or things will get inconsistent.267 type KickThreshold = SessionPeriod;268 type ValidatorId = <Self as frame_system::Config>::AccountId;269 type ValidatorIdOf = pallet_collator_selection::IdentityCollator;270 type ValidatorRegistration = Session;271 type WeightInfo = ();272}runtime/common/construct_runtime/mod.rsdiffbeforeafterboth--- a/runtime/common/construct_runtime/mod.rs
+++ b/runtime/common/construct_runtime/mod.rs
@@ -32,9 +32,15 @@
ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,
ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,
+ #[runtimes(opal)]
Authorship: pallet_authorship::{Pallet, Call, Storage} = 22,
+
+ #[runtimes(opal)]
CollatorSelection: pallet_collator_selection::{Pallet, Call, Storage, Event<T>, Config<T>} = 23,
+
+ #[runtimes(opal)]
Session: pallet_session::{Pallet, Call, Storage, Event, Config<T>} = 24,
+
Aura: pallet_aura::{Pallet, Config<T>} = 25,
AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 26,
runtime/common/mod.rsdiffbeforeafterboth--- a/runtime/common/mod.rs
+++ b/runtime/common/mod.rs
@@ -180,154 +180,166 @@
pub struct AuraToCollatorSelection;
impl frame_support::traits::OnRuntimeUpgrade for AuraToCollatorSelection {
fn on_runtime_upgrade() -> Weight {
- use frame_support::{BoundedVec, storage::migration};
- use sp_runtime::{
- traits::{OpaqueKeys, Saturating},
- RuntimeAppPublic,
- };
- use pallet_session::SessionManager;
- use up_common::constants::EXISTENTIAL_DEPOSIT;
- use crate::config::substrate::MaxInvulnerables;
-
- let mut weight = <Runtime as frame_system::Config>::DbWeight::get().reads(1);
+ #[cfg(feature = "collator-selection")]
+ {
+ use frame_support::{BoundedVec, storage::migration};
+ use sp_runtime::{
+ traits::{OpaqueKeys, Saturating},
+ RuntimeAppPublic,
+ };
+ use pallet_session::SessionManager;
+ use up_common::constants::CANDIDACY_BOND;
+ use crate::config::pallets::collator_selection::MaxInvulnerables;
- let version =
- migration::get_storage_value::<()>(b"AuraToCollatorSelection", b"StorageVersion", &[]);
-
- let should_upgrade = match version {
- None => true,
- Some(_) => false,
- };
+ let mut weight = <Runtime as frame_system::Config>::DbWeight::get().reads(1);
- if should_upgrade {
- log::info!(
- target: "runtime::aura_to_collator_selection",
- "Running migration of Aura authorities to Collator Selection invulnerables"
+ let version = migration::get_storage_value::<()>(
+ b"AuraToCollatorSelection",
+ b"StorageVersion",
+ &[],
);
- let invulnerables = pallet_aura::Pallet::<Runtime>::authorities()
- .iter()
- .cloned()
- .filter_map(|authority_id| {
- weight.saturating_accrue(<Runtime as frame_system::Config>::DbWeight::get().reads_writes(1, 1));
- let vec = authority_id.clone().to_raw_vec();
- let slice = vec.as_slice();
- let array: Option<[u8; 32]> = match slice.try_into() {
- Ok(a) => Some(a),
- Err(_) => {
- log::error!("Failed to convert an Aura authority to a Collator Selection invulnerable: {:?}", authority_id);
- None
- },
- };
- array.map(|a| (AccountId::from(a), authority_id))
- })
- .collect::<Vec<_>>();
+ let should_upgrade = match version {
+ None => true,
+ Some(_) => false,
+ };
+
+ if should_upgrade {
+ log::info!(
+ target: "runtime::aura_to_collator_selection",
+ "Running migration of Aura authorities to Collator Selection invulnerables"
+ );
- let bounded_invulnerables = BoundedVec::<_, MaxInvulnerables>::try_from(
- invulnerables
+ let invulnerables = pallet_aura::Pallet::<Runtime>::authorities()
.iter()
.cloned()
- .map(|(acc, _)| acc)
- .collect::<Vec<_>>(),
- )
- .expect("Existing collators/invulnerables are more than MaxInvulnerables");
+ .filter_map(|authority_id| {
+ weight.saturating_accrue(<Runtime as frame_system::Config>::DbWeight::get().reads_writes(1, 1));
+ let vec = authority_id.clone().to_raw_vec();
+ let slice = vec.as_slice();
+ let array: Option<[u8; 32]> = match slice.try_into() {
+ Ok(a) => Some(a),
+ Err(_) => {
+ log::error!("Failed to convert an Aura authority to a Collator Selection invulnerable: {:?}", authority_id);
+ None
+ },
+ };
+ array.map(|a| (AccountId::from(a), authority_id))
+ })
+ .collect::<Vec<_>>();
- <pallet_collator_selection::Invulnerables<Runtime>>::put(bounded_invulnerables);
- <pallet_collator_selection::DesiredCandidates<Runtime>>::put(0);
- <pallet_collator_selection::CandidacyBond<Runtime>>::put(EXISTENTIAL_DEPOSIT * 16);
+ let bounded_invulnerables = BoundedVec::<_, MaxInvulnerables>::try_from(
+ invulnerables
+ .iter()
+ .cloned()
+ .map(|(acc, _)| acc)
+ .collect::<Vec<_>>(),
+ )
+ .expect("Existing collators/invulnerables are more than MaxInvulnerables");
+
+ <pallet_collator_selection::Invulnerables<Runtime>>::put(bounded_invulnerables);
+ <pallet_collator_selection::DesiredCandidates<Runtime>>::put(0);
+ <pallet_collator_selection::CandidacyBond<Runtime>>::put(CANDIDACY_BOND);
- let keys = invulnerables
- .into_iter()
- .map(|(acc, aura)| {
- (
- acc.clone(), // account id
- acc, // validator id
- SessionKeys { aura: aura.clone() }, // session keys
- )
- })
- .collect::<Vec<_>>();
+ let keys = invulnerables
+ .into_iter()
+ .map(|(acc, aura)| {
+ (
+ acc.clone(), // account id
+ acc, // validator id
+ SessionKeys { aura: aura.clone() }, // session keys
+ )
+ })
+ .collect::<Vec<_>>();
- for (account, val, keys) in keys.iter().cloned() {
- for id in <Runtime as pallet_session::Config>::Keys::key_ids() {
- <pallet_session::KeyOwner<Runtime>>::insert((*id, keys.get_raw(*id)), &val)
- }
- <pallet_session::NextKeys<Runtime>>::insert(&val, &keys);
- // todo exercise caution, the following is taken from genesis
- if frame_system::Pallet::<Runtime>::inc_consumers_without_limit(&account).is_err() {
- log::warn!(
- "We have entered an error with incrementing consumers without limit during the migration"
- );
- // This will leak a provider reference, however it only happens once (at
- // genesis) so it's really not a big deal and we assume that the user wants to
- // do this since it's the only way a non-endowed account can contain a session
- // key.
- frame_system::Pallet::<Runtime>::inc_providers(&account);
+ for (account, val, keys) in keys.iter().cloned() {
+ for id in <Runtime as pallet_session::Config>::Keys::key_ids() {
+ <pallet_session::KeyOwner<Runtime>>::insert((*id, keys.get_raw(*id)), &val)
+ }
+ <pallet_session::NextKeys<Runtime>>::insert(&val, &keys);
+ // todo exercise caution, the following is taken from genesis
+ if frame_system::Pallet::<Runtime>::inc_consumers_without_limit(&account)
+ .is_err()
+ {
+ log::warn!(
+ "We have entered an error with incrementing consumers without limit during the migration"
+ );
+ // This will leak a provider reference, however it only happens once (at
+ // genesis) so it's really not a big deal and we assume that the user wants to
+ // do this since it's the only way a non-endowed account can contain a session
+ // key.
+ frame_system::Pallet::<Runtime>::inc_providers(&account);
+ }
}
- }
- let initial_validators_0 =
- <Runtime as pallet_session::Config>::SessionManager::new_session(0).unwrap_or_else(
- || {
- frame_support::print(
- "No initial validator provided by `SessionManager`, use \
- session config keys to generate initial validator set.",
- );
- keys.iter().map(|x| x.1.clone()).collect()
- },
- );
- /*assert!(
- !initial_validators_0.is_empty(),
- "Empty validator set for session 0 in (pseudo) genesis block!"
- );*/
+ let initial_validators_0 =
+ <Runtime as pallet_session::Config>::SessionManager::new_session(0)
+ .unwrap_or_else(|| {
+ frame_support::print(
+ "No initial validator provided by `SessionManager`, use \
+ session config keys to generate initial validator set.",
+ );
+ keys.iter().map(|x| x.1.clone()).collect()
+ });
+ /*assert!(
+ !initial_validators_0.is_empty(),
+ "Empty validator set for session 0 in (pseudo) genesis block!"
+ );*/
- let initial_validators_1 =
- <Runtime as pallet_session::Config>::SessionManager::new_session(1)
- .unwrap_or_else(|| initial_validators_0.clone());
- /*assert!(
- !initial_validators_1.is_empty(),
- "Empty validator set for session 1 in (pseudo) genesis block!"
- );*/
+ let initial_validators_1 =
+ <Runtime as pallet_session::Config>::SessionManager::new_session(1)
+ .unwrap_or_else(|| initial_validators_0.clone());
+ /*assert!(
+ !initial_validators_1.is_empty(),
+ "Empty validator set for session 1 in (pseudo) genesis block!"
+ );*/
- let queued_keys: Vec<_> = initial_validators_1
- .iter()
- .cloned()
- .map(|v| {
- (
- v.clone(),
- <pallet_session::NextKeys<Runtime>>::get(&v)
- .expect("Validator in session 1 missing keys!"),
- )
- })
- .collect();
+ let queued_keys: Vec<_> = initial_validators_1
+ .iter()
+ .cloned()
+ .map(|v| {
+ (
+ v.clone(),
+ <pallet_session::NextKeys<Runtime>>::get(&v)
+ .expect("Validator in session 1 missing keys!"),
+ )
+ })
+ .collect();
- // Tell everyone about the genesis session keys -- Aura must've already initialized it
- //<Runtime as pallet_session::Config>::SessionHandler::on_genesis_session::<<Runtime as pallet_session::Config>::Keys>(&queued_keys);
+ // Tell everyone about the genesis session keys -- Aura must've already initialized it
+ //<Runtime as pallet_session::Config>::SessionHandler::on_genesis_session::<<Runtime as pallet_session::Config>::Keys>(&queued_keys);
+
+ <pallet_session::Validators<Runtime>>::put(initial_validators_0);
+ <pallet_session::QueuedKeys<Runtime>>::put(queued_keys);
- <pallet_session::Validators<Runtime>>::put(initial_validators_0);
- <pallet_session::QueuedKeys<Runtime>>::put(queued_keys);
+ <Runtime as pallet_session::Config>::SessionManager::start_session(0);
- <Runtime as pallet_session::Config>::SessionManager::start_session(0);
+ log::info!(
+ target: "runtime::aura_to_collator_selection",
+ "Migration of Aura authorities to Collator Selection invulnerables is complete."
+ );
- log::info!(
- target: "runtime::aura_to_collator_selection",
- "Migration of Aura authorities to Collator Selection invulnerables is complete."
- );
+ migration::put_storage_value::<()>(
+ b"AuraToCollatorSelection",
+ b"StorageVersion",
+ &[],
+ (),
+ );
- migration::put_storage_value::<()>(
- b"AuraToCollatorSelection",
- b"StorageVersion",
- &[],
- (),
- );
+ weight += <Runtime as frame_system::Config>::DbWeight::get().writes(1)
+ } else {
+ log::info!(
+ target: "runtime::aura_to_collator_selection",
+ "The storage migration has already been flagged as complete. No migration needs to be done.",
+ );
+ }
- weight += <Runtime as frame_system::Config>::DbWeight::get().writes(1)
- } else {
- log::info!(
- target: "runtime::aura_to_collator_selection",
- "The storage migration has already been flagged as complete. No migration needs to be done.",
- );
+ weight
}
- weight
+ #[cfg(not(feature = "collator-selection"))]
+ {
+ Weight::zero()
+ }
}
}
runtime/opal/Cargo.tomldiffbeforeafterboth--- a/runtime/opal/Cargo.toml
+++ b/runtime/opal/Cargo.toml
@@ -173,13 +173,14 @@
"pallet-foreign-assets/std",
]
limit-testing = ['pallet-unique/limit-testing', 'up-data-structs/limit-testing']
-opal-runtime = ['refungible', 'rmrk', 'app-promotion', 'foreign-assets']
+opal-runtime = ['refungible', 'rmrk', 'app-promotion', 'foreign-assets', 'collator-selection']
refungible = []
scheduler = []
rmrk = []
foreign-assets = []
app-promotion = []
+collator-selection = []
################################################################################
# Substrate Dependencies
runtime/quartz/Cargo.tomldiffbeforeafterboth--- a/runtime/quartz/Cargo.toml
+++ b/runtime/quartz/Cargo.toml
@@ -177,6 +177,7 @@
scheduler = []
rmrk = []
foreign-assets = []
+collator-selection = []
################################################################################
# Substrate Dependencies
runtime/unique/Cargo.tomldiffbeforeafterboth--- a/runtime/unique/Cargo.toml
+++ b/runtime/unique/Cargo.toml
@@ -178,6 +178,7 @@
scheduler = []
rmrk = []
foreign-assets = []
+collator-selection = []
################################################################################
# Substrate Dependencies