12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879#![cfg_attr(not(feature = "std"), no_std)]8081pub use pallet::*;8283#[cfg(test)]84mod mock;8586#[cfg(test)]87mod tests;8889#[cfg(feature = "runtime-benchmarks")]90mod benchmarking;91pub mod weights;9293#[frame_support::pallet]94pub mod pallet {95 pub use crate::weights::WeightInfo;96 use core::ops::Div;97 use frame_support::{98 dispatch::{DispatchClass, DispatchResultWithPostInfo},99 inherent::Vec,100 pallet_prelude::*,101 sp_runtime::traits::{AccountIdConversion, CheckedSub, Saturating, Zero},102 traits::{103 Currency, EnsureOrigin, ExistenceRequirement::KeepAlive, ReservableCurrency,104 ValidatorRegistration,105 },106 BoundedVec, PalletId,107 };108 use frame_system::{pallet_prelude::*, Config as SystemConfig};109 use pallet_session::SessionManager;110 use sp_runtime::{111 Perbill,112 traits::{One, Convert},113 };114 use sp_staking::SessionIndex;115116 type BalanceOf<T> =117 <<T as Config>::Currency as Currency<<T as SystemConfig>::AccountId>>::Balance;118119 120 121 pub struct IdentityCollator;122 impl<T> sp_runtime::traits::Convert<T, Option<T>> for IdentityCollator {123 fn convert(t: T) -> Option<T> {124 Some(t)125 }126 }127128 129 #[pallet::config]130 pub trait Config: frame_system::Config {131 132 type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;133134 135 type Currency: ReservableCurrency<Self::AccountId>;136137 138 type UpdateOrigin: EnsureOrigin<Self::RuntimeOrigin>;139140 141 type TreasuryAccountId: Get<Self::AccountId>;142143 144 type PotId: Get<PalletId>;145146 147 type MaxCollators: Get<u32>;148149 150 type SlashRatio: Get<Perbill>;151152 153 type ValidatorId: Member + Parameter;154155 156 157 158 type ValidatorIdOf: Convert<Self::AccountId, Option<Self::ValidatorId>>;159160 161 type ValidatorRegistration: ValidatorRegistration<Self::ValidatorId>;162163 164 type WeightInfo: WeightInfo;165 }166167 #[pallet::pallet]168 #[pallet::generate_store(pub(super) trait Store)]169 pub struct Pallet<T>(_);170171 172 #[pallet::storage]173 #[pallet::getter(fn invulnerables)]174 pub type Invulnerables<T: Config> =175 StorageValue<_, BoundedVec<T::AccountId, T::MaxCollators>, ValueQuery>;176177 178 #[pallet::storage]179 #[pallet::getter(fn licenses)]180 pub type Licenses<T: Config> =181 StorageMap<_, Blake2_128Concat, T::AccountId, BalanceOf<T>, ValueQuery>;182183 184 #[pallet::storage]185 #[pallet::getter(fn candidates)]186 pub type Candidates<T: Config> = StorageValue<187 _,188 BoundedVec<T::AccountId, T::MaxCollators>, 189 ValueQuery,190 >;191192 193 194 195 #[pallet::storage]196 #[pallet::getter(fn kick_threshold)]197 pub type KickThreshold<T: Config> = StorageValue<_, T::BlockNumber, ValueQuery>;198199 200 #[pallet::storage]201 #[pallet::getter(fn last_authored_block)]202 pub type LastAuthoredBlock<T: Config> =203 StorageMap<_, Twox64Concat, T::AccountId, T::BlockNumber, ValueQuery>;204205 206 207 208 #[pallet::storage]209 #[pallet::getter(fn desired_collators)]210 pub type DesiredCollators<T> = StorageValue<_, u32, ValueQuery>;211212 213 214 215 #[pallet::storage]216 #[pallet::getter(fn license_bond)]217 pub type LicenseBond<T> = StorageValue<_, BalanceOf<T>, ValueQuery>;218219 #[pallet::genesis_config]220 pub struct GenesisConfig<T: Config> {221 pub invulnerables: Vec<T::AccountId>,222 pub license_bond: BalanceOf<T>,223 pub kick_threshold: T::BlockNumber,224 pub desired_collators: u32,225 }226227 #[cfg(feature = "std")]228 impl<T: Config> Default for GenesisConfig<T> {229 fn default() -> Self {230 Self {231 invulnerables: Default::default(),232 license_bond: Default::default(),233 kick_threshold: T::BlockNumber::one(),234 desired_collators: Default::default(),235 }236 }237 }238239 #[pallet::genesis_build]240 impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {241 fn build(&self) {242 let duplicate_invulnerables = self243 .invulnerables244 .iter()245 .collect::<std::collections::BTreeSet<_>>();246 assert!(247 duplicate_invulnerables.len() == self.invulnerables.len(),248 "duplicate invulnerables in genesis."249 );250251 let bounded_invulnerables =252 BoundedVec::<_, T::MaxCollators>::try_from(self.invulnerables.clone())253 .expect("genesis invulnerables are more than T::MaxCollators");254 assert!(255 T::MaxCollators::get() >= self.desired_collators,256 "genesis desired_collators are more than T::MaxCollators",257 );258259 <DesiredCollators<T>>::put(self.desired_collators);260 <LicenseBond<T>>::put(self.license_bond);261 <KickThreshold<T>>::put(self.kick_threshold);262 <Invulnerables<T>>::put(bounded_invulnerables);263 }264 }265266 #[pallet::event]267 #[pallet::generate_deposit(pub(super) fn deposit_event)]268 pub enum Event<T: Config> {269 NewDesiredCollators {270 desired_collators: u32,271 },272 NewLicenseBond {273 bond_amount: BalanceOf<T>,274 },275 NewKickThreshold {276 length_in_blocks: T::BlockNumber,277 },278 InvulnerableAdded {279 invulnerable: T::AccountId,280 },281 InvulnerableRemoved {282 invulnerable: T::AccountId,283 },284 LicenseObtained {285 account_id: T::AccountId,286 deposit: BalanceOf<T>,287 },288 LicenseForfeited {289 account_id: T::AccountId,290 deposit_returned: BalanceOf<T>,291 },292 CandidateAdded {293 account_id: T::AccountId,294 },295 CandidateRemoved {296 account_id: T::AccountId,297 },298 }299300 301 #[pallet::error]302 pub enum Error<T> {303 304 TooManyCandidates,305 306 Unknown,307 308 Permission,309 310 AlreadyHoldingLicense,311 312 NoLicense,313 314 AlreadyCandidate,315 316 NotCandidate,317 318 TooManyInvulnerables,319 320 TooFewInvulnerables,321 322 AlreadyInvulnerable,323 324 NotInvulnerable,325 326 NoAssociatedValidatorId,327 328 ValidatorNotRegistered,329 }330331 #[pallet::hooks]332 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}333334 #[pallet::call]335 impl<T: Config> Pallet<T> {336 337 #[pallet::weight(T::WeightInfo::set_invulnerables(1u32))] 338 pub fn add_invulnerable(339 origin: OriginFor<T>,340 new: T::AccountId,341 ) -> DispatchResultWithPostInfo {342 T::UpdateOrigin::ensure_origin(origin)?;343344 345 let validator_key = T::ValidatorIdOf::convert(new.clone())346 .ok_or(Error::<T>::NoAssociatedValidatorId)?;347 ensure!(348 T::ValidatorRegistration::is_registered(&validator_key),349 Error::<T>::ValidatorNotRegistered350 );351 352 if Self::invulnerables().contains(&new) {353 return Ok(().into());354 }355356 <Invulnerables<T>>::try_append(new.clone())357 .map_err(|_| Error::<T>::TooManyInvulnerables)?;358359 360 let _ = Self::try_remove_candidate(&new);361362 Self::deposit_event(Event::InvulnerableAdded { invulnerable: new });363 Ok(().into())364 }365366 367 #[pallet::weight(T::WeightInfo::set_invulnerables(1))] 368 pub fn remove_invulnerable(369 origin: OriginFor<T>,370 who: T::AccountId,371 ) -> DispatchResultWithPostInfo {372 T::UpdateOrigin::ensure_origin(origin)?;373374 375 <Invulnerables<T>>::try_mutate(|invulnerables| -> DispatchResult {376 if invulnerables.len() <= 1 {377 return Err(Error::<T>::TooFewInvulnerables.into());378 }379380 let index = invulnerables381 .into_iter()382 .position(|r| *r == who)383 .ok_or(Error::<T>::NotInvulnerable)?;384 invulnerables.remove(index);385 Ok(())386 })?;387 388389390391 Self::deposit_event(Event::InvulnerableRemoved { invulnerable: who });392 Ok(().into())393 }394395 396 397 398 #[pallet::weight(T::WeightInfo::set_desired_collators())]399 pub fn set_desired_collators(origin: OriginFor<T>, max: u32) -> DispatchResultWithPostInfo {400 T::UpdateOrigin::ensure_origin(origin)?;401 402 if max > T::MaxCollators::get() {403 log::warn!("max > T::MaxCollators; you might need to run benchmarks again");404 }405 <DesiredCollators<T>>::put(max);406 Self::deposit_event(Event::NewDesiredCollators {407 desired_collators: max,408 });409 Ok(().into())410 }411412 413 #[pallet::weight(T::WeightInfo::set_license_bond())]414 pub fn set_license_bond(415 origin: OriginFor<T>,416 bond: BalanceOf<T>,417 ) -> DispatchResultWithPostInfo {418 T::UpdateOrigin::ensure_origin(origin)?;419 <LicenseBond<T>>::put(bond);420 Self::deposit_event(Event::NewLicenseBond { bond_amount: bond });421 Ok(().into())422 }423424 425 426 #[pallet::weight(T::WeightInfo::set_license_bond())] 427 pub fn set_kick_threshold(428 origin: OriginFor<T>,429 kick_threshold: T::BlockNumber,430 ) -> DispatchResultWithPostInfo {431 T::UpdateOrigin::ensure_origin(origin)?;432 433 <KickThreshold<T>>::put(kick_threshold);434 Self::deposit_event(Event::NewKickThreshold {435 length_in_blocks: kick_threshold,436 });437 Ok(().into())438 }439440 441 442 443 444 445 #[pallet::weight(T::WeightInfo::register_as_candidate(T::MaxCollators::get()))] 446 pub fn get_license(origin: OriginFor<T>) -> DispatchResultWithPostInfo {447 448 let who = ensure_signed(origin)?;449450 if Licenses::<T>::contains_key(&who) {451 return Err(Error::<T>::AlreadyHoldingLicense.into());452 }453454 455456457458459 let validator_key = T::ValidatorIdOf::convert(who.clone())460 .ok_or(Error::<T>::NoAssociatedValidatorId)?;461 ensure!(462 T::ValidatorRegistration::is_registered(&validator_key),463 Error::<T>::ValidatorNotRegistered464 );465466 let deposit = Self::license_bond();467 468 469470471472473 T::Currency::reserve(&who, deposit)?;474 Licenses::<T>::insert(who.clone(), deposit);475476 477478479480481482483484485486487488489490491492493494495496 Self::deposit_event(Event::LicenseObtained {497 account_id: who,498 deposit,499 });500 Ok(().into()) 501 }502503 504 505 506 507 #[pallet::weight(T::WeightInfo::register_as_candidate(T::MaxCollators::get()))] 508 pub fn onboard(origin: OriginFor<T>) -> DispatchResultWithPostInfo {509 510 let who = ensure_signed(origin)?;511512 513 ensure!(Licenses::<T>::contains_key(&who), Error::<T>::NoLicense);514 515 let length = <Candidates<T>>::decode_len().unwrap_or_default()516 + <Invulnerables<T>>::decode_len().unwrap_or_default();517 ensure!(518 (length as u32) < Self::desired_collators(),519 Error::<T>::TooManyCandidates520 );521 522 ensure!(523 !Self::invulnerables().contains(&who),524 Error::<T>::AlreadyInvulnerable525 );526527 528529530531532 let current_count =533 <Candidates<T>>::try_mutate(|candidates| -> Result<usize, DispatchError> {534 if candidates.iter().any(|candidate| *candidate == who) {535 Err(Error::<T>::AlreadyCandidate)?536 } else {537 candidates538 .try_push(who.clone())539 .map_err(|_| Error::<T>::TooManyCandidates)?;540 541 <LastAuthoredBlock<T>>::insert(542 who.clone(),543 frame_system::Pallet::<T>::block_number() + Self::kick_threshold(),544 );545 Ok(candidates.len())546 }547 })?;548549 Self::deposit_event(Event::CandidateAdded { account_id: who });550 Ok(Some(T::WeightInfo::register_as_candidate(current_count as u32)).into())551 }552553 554 555 556 557 #[pallet::weight(T::WeightInfo::leave_intent(T::MaxCollators::get()))] 558 pub fn offboard(origin: OriginFor<T>) -> DispatchResultWithPostInfo {559 560 let who = ensure_signed(origin)?;561 562563564565566 let current_count = Self::try_remove_candidate(&who)?;567568 Ok(Some(T::WeightInfo::leave_intent(current_count as u32)).into()) 569 }570571 572 573 574 #[pallet::weight(T::WeightInfo::leave_intent(T::MaxCollators::get()))] 575 pub fn release_license(origin: OriginFor<T>) -> DispatchResultWithPostInfo {576 577 let who = ensure_signed(origin)?;578579 let current_count = Self::try_remove_candidate_and_release_license(&who, false, true)?;580581 Ok(Some(T::WeightInfo::leave_intent(current_count as u32)).into()) 582 }583584 585 586 587 588 589 #[pallet::weight(T::WeightInfo::leave_intent(T::MaxCollators::get()))] 590 pub fn force_revoke_license(591 origin: OriginFor<T>,592 who: T::AccountId,593 ) -> DispatchResultWithPostInfo {594 595 T::UpdateOrigin::ensure_origin(origin)?;596597 let current_count = Self::try_remove_candidate_and_release_license(&who, false, true)?;598599 Ok(Some(T::WeightInfo::leave_intent(current_count as u32)).into()) 600 }601 }602603 impl<T: Config> Pallet<T> {604 605 pub fn account_id() -> T::AccountId {606 T::PotId::get().into_account_truncating()607 }608609 fn try_remove_candidate_and_release_license(610 who: &T::AccountId,611 should_slash: bool,612 ignore_if_not_candidate: bool,613 ) -> Result<usize, DispatchError> {614 let current_count = Self::try_remove_candidate(who);615 let current_count = if ignore_if_not_candidate616 && current_count == Err(Error::<T>::NotCandidate.into())617 {618 <Candidates<T>>::decode_len().unwrap_or_default()619 } else {620 current_count?621 };622 Self::try_release_license(who, should_slash)?;623 Ok(current_count)624 }625626 627 fn try_remove_candidate(who: &T::AccountId) -> Result<usize, DispatchError> {628 let current_count =629 <Candidates<T>>::try_mutate(|candidates| -> Result<usize, DispatchError> {630 let index = candidates631 .iter()632 .position(|candidate| *candidate == *who)633 .ok_or(Error::<T>::NotCandidate)?;634 candidates.remove(index);635 <LastAuthoredBlock<T>>::remove(who.clone());636 Ok(candidates.len())637 })?;638 Self::deposit_event(Event::CandidateRemoved {639 account_id: who.clone(),640 });641 Ok(current_count)642 }643644 645 fn try_release_license(who: &T::AccountId, should_slash: bool) -> DispatchResult {646 let mut deposit_returned = BalanceOf::<T>::default();647 Licenses::<T>::try_mutate_exists(who, |deposit| -> DispatchResult {648 if let Some(deposit) = deposit.take() {649 if should_slash {650 let slashed = T::SlashRatio::get() * deposit;651 let remaining = deposit - slashed;652653 let (imbalance, _) = T::Currency::slash_reserved(who, slashed);654 655 deposit_returned = remaining;656657 T::Currency::resolve_creating(&T::TreasuryAccountId::get(), imbalance);658 } else {659 660 deposit_returned = deposit;661 }662663 T::Currency::unreserve(who, deposit_returned);664 Ok(())665 } else {666 Err(Error::<T>::NoLicense.into())667 }668 })?;669 Self::deposit_event(Event::LicenseForfeited {670 account_id: who.clone(),671 deposit_returned,672 });673 Ok(())674 }675676 677 678 679 pub fn assemble_collators(680 candidates: BoundedVec<T::AccountId, T::MaxCollators>,681 ) -> Vec<T::AccountId> {682 let mut collators = Self::invulnerables().to_vec();683 collators.extend(candidates);684 collators685 }686687 688 689 pub fn kick_stale_candidates(690 candidates: BoundedVec<T::AccountId, T::MaxCollators>, 691 ) -> BoundedVec<T::AccountId, T::MaxCollators> {692 let now = frame_system::Pallet::<T>::block_number();693 let kick_threshold = Self::kick_threshold();694 candidates695 .into_iter()696 .filter_map(|c| {697 let last_block = <LastAuthoredBlock<T>>::get(c.clone());698 let since_last = now.saturating_sub(last_block);699 if since_last < kick_threshold {700 Some(c)701 } else {702 let outcome = Self::try_remove_candidate_and_release_license(&c, true, false);703 if let Err(why) = outcome {704 log::warn!("Failed to kick collator and release license {:?}", why);705 debug_assert!(false, "failed to kick collator and release license {why:?}");706 }707 None708 }709 })710 .collect::<Vec<_>>()711 .try_into()712 .expect("filter_map operation can't result in a bounded vec larger than its original; qed")713 }714 }715716 717 718 impl<T: Config + pallet_authorship::Config>719 pallet_authorship::EventHandler<T::AccountId, T::BlockNumber> for Pallet<T>720 {721 fn note_author(author: T::AccountId) {722 let pot = Self::account_id();723 724 let reward = T::Currency::free_balance(&pot)725 .checked_sub(&T::Currency::minimum_balance())726 .unwrap_or_else(Zero::zero)727 .div(2u32.into());728 729 let _success = T::Currency::transfer(&pot, &author, reward, KeepAlive);730 debug_assert!(_success.is_ok());731 <LastAuthoredBlock<T>>::insert(author, frame_system::Pallet::<T>::block_number());732733 frame_system::Pallet::<T>::register_extra_weight_unchecked(734 T::WeightInfo::note_author(),735 DispatchClass::Mandatory,736 );737 }738739 fn note_uncle(_author: T::AccountId, _age: T::BlockNumber) {740 741 }742 }743744 745 impl<T: Config> SessionManager<T::AccountId> for Pallet<T> {746 fn new_session(index: SessionIndex) -> Option<Vec<T::AccountId>> {747 log::info!(748 "assembling new collators for new session {} at #{:?}",749 index,750 <frame_system::Pallet<T>>::block_number(),751 );752753 let candidates = Self::candidates();754 let candidates_len_before = candidates.len();755 let active_candidates = Self::kick_stale_candidates(candidates);756 let removed = candidates_len_before - active_candidates.len();757 let result = Self::assemble_collators(active_candidates);758759 frame_system::Pallet::<T>::register_extra_weight_unchecked(760 T::WeightInfo::new_session(candidates_len_before as u32, removed as u32),761 DispatchClass::Mandatory,762 );763 Some(result)764 }765 fn start_session(_: SessionIndex) {766 767 }768 fn end_session(_: SessionIndex) {769 770 }771 }772}