git.delta.rocks / unique-network / refs/commits / cbfc871bee98

difftreelog

feat(collator-selection) benchmarks for collator-selection and data-management + cargo fmt

Fahrrader2022-12-27parent: #9206f91.patch.diff
in: master

21 files changed

modifiedMakefilediffbeforeafterboth
--- a/Makefile
+++ b/Makefile
@@ -127,16 +127,16 @@
 
 .PHONY: bench-foreign-assets
 bench-foreign-assets:
-	make _bench PALLET=foreign-assets	
+	make _bench PALLET=foreign-assets
+
+.PHONY: bench-collator-selection
+bench-collator-selection:
+	make _bench PALLET=collator-selection
 
 .PHONY: bench-app-promotion
 bench-app-promotion:
 	make _bench PALLET=app-promotion PALLET_DIR=app-promotion
 	
 .PHONY: bench
-<<<<<<< HEAD
-bench: bench-data-management bench-unique bench-structure bench-fungible bench-refungible bench-nonfungible bench-scheduler bench-rmrk-core bench-rmrk-equip bench-foreign-assets
-=======
 # Disabled: bench-scheduler, bench-rmrk-core, bench-rmrk-equip
-bench: bench-evm-migration bench-unique bench-structure bench-fungible bench-refungible bench-nonfungible bench-foreign-assets
->>>>>>> develop
+bench: bench-data-management bench-unique bench-structure bench-fungible bench-refungible bench-nonfungible bench-foreign-assets
modifiedpallets/collator-selection/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/collator-selection/src/benchmarking.rs
+++ b/pallets/collator-selection/src/benchmarking.rs
@@ -45,10 +45,15 @@
 use frame_system::{EventRecord, RawOrigin};
 use pallet_authorship::EventHandler;
 use pallet_session::{self as session, SessionManager};
+use pallet_configuration::{
+	self as configuration, BalanceOf,
+	CollatorSelectionDesiredCollatorsOverride as DesiredCollators,
+	CollatorSelectionLicenseBondOverride as LicenseBond,
+};
 use sp_std::prelude::*;
 
-pub type BalanceOf<T> =
-	<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
+/*pub type BalanceOf<T> =
+<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;*/
 
 const SEED: u32 = 0;
 
@@ -111,7 +116,7 @@
 	validators.into_iter().map(|(who, _)| who).collect()
 }
 
-fn register_candidates<T: Config>(count: u32) {
+fn register_candidates<T: Config + configuration::Config>(count: u32) {
 	let candidates = (0..count)
 		.map(|c| account("candidate", c, SEED))
 		.collect::<Vec<_>>();
@@ -122,27 +127,44 @@
 
 	for who in candidates {
 		T::Currency::make_free_balance_be(&who, <LicenseBond<T>>::get() * 2u32.into());
-		<CollatorSelection<T>>::register_as_candidate(RawOrigin::Signed(who).into()).unwrap();
+		<CollatorSelection<T>>::get_license(RawOrigin::Signed(who.clone()).into()).unwrap();
+		<CollatorSelection<T>>::onboard(RawOrigin::Signed(who).into()).unwrap();
 	}
 }
 
 benchmarks! {
-	where_clause { where T: pallet_authorship::Config + session::Config }
+	where_clause { where T: pallet_authorship::Config + session::Config + configuration::Config }
+
+	add_invulnerable {
+		let b in 1 .. T::MaxCollators::get();
+		let new_invulnerable = register_validators::<T>(b)[0].clone();
+		let origin = T::UpdateOrigin::successful_origin();
+	}: {
+		assert_ok!(
+			<CollatorSelection<T>>::add_invulnerable(origin, new_invulnerable.clone())
+		);
+	}
+	verify {
+		assert_last_event::<T>(Event::InvulnerableAdded{invulnerable: new_invulnerable}.into());
+	}
 
-	set_invulnerables {
+	remove_invulnerable {
 		let b in 1 .. T::MaxCollators::get();
-		let new_invulnerables = register_validators::<T>(b);
+		let new_invulnerable = register_validators::<T>(b)[0].clone();
 		let origin = T::UpdateOrigin::successful_origin();
+		assert_ok!(
+			<CollatorSelection<T>>::add_invulnerable(origin.clone(), new_invulnerable.clone())
+		);
 	}: {
 		assert_ok!(
-			<CollatorSelection<T>>::set_invulnerables(origin, new_invulnerables.clone())
+			<CollatorSelection<T>>::remove_invulnerable(origin, new_invulnerable.clone())
 		);
 	}
 	verify {
-		assert_last_event::<T>(Event::NewInvulnerables{invulnerables: new_invulnerables}.into());
+		assert_last_event::<T>(Event::InvulnerableRemoved{invulnerable: new_invulnerable}.into());
 	}
 
-	set_desired_collators {
+	/*set_desired_collators {
 		let max: u32 = 999;
 		let origin = T::UpdateOrigin::successful_origin();
 	}: {
@@ -164,11 +186,9 @@
 	}
 	verify {
 		assert_last_event::<T>(Event::NewLicenseBond{bond_amount}.into());
-	}
+	}*/
 
-	// worse case is when we have all the max-candidate slots filled except one, and we fill that
-	// one.
-	register_as_candidate {
+	get_license {
 		let c in 1 .. T::MaxCollators::get();
 
 		<LicenseBond<T>>::put(T::Currency::minimum_balance());
@@ -189,27 +209,96 @@
 
 	}: _(RawOrigin::Signed(caller.clone()))
 	verify {
-		assert_last_event::<T>(Event::CandidateAdded{account_id: caller, deposit: bond / 2u32.into()}.into());
+		assert_last_event::<T>(Event::LicenseObtained{account_id: caller, deposit: bond / 2u32.into()}.into());
 	}
 
-	// worse case is the last candidate leaving.
-	leave_intent {
-		let c in (T::MinCandidates::get() + 1) .. T::MaxCollators::get();
+	// worst case is when we have all the max-candidate slots filled except one, and we fill that
+	// one.
+	onboard {
+		let c in 1 .. T::MaxCollators::get();
+
 		<LicenseBond<T>>::put(T::Currency::minimum_balance());
+		<DesiredCollators<T>>::put(c + 1);
+
+		register_validators::<T>(c);
+		register_candidates::<T>(c);
+
+		let caller: T::AccountId = whitelisted_caller();
+		let bond: BalanceOf<T> = T::Currency::minimum_balance() * 2u32.into();
+		T::Currency::make_free_balance_be(&caller, bond.clone());
+
+		let origin = RawOrigin::Signed(caller.clone());
+
+		<session::Pallet<T>>::set_keys(
+			origin.clone().into(),
+			keys::<T>(c + 1),
+			Vec::new()
+		).unwrap();
+
+		assert_ok!(
+			<CollatorSelection<T>>::get_license(origin.clone().into())
+		);
+	}: _(origin)
+	verify {
+		assert_last_event::<T>(Event::CandidateAdded{account_id: caller}.into());
+	}
+
+	// worst case is the last candidate leaving.
+	offboard {
+		let c in 1 .. T::MaxCollators::get();
+		<LicenseBond<T>>::put(T::Currency::minimum_balance());
 		<DesiredCollators<T>>::put(c);
 
 		register_validators::<T>(c);
 		register_candidates::<T>(c);
 
-		let leaving = <Candidates<T>>::get().last().unwrap().who.clone();
+		let leaving = <Candidates<T>>::get().last().unwrap().clone();
 		whitelist!(leaving);
 	}: _(RawOrigin::Signed(leaving.clone()))
 	verify {
-		// todo:collator verify these
-		assert_last_event::<T>(Event::CandidateRemoved{account_id: leaving, deposit_returned: bond / 2u32.into() }.into());
+		assert_last_event::<T>(Event::CandidateRemoved{account_id: leaving}.into());
 	}
 
-	// worse case is paying a non-existing candidate account.
+	// worst case is the last candidate leaving.
+	release_license {
+		let c in 1 .. T::MaxCollators::get();
+		let bond = T::Currency::minimum_balance();
+		<LicenseBond<T>>::put(bond);
+		<DesiredCollators<T>>::put(c);
+
+		register_validators::<T>(c);
+		register_candidates::<T>(c);
+
+		let leaving = <Candidates<T>>::get().last().unwrap().clone();
+		whitelist!(leaving);
+	}: _(RawOrigin::Signed(leaving.clone()))
+	verify {
+		assert_last_event::<T>(Event::LicenseReleased{account_id: leaving, deposit_returned: bond}.into());
+	}
+
+	// worst case is the last candidate leaving.
+	force_release_license {
+		let c in 1 .. T::MaxCollators::get();
+		let bond = T::Currency::minimum_balance();
+		<LicenseBond<T>>::put(bond);
+		<DesiredCollators<T>>::put(c);
+
+		register_validators::<T>(c);
+		register_candidates::<T>(c);
+
+		let leaving = <Candidates<T>>::get().last().unwrap().clone();
+		whitelist!(leaving);
+		let origin = T::UpdateOrigin::successful_origin();
+	}: {
+		assert_ok!(
+			<CollatorSelection<T>>::force_release_license(origin, leaving.clone())
+		);
+	}
+	verify {
+		assert_last_event::<T>(Event::LicenseReleased{account_id: leaving, deposit_returned: bond}.into());
+	}
+
+	// worst case is paying a non-existing candidate account.
 	note_author {
 		<LicenseBond<T>>::put(T::Currency::minimum_balance());
 		T::Currency::make_free_balance_be(
@@ -247,16 +336,16 @@
 		let non_removals = c.saturating_sub(r);
 
 		for i in 0..c {
-			<LastAuthoredBlock<T>>::insert(candidates[i as usize].who.clone(), zero_block);
+			<LastAuthoredBlock<T>>::insert(candidates[i as usize].clone(), zero_block);
 		}
 
 		if non_removals > 0 {
 			for i in 0..non_removals {
-				<LastAuthoredBlock<T>>::insert(candidates[i as usize].who.clone(), new_block);
+				<LastAuthoredBlock<T>>::insert(candidates[i as usize].clone(), new_block);
 			}
 		} else {
 			for i in 0..c {
-				<LastAuthoredBlock<T>>::insert(candidates[i as usize].who.clone(), new_block);
+				<LastAuthoredBlock<T>>::insert(candidates[i as usize].clone(), new_block);
 			}
 		}
 
@@ -268,10 +357,8 @@
 	}: {
 		<CollatorSelection<T> as SessionManager<_>>::new_session(0)
 	} verify {
-		if c > r && non_removals >= T::MinCandidates::get() {
+		if c > r {
 			assert!(<Candidates<T>>::get().len() < pre_length);
-		} else if c > r && non_removals < T::MinCandidates::get() {
-			assert!(<Candidates<T>>::get().len() == T::MinCandidates::get() as usize);
 		} else {
 			assert!(<Candidates<T>>::get().len() == pre_length);
 		}
modifiedpallets/collator-selection/src/lib.rsdiffbeforeafterboth
--- a/pallets/collator-selection/src/lib.rs
+++ b/pallets/collator-selection/src/lib.rs
@@ -235,7 +235,7 @@
 			account_id: T::AccountId,
 			deposit: BalanceOf<T>,
 		},
-		LicenseForfeited {
+		LicenseReleased {
 			account_id: T::AccountId,
 			deposit_returned: BalanceOf<T>,
 		},
@@ -285,7 +285,7 @@
 	impl<T: Config> Pallet<T> {
 		/// Add a collator to the list of invulnerable (fixed) collators.
 		#[pallet::call_index(0)]
-		#[pallet::weight(T::WeightInfo::set_invulnerables(1u32))] // todo:collator weight
+		#[pallet::weight(T::WeightInfo::add_invulnerable(T::MaxCollators::get()))] // todo:collator weight
 		pub fn add_invulnerable(
 			origin: OriginFor<T>,
 			new: T::AccountId,
@@ -315,7 +315,7 @@
 
 		/// Remove a collator from the list of invulnerable (fixed) collators.
 		#[pallet::call_index(1)]
-		#[pallet::weight(T::WeightInfo::set_invulnerables(1))] // todo:collator weight
+		#[pallet::weight(T::WeightInfo::remove_invulnerable(T::MaxCollators::get()))] // todo:collator weight
 		pub fn remove_invulnerable(
 			origin: OriginFor<T>,
 			who: T::AccountId,
@@ -344,7 +344,7 @@
 		///
 		/// This call is not available to `Invulnerable` collators.
 		#[pallet::call_index(2)]
-		#[pallet::weight(T::WeightInfo::register_as_candidate(T::MaxCollators::get()))] // todo:collator weight
+		#[pallet::weight(T::WeightInfo::get_license(T::MaxCollators::get()))] // todo:collator weight
 		pub fn get_license(origin: OriginFor<T>) -> DispatchResultWithPostInfo {
 			// register_as_candidate
 			let who = ensure_signed(origin)?;
@@ -377,7 +377,7 @@
 		///
 		/// This call is not available to `Invulnerable` collators.
 		#[pallet::call_index(3)]
-		#[pallet::weight(T::WeightInfo::register_as_candidate(T::MaxCollators::get()))] // todo:collator weight
+		#[pallet::weight(T::WeightInfo::onboard(T::MaxCollators::get()))] // todo:collator weight
 		pub fn onboard(origin: OriginFor<T>) -> DispatchResultWithPostInfo {
 			// register_as_candidate
 			let who = ensure_signed(origin)?;
@@ -417,33 +417,33 @@
 				})?;
 
 			Self::deposit_event(Event::CandidateAdded { account_id: who });
-			Ok(Some(T::WeightInfo::register_as_candidate(current_count as u32)).into())
+			Ok(Some(T::WeightInfo::onboard(current_count as u32)).into())
 		}
 
 		/// Deregister `origin` as a collator candidate. Note that the collator can only leave on
 		/// session change. The license to `onboard` later at any other time will remain.
 		#[pallet::call_index(4)]
-		#[pallet::weight(T::WeightInfo::leave_intent(T::MaxCollators::get()))] // todo:collator weight
+		#[pallet::weight(T::WeightInfo::offboard(T::MaxCollators::get()))] // todo:collator weight
 		pub fn offboard(origin: OriginFor<T>) -> DispatchResultWithPostInfo {
 			// leave_intent
 			let who = ensure_signed(origin)?;
 			let current_count = Self::try_remove_candidate(&who)?;
 
-			Ok(Some(T::WeightInfo::leave_intent(current_count as u32)).into()) // todo:collator weight
+			Ok(Some(T::WeightInfo::offboard(current_count as u32)).into()) // todo:collator weight
 		}
 
 		/// Forfeit `origin`'s own license. The `LicenseBond` will be unreserved immediately.
 		///
 		/// This call is not available to `Invulnerable` collators.
 		#[pallet::call_index(5)]
-		#[pallet::weight(T::WeightInfo::leave_intent(T::MaxCollators::get()))] // todo:collator weight
+		#[pallet::weight(T::WeightInfo::release_license(T::MaxCollators::get()))] // todo:collator weight
 		pub fn release_license(origin: OriginFor<T>) -> DispatchResultWithPostInfo {
 			// leave_intent
 			let who = ensure_signed(origin)?;
 
 			let current_count = Self::try_remove_candidate_and_release_license(&who, false, true)?;
 
-			Ok(Some(T::WeightInfo::leave_intent(current_count as u32)).into()) // todo:collator weight
+			Ok(Some(T::WeightInfo::release_license(current_count as u32)).into()) // todo:collator weight
 		}
 
 		/// Force deregister `origin` as a collator candidate as a governing authority, and revoke its license.
@@ -452,7 +452,7 @@
 		///
 		/// This call is, of course, not applicable to `Invulnerable` collators.
 		#[pallet::call_index(6)]
-		#[pallet::weight(T::WeightInfo::leave_intent(T::MaxCollators::get()))] // todo:collator weight
+		#[pallet::weight(T::WeightInfo::force_release_license(T::MaxCollators::get()))] // todo:collator weight
 		pub fn force_release_license(
 			origin: OriginFor<T>,
 			who: T::AccountId,
@@ -462,7 +462,7 @@
 
 			let current_count = Self::try_remove_candidate_and_release_license(&who, false, true)?;
 
-			Ok(Some(T::WeightInfo::leave_intent(current_count as u32)).into()) // todo:collator weight
+			Ok(Some(T::WeightInfo::force_release_license(current_count as u32)).into()) // todo:collator weight
 		}
 	}
 
@@ -534,7 +534,7 @@
 					Err(Error::<T>::NoLicense.into())
 				}
 			})?;
-			Self::deposit_event(Event::LicenseForfeited {
+			Self::deposit_event(Event::LicenseReleased {
 				account_id: who.clone(),
 				deposit_returned,
 			});
modifiedpallets/collator-selection/src/weights.rsdiffbeforeafterboth
--- a/pallets/collator-selection/src/weights.rs
+++ b/pallets/collator-selection/src/weights.rs
@@ -44,11 +44,13 @@
 // todo:collator re-generate weights
 // The weight info trait for `pallet_collator_selection`.
 pub trait WeightInfo {
-	fn set_invulnerables(_b: u32) -> Weight;
-	fn set_desired_collators() -> Weight;
-	fn set_license_bond() -> Weight;
-	fn register_as_candidate(_c: u32) -> Weight;
-	fn leave_intent(_c: u32) -> Weight;
+	fn add_invulnerable(_b: u32) -> Weight;
+	fn remove_invulnerable(_b: u32) -> Weight;
+	fn get_license(_c: u32) -> Weight;
+	fn onboard(_c: u32) -> Weight;
+	fn offboard(_c: u32) -> Weight;
+	fn release_license(_c: u32) -> Weight;
+	fn force_release_license(_c: u32) -> Weight;
 	fn note_author() -> Weight;
 	fn new_session(_c: u32, _r: u32) -> Weight;
 }
@@ -56,26 +58,47 @@
 /// Weights for pallet_collator_selection using the Substrate node and recommended hardware.
 pub struct SubstrateWeight<T>(PhantomData<T>);
 impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
-	fn set_invulnerables(b: u32) -> Weight {
+	fn add_invulnerable(b: u32) -> Weight {
 		Weight::from_ref_time(18_563_000 as u64)
 			// Standard Error: 0
 			.saturating_add(Weight::from_ref_time(68_000 as u64).saturating_mul(b as u64))
 			.saturating_add(T::DbWeight::get().writes(1 as u64))
 	}
-	fn set_desired_collators() -> Weight {
-		Weight::from_ref_time(16_363_000 as u64).saturating_add(T::DbWeight::get().writes(1 as u64))
+	fn remove_invulnerable(b: u32) -> Weight {
+		Weight::from_ref_time(18_563_000 as u64)
+			// Standard Error: 0
+			.saturating_add(Weight::from_ref_time(68_000 as u64).saturating_mul(b as u64))
+			.saturating_add(T::DbWeight::get().writes(1 as u64))
 	}
-	fn set_license_bond() -> Weight {
-		Weight::from_ref_time(16_840_000 as u64).saturating_add(T::DbWeight::get().writes(1 as u64))
+	fn get_license(c: u32) -> Weight {
+		Weight::from_ref_time(71_196_000 as u64)
+			// Standard Error: 0
+			.saturating_add(Weight::from_ref_time(198_000 as u64).saturating_mul(c as u64))
+			.saturating_add(T::DbWeight::get().reads(4 as u64))
+			.saturating_add(T::DbWeight::get().writes(2 as u64))
 	}
-	fn register_as_candidate(c: u32) -> Weight {
+	fn onboard(c: u32) -> Weight {
 		Weight::from_ref_time(71_196_000 as u64)
 			// Standard Error: 0
 			.saturating_add(Weight::from_ref_time(198_000 as u64).saturating_mul(c as u64))
 			.saturating_add(T::DbWeight::get().reads(4 as u64))
 			.saturating_add(T::DbWeight::get().writes(2 as u64))
 	}
-	fn leave_intent(c: u32) -> Weight {
+	fn offboard(c: u32) -> Weight {
+		Weight::from_ref_time(55_336_000 as u64)
+			// Standard Error: 0
+			.saturating_add(Weight::from_ref_time(151_000 as u64).saturating_mul(c as u64))
+			.saturating_add(T::DbWeight::get().reads(1 as u64))
+			.saturating_add(T::DbWeight::get().writes(2 as u64))
+	}
+	fn release_license(c: u32) -> Weight {
+		Weight::from_ref_time(55_336_000 as u64)
+			// Standard Error: 0
+			.saturating_add(Weight::from_ref_time(151_000 as u64).saturating_mul(c as u64))
+			.saturating_add(T::DbWeight::get().reads(1 as u64))
+			.saturating_add(T::DbWeight::get().writes(2 as u64))
+	}
+	fn force_release_license(c: u32) -> Weight {
 		Weight::from_ref_time(55_336_000 as u64)
 			// Standard Error: 0
 			.saturating_add(Weight::from_ref_time(151_000 as u64).saturating_mul(c as u64))
@@ -102,28 +125,47 @@
 
 // For backwards compatibility and tests
 impl WeightInfo for () {
-	fn set_invulnerables(b: u32) -> Weight {
+	fn add_invulnerable(b: u32) -> Weight {
 		Weight::from_ref_time(18_563_000 as u64)
 			// Standard Error: 0
 			.saturating_add(Weight::from_ref_time(68_000 as u64).saturating_mul(b as u64))
 			.saturating_add(RocksDbWeight::get().writes(1 as u64))
 	}
-	fn set_desired_collators() -> Weight {
-		Weight::from_ref_time(16_363_000 as u64)
+	fn remove_invulnerable(b: u32) -> Weight {
+		Weight::from_ref_time(18_563_000 as u64)
+			// Standard Error: 0
+			.saturating_add(Weight::from_ref_time(68_000 as u64).saturating_mul(b as u64))
 			.saturating_add(RocksDbWeight::get().writes(1 as u64))
 	}
-	fn set_license_bond() -> Weight {
-		Weight::from_ref_time(16_840_000 as u64)
-			.saturating_add(RocksDbWeight::get().writes(1 as u64))
+	fn get_license(c: u32) -> Weight {
+		Weight::from_ref_time(71_196_000 as u64)
+			// Standard Error: 0
+			.saturating_add(Weight::from_ref_time(198_000 as u64).saturating_mul(c as u64))
+			.saturating_add(RocksDbWeight::get().reads(4 as u64))
+			.saturating_add(RocksDbWeight::get().writes(2 as u64))
 	}
-	fn register_as_candidate(c: u32) -> Weight {
+	fn onboard(c: u32) -> Weight {
 		Weight::from_ref_time(71_196_000 as u64)
 			// Standard Error: 0
 			.saturating_add(Weight::from_ref_time(198_000 as u64).saturating_mul(c as u64))
 			.saturating_add(RocksDbWeight::get().reads(4 as u64))
 			.saturating_add(RocksDbWeight::get().writes(2 as u64))
 	}
-	fn leave_intent(c: u32) -> Weight {
+	fn offboard(c: u32) -> Weight {
+		Weight::from_ref_time(55_336_000 as u64)
+			// Standard Error: 0
+			.saturating_add(Weight::from_ref_time(151_000 as u64).saturating_mul(c as u64))
+			.saturating_add(RocksDbWeight::get().reads(1 as u64))
+			.saturating_add(RocksDbWeight::get().writes(2 as u64))
+	}
+	fn release_license(c: u32) -> Weight {
+		Weight::from_ref_time(55_336_000 as u64)
+			// Standard Error: 0
+			.saturating_add(Weight::from_ref_time(151_000 as u64).saturating_mul(c as u64))
+			.saturating_add(RocksDbWeight::get().reads(1 as u64))
+			.saturating_add(RocksDbWeight::get().writes(2 as u64))
+	}
+	fn force_release_license(c: u32) -> Weight {
 		Weight::from_ref_time(55_336_000 as u64)
 			// Standard Error: 0
 			.saturating_add(Weight::from_ref_time(151_000 as u64).saturating_mul(c as u64))
modifiedpallets/data-management/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/data-management/src/benchmarking.rs
+++ b/pallets/data-management/src/benchmarking.rs
@@ -63,4 +63,28 @@
 		use codec::Encode;
 		let logs = (0..b).map(|_| <T as Config>::RuntimeEvent::from(crate::Event::<T>::TestEvent).encode()).collect::<Vec<_>>();
 	}: _(RawOrigin::Root, logs)
+
+	set_identities {
+		let b in 0..600;
+		use frame_benchmarking::account;
+		use pallet_identity::{BalanceOf, Registration, IdentityInfo};
+		let identities = (0..b).map(|i| (
+			account("caller", i, 0),
+			Some(Registration::<BalanceOf<T>, T::MaxRegistrars, T::MaxAdditionalFields> {
+				judgements: Default::default(),
+				deposit: Default::default(),
+				info: IdentityInfo {
+					additional: Default::default(),
+					display: Default::default(),
+					legal: Default::default(),
+					web: Default::default(),
+					riot: Default::default(),
+					email: Default::default(),
+					pgp_fingerprint: None,
+					image: Default::default(),
+					twitter: Default::default(),
+				},
+			}),
+		)).collect::<Vec<_>>();
+	}: _(RawOrigin::Root, identities)
 }
modifiedpallets/data-management/src/lib.rsdiffbeforeafterboth
--- a/pallets/data-management/src/lib.rs
+++ b/pallets/data-management/src/lib.rs
@@ -153,12 +153,18 @@
 
 		/// Insert or remove identities.
 		#[pallet::call_index(5)]
-		#[pallet::weight(<SelfWeightOf<T>>::insert_events(identities.len() as u32))] // todo:collator weight
+		#[pallet::weight(<SelfWeightOf<T>>::set_identities(identities.len() as u32))] // todo:collator weight
 		pub fn set_identities(
 			origin: OriginFor<T>,
 			identities: Vec<(
 				T::AccountId,
-				Option<Registration<pallet_identity::BalanceOf<T>, T::MaxRegistrars, T::MaxAdditionalFields>>,
+				Option<
+					Registration<
+						pallet_identity::BalanceOf<T>,
+						T::MaxRegistrars,
+						T::MaxAdditionalFields,
+					>,
+				>,
 			)>,
 		) -> DispatchResult {
 			ensure_root(origin)?;
modifiedpallets/data-management/src/weights.rsdiffbeforeafterboth
--- a/pallets/data-management/src/weights.rs
+++ b/pallets/data-management/src/weights.rs
@@ -39,6 +39,7 @@
 	fn finish(b: u32, ) -> Weight;
 	fn insert_eth_logs(b: u32, ) -> Weight;
 	fn insert_events(b: u32, ) -> Weight;
+	fn set_identities(b: u32, ) -> Weight;
 }
 
 /// Weights for pallet_data_management using the Substrate node and recommended hardware.
@@ -80,6 +81,11 @@
 			// Standard Error: 1_227
 			.saturating_add(Weight::from_ref_time(1_311_481 as u64).saturating_mul(b as u64))
 	}
+	fn set_identities(b: u32, ) -> Weight {
+		Weight::from_ref_time(10_936_376 as u64)
+			// Standard Error: 1_227
+			.saturating_add(Weight::from_ref_time(1_311_481 as u64).saturating_mul(b as u64))
+	}
 }
 
 // For backwards compatibility and tests
@@ -120,4 +126,9 @@
 			// Standard Error: 1_227
 			.saturating_add(Weight::from_ref_time(1_311_481 as u64).saturating_mul(b as u64))
 	}
+	fn set_identities(b: u32, ) -> Weight {
+		Weight::from_ref_time(10_936_376 as u64)
+			// Standard Error: 1_227
+			.saturating_add(Weight::from_ref_time(1_311_481 as u64).saturating_mul(b as u64))
+	}
 }
modifiedpallets/identity/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/identity/src/benchmarking.rs
+++ b/pallets/identity/src/benchmarking.rs
@@ -62,14 +62,16 @@
 		let registrar_origin = T::RegistrarOrigin::successful_origin();
 		Identity::<T>::add_registrar(registrar_origin, registrar_lookup)?;
 		Identity::<T>::set_fee(RawOrigin::Signed(registrar.clone()).into(), i, 10u32.into())?;
-		let fields =
-			IdentityFields(
-				IdentityField::Display |
-					IdentityField::Legal | IdentityField::Web |
-					IdentityField::Riot | IdentityField::Email |
-					IdentityField::PgpFingerprint |
-					IdentityField::Image | IdentityField::Twitter,
-			);
+		let fields = IdentityFields(
+			IdentityField::Display
+				| IdentityField::Legal
+				| IdentityField::Web
+				| IdentityField::Riot
+				| IdentityField::Email
+				| IdentityField::PgpFingerprint
+				| IdentityField::Image
+				| IdentityField::Twitter,
+		);
 		Identity::<T>::set_fields(RawOrigin::Signed(registrar.clone()).into(), i, fields)?;
 	}
 
@@ -122,7 +124,9 @@
 	let data = Data::Raw(vec![0; 32].try_into().unwrap());
 
 	IdentityInfo {
-		additional: vec![(data.clone(), data.clone()); num_fields as usize].try_into().unwrap(),
+		additional: vec![(data.clone(), data.clone()); num_fields as usize]
+			.try_into()
+			.unwrap(),
 		display: data.clone(),
 		legal: data.clone(),
 		web: data.clone(),
modifiedpallets/identity/src/lib.rsdiffbeforeafterboth
before · pallets/identity/src/lib.rs
1// 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/>.1617// Original license:18// This file is part of Substrate.1920// Copyright (C) 2019-2022 Parity Technologies (UK) Ltd.21// SPDX-License-Identifier: Apache-2.02223// Licensed under the Apache License, Version 2.0 (the "License");24// you may not use this file except in compliance with the License.25// You may obtain a copy of the License at26//27// 	http://www.apache.org/licenses/LICENSE-2.028//29// Unless required by applicable law or agreed to in writing, software30// distributed under the License is distributed on an "AS IS" BASIS,31// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.32// See the License for the specific language governing permissions and33// limitations under the License.3435//! # Identity Pallet36//!37//! - [`Config`]38//! - [`Call`]39//!40//! ## Overview41//!42//! A federated naming system, allowing for multiple registrars to be added from a specified origin.43//! Registrars can set a fee to provide identity-verification service. Anyone can put forth a44//! proposed identity for a fixed deposit and ask for review by any number of registrars (paying45//! each of their fees). Registrar judgements are given as an `enum`, allowing for sophisticated,46//! multi-tier opinions.47//!48//! Some judgements are identified as *sticky*, which means they cannot be removed except by49//! complete removal of the identity, or by the registrar. Judgements are allowed to represent a50//! portion of funds that have been reserved for the registrar.51//!52//! A super-user can remove accounts and in doing so, slash the deposit.53//!54//! All accounts may also have a limited number of sub-accounts which may be specified by the owner;55//! by definition, these have equivalent ownership and each has an individual name.56//!57//! The number of registrars should be limited, and the deposit made sufficiently large, to ensure58//! no state-bloat attack is viable.59//!60//! ## Interface61//!62//! ### Dispatchable Functions63//!64//! #### For general users65//! * `set_identity` - Set the associated identity of an account; a small deposit is reserved if not66//!   already taken.67//! * `clear_identity` - Remove an account's associated identity; the deposit is returned.68//! * `request_judgement` - Request a judgement from a registrar, paying a fee.69//! * `cancel_request` - Cancel the previous request for a judgement.70//!71//! #### For general users with sub-identities72//! * `set_subs` - Set the sub-accounts of an identity.73//! * `add_sub` - Add a sub-identity to an identity.74//! * `remove_sub` - Remove a sub-identity of an identity.75//! * `rename_sub` - Rename a sub-identity of an identity.76//! * `quit_sub` - Remove a sub-identity of an identity (called by the sub-identity).77//!78//! #### For registrars79//! * `set_fee` - Set the fee required to be paid for a judgement to be given by the registrar.80//! * `set_fields` - Set the fields that a registrar cares about in their judgements.81//! * `provide_judgement` - Provide a judgement to an identity.82//!83//! #### For super-users84//! * `add_registrar` - Add a new registrar to the system.85//! * `kill_identity` - Forcibly remove the associated identity; the deposit is lost.86//!87//! [`Call`]: ./enum.Call.html88//! [`Config`]: ./trait.Config.html8990#![cfg_attr(not(feature = "std"), no_std)]9192mod benchmarking;93#[cfg(test)]94mod tests;95mod types;96pub mod weights;9798use frame_support::traits::{BalanceStatus, Currency, OnUnbalanced, ReservableCurrency};99use sp_runtime::traits::{AppendZerosInput, Hash, Saturating, StaticLookup, Zero};100use sp_std::prelude::*;101pub use weights::WeightInfo;102103pub use pallet::*;104pub use types::{105	Data, IdentityField, IdentityFields, IdentityInfo, Judgement, RegistrarIndex, RegistrarInfo,106	Registration,107};108109pub type BalanceOf<T> =110	<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;111type NegativeImbalanceOf<T> = <<T as Config>::Currency as Currency<112	<T as frame_system::Config>::AccountId,113>>::NegativeImbalance;114type AccountIdLookupOf<T> = <<T as frame_system::Config>::Lookup as StaticLookup>::Source;115116#[frame_support::pallet]117pub mod pallet {118	use super::*;119	use frame_support::pallet_prelude::*;120	use frame_system::pallet_prelude::*;121122	#[pallet::config]123	pub trait Config: frame_system::Config {124		/// The overarching event type.125		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;126127		/// The currency trait.128		type Currency: ReservableCurrency<Self::AccountId>;129130		/// The amount held on deposit for a registered identity131		#[pallet::constant]132		type BasicDeposit: Get<BalanceOf<Self>>;133134		/// The amount held on deposit per additional field for a registered identity.135		#[pallet::constant]136		type FieldDeposit: Get<BalanceOf<Self>>;137138		/// The amount held on deposit for a registered subaccount. This should account for the fact139		/// that one storage item's value will increase by the size of an account ID, and there will140		/// be another trie item whose value is the size of an account ID plus 32 bytes.141		#[pallet::constant]142		type SubAccountDeposit: Get<BalanceOf<Self>>;143144		/// The maximum number of sub-accounts allowed per identified account.145		#[pallet::constant]146		type MaxSubAccounts: Get<u32>;147148		/// Maximum number of additional fields that may be stored in an ID. Needed to bound the I/O149		/// required to access an identity, but can be pretty high.150		#[pallet::constant]151		type MaxAdditionalFields: Get<u32>;152153		/// Maxmimum number of registrars allowed in the system. Needed to bound the complexity154		/// of, e.g., updating judgements.155		#[pallet::constant]156		type MaxRegistrars: Get<u32>;157158		/// What to do with slashed funds.159		type Slashed: OnUnbalanced<NegativeImbalanceOf<Self>>;160161		/// The origin which may forcibly set or remove a name. Root can always do this.162		type ForceOrigin: EnsureOrigin<Self::RuntimeOrigin>;163164		/// The origin which may add or remove registrars. Root can always do this.165		type RegistrarOrigin: EnsureOrigin<Self::RuntimeOrigin>;166167		/// Weight information for extrinsics in this pallet.168		type WeightInfo: WeightInfo;169	}170171	#[pallet::pallet]172	#[pallet::generate_store(pub(super) trait Store)]173	pub struct Pallet<T>(_);174175	/// Information that is pertinent to identify the entity behind an account.176	///177	/// TWOX-NOTE: OK ― `AccountId` is a secure hash.178	#[pallet::storage]179	#[pallet::getter(fn identity)]180	pub type IdentityOf<T: Config> = StorageMap<181		_,182		Twox64Concat,183		T::AccountId,184		Registration<BalanceOf<T>, T::MaxRegistrars, T::MaxAdditionalFields>,185		OptionQuery,186	>;187188	/// The super-identity of an alternative "sub" identity together with its name, within that189	/// context. If the account is not some other account's sub-identity, then just `None`.190	#[pallet::storage]191	#[pallet::getter(fn super_of)]192	pub(super) type SuperOf<T: Config> =193		StorageMap<_, Blake2_128Concat, T::AccountId, (T::AccountId, Data), OptionQuery>;194195	/// Alternative "sub" identities of this account.196	///197	/// The first item is the deposit, the second is a vector of the accounts.198	///199	/// TWOX-NOTE: OK ― `AccountId` is a secure hash.200	#[pallet::storage]201	#[pallet::getter(fn subs_of)]202	pub(super) type SubsOf<T: Config> = StorageMap<203		_,204		Twox64Concat,205		T::AccountId,206		(BalanceOf<T>, BoundedVec<T::AccountId, T::MaxSubAccounts>),207		ValueQuery,208	>;209210	/// The set of registrars. Not expected to get very big as can only be added through a211	/// special origin (likely a council motion).212	///213	/// The index into this can be cast to `RegistrarIndex` to get a valid value.214	#[pallet::storage]215	#[pallet::getter(fn registrars)]216	pub(super) type Registrars<T: Config> = StorageValue<217		_,218		BoundedVec<Option<RegistrarInfo<BalanceOf<T>, T::AccountId>>, T::MaxRegistrars>,219		ValueQuery,220	>;221222	#[pallet::error]223	pub enum Error<T> {224		/// Too many subs-accounts.225		TooManySubAccounts,226		/// Account isn't found.227		NotFound,228		/// Account isn't named.229		NotNamed,230		/// Empty index.231		EmptyIndex,232		/// Fee is changed.233		FeeChanged,234		/// No identity found.235		NoIdentity,236		/// Sticky judgement.237		StickyJudgement,238		/// Judgement given.239		JudgementGiven,240		/// Invalid judgement.241		InvalidJudgement,242		/// The index is invalid.243		InvalidIndex,244		/// The target is invalid.245		InvalidTarget,246		/// Too many additional fields.247		TooManyFields,248		/// Maximum amount of registrars reached. Cannot add any more.249		TooManyRegistrars,250		/// Account ID is already named.251		AlreadyClaimed,252		/// Sender is not a sub-account.253		NotSub,254		/// Sub-account isn't owned by sender.255		NotOwned,256		/// The provided judgement was for a different identity.257		JudgementForDifferentIdentity,258		/// Error that occurs when there is an issue paying for judgement.259		JudgementPaymentFailed,260	}261262	#[pallet::event]263	#[pallet::generate_deposit(pub(super) fn deposit_event)]264	pub enum Event<T: Config> {265		/// A name was set or reset (which will remove all judgements).266		IdentitySet { who: T::AccountId },267		/// A name was cleared, and the given balance returned.268		IdentityCleared { who: T::AccountId, deposit: BalanceOf<T> },269		/// A name was removed and the given balance slashed.270		IdentityKilled { who: T::AccountId, deposit: BalanceOf<T> },271		/// A judgement was asked from a registrar.272		JudgementRequested { who: T::AccountId, registrar_index: RegistrarIndex },273		/// A judgement request was retracted.274		JudgementUnrequested { who: T::AccountId, registrar_index: RegistrarIndex },275		/// A judgement was given by a registrar.276		JudgementGiven { target: T::AccountId, registrar_index: RegistrarIndex },277		/// A registrar was added.278		RegistrarAdded { registrar_index: RegistrarIndex },279		/// A sub-identity was added to an identity and the deposit paid.280		SubIdentityAdded { sub: T::AccountId, main: T::AccountId, deposit: BalanceOf<T> },281		/// A sub-identity was removed from an identity and the deposit freed.282		SubIdentityRemoved { sub: T::AccountId, main: T::AccountId, deposit: BalanceOf<T> },283		/// A sub-identity was cleared, and the given deposit repatriated from the284		/// main identity account to the sub-identity account.285		SubIdentityRevoked { sub: T::AccountId, main: T::AccountId, deposit: BalanceOf<T> },286	}287288	#[pallet::call]289	/// Identity pallet declaration.290	impl<T: Config> Pallet<T> {291		/// Add a registrar to the system.292		///293		/// The dispatch origin for this call must be `T::RegistrarOrigin`.294		///295		/// - `account`: the account of the registrar.296		///297		/// Emits `RegistrarAdded` if successful.298		///299		/// # <weight>300		/// - `O(R)` where `R` registrar-count (governance-bounded and code-bounded).301		/// - One storage mutation (codec `O(R)`).302		/// - One event.303		/// # </weight>304		#[pallet::call_index(0)]305		#[pallet::weight(T::WeightInfo::add_registrar(T::MaxRegistrars::get()))]306		pub fn add_registrar(307			origin: OriginFor<T>,308			account: AccountIdLookupOf<T>,309		) -> DispatchResultWithPostInfo {310			T::RegistrarOrigin::ensure_origin(origin)?;311			let account = T::Lookup::lookup(account)?;312313			let (i, registrar_count) = <Registrars<T>>::try_mutate(314				|registrars| -> Result<(RegistrarIndex, usize), DispatchError> {315					registrars316						.try_push(Some(RegistrarInfo {317							account,318							fee: Zero::zero(),319							fields: Default::default(),320						}))321						.map_err(|_| Error::<T>::TooManyRegistrars)?;322					Ok(((registrars.len() - 1) as RegistrarIndex, registrars.len()))323				},324			)?;325326			Self::deposit_event(Event::RegistrarAdded { registrar_index: i });327328			Ok(Some(T::WeightInfo::add_registrar(registrar_count as u32)).into())329		}330331		/// Set an account's identity information and reserve the appropriate deposit.332		///333		/// If the account already has identity information, the deposit is taken as part payment334		/// for the new deposit.335		///336		/// The dispatch origin for this call must be _Signed_.337		///338		/// - `info`: The identity information.339		///340		/// Emits `IdentitySet` if successful.341		///342		/// # <weight>343		/// - `O(X + X' + R)`344		///   - where `X` additional-field-count (deposit-bounded and code-bounded)345		///   - where `R` judgements-count (registrar-count-bounded)346		/// - One balance reserve operation.347		/// - One storage mutation (codec-read `O(X' + R)`, codec-write `O(X + R)`).348		/// - One event.349		/// # </weight>350		#[pallet::call_index(1)]351		#[pallet::weight( T::WeightInfo::set_identity(352			T::MaxRegistrars::get(), // R353			T::MaxAdditionalFields::get(), // X354		))]355		pub fn set_identity(356			origin: OriginFor<T>,357			info: Box<IdentityInfo<T::MaxAdditionalFields>>,358		) -> DispatchResultWithPostInfo {359			let sender = ensure_signed(origin)?;360			let extra_fields = info.additional.len() as u32;361			ensure!(extra_fields <= T::MaxAdditionalFields::get(), Error::<T>::TooManyFields);362			let fd = <BalanceOf<T>>::from(extra_fields) * T::FieldDeposit::get();363364			let mut id = match <IdentityOf<T>>::get(&sender) {365				Some(mut id) => {366					// Only keep non-positive judgements.367					id.judgements.retain(|j| j.1.is_sticky());368					id.info = *info;369					id370				},371				None => Registration {372					info: *info,373					judgements: BoundedVec::default(),374					deposit: Zero::zero(),375				},376			};377378			let old_deposit = id.deposit;379			id.deposit = T::BasicDeposit::get() + fd;380			if id.deposit > old_deposit {381				T::Currency::reserve(&sender, id.deposit - old_deposit)?;382			}383			if old_deposit > id.deposit {384				let err_amount = T::Currency::unreserve(&sender, old_deposit - id.deposit);385				debug_assert!(err_amount.is_zero());386			}387388			let judgements = id.judgements.len();389			<IdentityOf<T>>::insert(&sender, id);390			Self::deposit_event(Event::IdentitySet { who: sender });391392			Ok(Some(T::WeightInfo::set_identity(393				judgements as u32, // R394				extra_fields,      // X395			))396			.into())397		}398399		/// Set the sub-accounts of the sender.400		///401		/// Payment: Any aggregate balance reserved by previous `set_subs` calls will be returned402		/// and an amount `SubAccountDeposit` will be reserved for each item in `subs`.403		///404		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered405		/// identity.406		///407		/// - `subs`: The identity's (new) sub-accounts.408		///409		/// # <weight>410		/// - `O(P + S)`411		///   - where `P` old-subs-count (hard- and deposit-bounded).412		///   - where `S` subs-count (hard- and deposit-bounded).413		/// - At most one balance operations.414		/// - DB:415		///   - `P + S` storage mutations (codec complexity `O(1)`)416		///   - One storage read (codec complexity `O(P)`).417		///   - One storage write (codec complexity `O(S)`).418		///   - One storage-exists (`IdentityOf::contains_key`).419		/// # </weight>420		// TODO: This whole extrinsic screams "not optimized". For example we could421		// filter any overlap between new and old subs, and avoid reading/writing422		// to those values... We could also ideally avoid needing to write to423		// N storage items for N sub accounts. Right now the weight on this function424		// is a large overestimate due to the fact that it could potentially write425		// to 2 x T::MaxSubAccounts::get().426		#[pallet::call_index(2)]427		#[pallet::weight(T::WeightInfo::set_subs_old(T::MaxSubAccounts::get()) // P: Assume max sub accounts removed.428			.saturating_add(T::WeightInfo::set_subs_new(subs.len() as u32)) // S: Assume all subs are new.429		)]430		pub fn set_subs(431			origin: OriginFor<T>,432			subs: Vec<(T::AccountId, Data)>,433		) -> DispatchResultWithPostInfo {434			let sender = ensure_signed(origin)?;435			ensure!(<IdentityOf<T>>::contains_key(&sender), Error::<T>::NotFound);436			ensure!(437				subs.len() <= T::MaxSubAccounts::get() as usize,438				Error::<T>::TooManySubAccounts439			);440441			let (old_deposit, old_ids) = <SubsOf<T>>::get(&sender);442			let new_deposit = T::SubAccountDeposit::get() * <BalanceOf<T>>::from(subs.len() as u32);443444			let not_other_sub =445				subs.iter().filter_map(|i| SuperOf::<T>::get(&i.0)).all(|i| i.0 == sender);446			ensure!(not_other_sub, Error::<T>::AlreadyClaimed);447448			if old_deposit < new_deposit {449				T::Currency::reserve(&sender, new_deposit - old_deposit)?;450			} else if old_deposit > new_deposit {451				let err_amount = T::Currency::unreserve(&sender, old_deposit - new_deposit);452				debug_assert!(err_amount.is_zero());453			}454			// do nothing if they're equal.455456			for s in old_ids.iter() {457				<SuperOf<T>>::remove(s);458			}459			let mut ids = BoundedVec::<T::AccountId, T::MaxSubAccounts>::default();460			for (id, name) in subs {461				<SuperOf<T>>::insert(&id, (sender.clone(), name));462				ids.try_push(id).expect("subs length is less than T::MaxSubAccounts; qed");463			}464			let new_subs = ids.len();465466			if ids.is_empty() {467				<SubsOf<T>>::remove(&sender);468			} else {469				<SubsOf<T>>::insert(&sender, (new_deposit, ids));470			}471472			Ok(Some(473				T::WeightInfo::set_subs_old(old_ids.len() as u32) // P: Real number of old accounts removed.474					// S: New subs added475					.saturating_add(T::WeightInfo::set_subs_new(new_subs as u32)),476			)477			.into())478		}479480		/// Clear an account's identity info and all sub-accounts and return all deposits.481		///482		/// Payment: All reserved balances on the account are returned.483		///484		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered485		/// identity.486		///487		/// Emits `IdentityCleared` if successful.488		///489		/// # <weight>490		/// - `O(R + S + X)`491		///   - where `R` registrar-count (governance-bounded).492		///   - where `S` subs-count (hard- and deposit-bounded).493		///   - where `X` additional-field-count (deposit-bounded and code-bounded).494		/// - One balance-unreserve operation.495		/// - `2` storage reads and `S + 2` storage deletions.496		/// - One event.497		/// # </weight>498		#[pallet::call_index(3)]499		#[pallet::weight(T::WeightInfo::clear_identity(500			T::MaxRegistrars::get(), // R501			T::MaxSubAccounts::get(), // S502			T::MaxAdditionalFields::get(), // X503		))]504		pub fn clear_identity(origin: OriginFor<T>) -> DispatchResultWithPostInfo {505			let sender = ensure_signed(origin)?;506507			let (subs_deposit, sub_ids) = <SubsOf<T>>::take(&sender);508			let id = <IdentityOf<T>>::take(&sender).ok_or(Error::<T>::NotNamed)?;509			let deposit = id.total_deposit() + subs_deposit;510			for sub in sub_ids.iter() {511				<SuperOf<T>>::remove(sub);512			}513514			let err_amount = T::Currency::unreserve(&sender, deposit);515			debug_assert!(err_amount.is_zero());516517			Self::deposit_event(Event::IdentityCleared { who: sender, deposit });518519			Ok(Some(T::WeightInfo::clear_identity(520				id.judgements.len() as u32,      // R521				sub_ids.len() as u32,            // S522				id.info.additional.len() as u32, // X523			))524			.into())525		}526527		/// Request a judgement from a registrar.528		///529		/// Payment: At most `max_fee` will be reserved for payment to the registrar if judgement530		/// given.531		///532		/// The dispatch origin for this call must be _Signed_ and the sender must have a533		/// registered identity.534		///535		/// - `reg_index`: The index of the registrar whose judgement is requested.536		/// - `max_fee`: The maximum fee that may be paid. This should just be auto-populated as:537		///538		/// ```nocompile539		/// Self::registrars().get(reg_index).unwrap().fee540		/// ```541		///542		/// Emits `JudgementRequested` if successful.543		///544		/// # <weight>545		/// - `O(R + X)`.546		/// - One balance-reserve operation.547		/// - Storage: 1 read `O(R)`, 1 mutate `O(X + R)`.548		/// - One event.549		/// # </weight>550		#[pallet::call_index(4)]551		#[pallet::weight(T::WeightInfo::request_judgement(552			T::MaxRegistrars::get(), // R553			T::MaxAdditionalFields::get(), // X554		))]555		pub fn request_judgement(556			origin: OriginFor<T>,557			#[pallet::compact] reg_index: RegistrarIndex,558			#[pallet::compact] max_fee: BalanceOf<T>,559		) -> DispatchResultWithPostInfo {560			let sender = ensure_signed(origin)?;561			let registrars = <Registrars<T>>::get();562			let registrar = registrars563				.get(reg_index as usize)564				.and_then(Option::as_ref)565				.ok_or(Error::<T>::EmptyIndex)?;566			ensure!(max_fee >= registrar.fee, Error::<T>::FeeChanged);567			let mut id = <IdentityOf<T>>::get(&sender).ok_or(Error::<T>::NoIdentity)?;568569			let item = (reg_index, Judgement::FeePaid(registrar.fee));570			match id.judgements.binary_search_by_key(&reg_index, |x| x.0) {571				Ok(i) =>572					if id.judgements[i].1.is_sticky() {573						return Err(Error::<T>::StickyJudgement.into())574					} else {575						id.judgements[i] = item576					},577				Err(i) =>578					id.judgements.try_insert(i, item).map_err(|_| Error::<T>::TooManyRegistrars)?,579			}580581			T::Currency::reserve(&sender, registrar.fee)?;582583			let judgements = id.judgements.len();584			let extra_fields = id.info.additional.len();585			<IdentityOf<T>>::insert(&sender, id);586587			Self::deposit_event(Event::JudgementRequested {588				who: sender,589				registrar_index: reg_index,590			});591592			Ok(Some(T::WeightInfo::request_judgement(judgements as u32, extra_fields as u32))593				.into())594		}595596		/// Cancel a previous request.597		///598		/// Payment: A previously reserved deposit is returned on success.599		///600		/// The dispatch origin for this call must be _Signed_ and the sender must have a601		/// registered identity.602		///603		/// - `reg_index`: The index of the registrar whose judgement is no longer requested.604		///605		/// Emits `JudgementUnrequested` if successful.606		///607		/// # <weight>608		/// - `O(R + X)`.609		/// - One balance-reserve operation.610		/// - One storage mutation `O(R + X)`.611		/// - One event612		/// # </weight>613		#[pallet::call_index(5)]614		#[pallet::weight(T::WeightInfo::cancel_request(615			T::MaxRegistrars::get(), // R616			T::MaxAdditionalFields::get(), // X617		))]618		pub fn cancel_request(619			origin: OriginFor<T>,620			reg_index: RegistrarIndex,621		) -> DispatchResultWithPostInfo {622			let sender = ensure_signed(origin)?;623			let mut id = <IdentityOf<T>>::get(&sender).ok_or(Error::<T>::NoIdentity)?;624625			let pos = id626				.judgements627				.binary_search_by_key(&reg_index, |x| x.0)628				.map_err(|_| Error::<T>::NotFound)?;629			let fee = if let Judgement::FeePaid(fee) = id.judgements.remove(pos).1 {630				fee631			} else {632				return Err(Error::<T>::JudgementGiven.into())633			};634635			let err_amount = T::Currency::unreserve(&sender, fee);636			debug_assert!(err_amount.is_zero());637			let judgements = id.judgements.len();638			let extra_fields = id.info.additional.len();639			<IdentityOf<T>>::insert(&sender, id);640641			Self::deposit_event(Event::JudgementUnrequested {642				who: sender,643				registrar_index: reg_index,644			});645646			Ok(Some(T::WeightInfo::cancel_request(judgements as u32, extra_fields as u32)).into())647		}648649		/// Set the fee required for a judgement to be requested from a registrar.650		///651		/// The dispatch origin for this call must be _Signed_ and the sender must be the account652		/// of the registrar whose index is `index`.653		///654		/// - `index`: the index of the registrar whose fee is to be set.655		/// - `fee`: the new fee.656		///657		/// # <weight>658		/// - `O(R)`.659		/// - One storage mutation `O(R)`.660		/// - Benchmark: 7.315 + R * 0.329 µs (min squares analysis)661		/// # </weight>662		#[pallet::call_index(6)]663		#[pallet::weight(T::WeightInfo::set_fee(T::MaxRegistrars::get()))] // R664		pub fn set_fee(665			origin: OriginFor<T>,666			#[pallet::compact] index: RegistrarIndex,667			#[pallet::compact] fee: BalanceOf<T>,668		) -> DispatchResultWithPostInfo {669			let who = ensure_signed(origin)?;670671			let registrars = <Registrars<T>>::mutate(|rs| -> Result<usize, DispatchError> {672				rs.get_mut(index as usize)673					.and_then(|x| x.as_mut())674					.and_then(|r| {675						if r.account == who {676							r.fee = fee;677							Some(())678						} else {679							None680						}681					})682					.ok_or_else(|| DispatchError::from(Error::<T>::InvalidIndex))?;683				Ok(rs.len())684			})?;685			Ok(Some(T::WeightInfo::set_fee(registrars as u32)).into()) // R686		}687688		/// Change the account associated with a registrar.689		///690		/// The dispatch origin for this call must be _Signed_ and the sender must be the account691		/// of the registrar whose index is `index`.692		///693		/// - `index`: the index of the registrar whose fee is to be set.694		/// - `new`: the new account ID.695		///696		/// # <weight>697		/// - `O(R)`.698		/// - One storage mutation `O(R)`.699		/// - Benchmark: 8.823 + R * 0.32 µs (min squares analysis)700		/// # </weight>701		#[pallet::call_index(7)]702		#[pallet::weight(T::WeightInfo::set_account_id(T::MaxRegistrars::get()))] // R703		pub fn set_account_id(704			origin: OriginFor<T>,705			#[pallet::compact] index: RegistrarIndex,706			new: AccountIdLookupOf<T>,707		) -> DispatchResultWithPostInfo {708			let who = ensure_signed(origin)?;709			let new = T::Lookup::lookup(new)?;710711			let registrars = <Registrars<T>>::mutate(|rs| -> Result<usize, DispatchError> {712				rs.get_mut(index as usize)713					.and_then(|x| x.as_mut())714					.and_then(|r| {715						if r.account == who {716							r.account = new;717							Some(())718						} else {719							None720						}721					})722					.ok_or_else(|| DispatchError::from(Error::<T>::InvalidIndex))?;723				Ok(rs.len())724			})?;725			Ok(Some(T::WeightInfo::set_account_id(registrars as u32)).into()) // R726		}727728		/// Set the field information for a registrar.729		///730		/// The dispatch origin for this call must be _Signed_ and the sender must be the account731		/// of the registrar whose index is `index`.732		///733		/// - `index`: the index of the registrar whose fee is to be set.734		/// - `fields`: the fields that the registrar concerns themselves with.735		///736		/// # <weight>737		/// - `O(R)`.738		/// - One storage mutation `O(R)`.739		/// - Benchmark: 7.464 + R * 0.325 µs (min squares analysis)740		/// # </weight>741		#[pallet::call_index(8)]742		#[pallet::weight(T::WeightInfo::set_fields(T::MaxRegistrars::get()))] // R743		pub fn set_fields(744			origin: OriginFor<T>,745			#[pallet::compact] index: RegistrarIndex,746			fields: IdentityFields,747		) -> DispatchResultWithPostInfo {748			let who = ensure_signed(origin)?;749750			let registrars = <Registrars<T>>::mutate(|rs| -> Result<usize, DispatchError> {751				rs.get_mut(index as usize)752					.and_then(|x| x.as_mut())753					.and_then(|r| {754						if r.account == who {755							r.fields = fields;756							Some(())757						} else {758							None759						}760					})761					.ok_or_else(|| DispatchError::from(Error::<T>::InvalidIndex))?;762				Ok(rs.len())763			})?;764			Ok(Some(T::WeightInfo::set_fields(765				registrars as u32, // R766			))767			.into())768		}769770		/// Provide a judgement for an account's identity.771		///772		/// The dispatch origin for this call must be _Signed_ and the sender must be the account773		/// of the registrar whose index is `reg_index`.774		///775		/// - `reg_index`: the index of the registrar whose judgement is being made.776		/// - `target`: the account whose identity the judgement is upon. This must be an account777		///   with a registered identity.778		/// - `judgement`: the judgement of the registrar of index `reg_index` about `target`.779		/// - `identity`: The hash of the [`IdentityInfo`] for that the judgement is provided.780		///781		/// Emits `JudgementGiven` if successful.782		///783		/// # <weight>784		/// - `O(R + X)`.785		/// - One balance-transfer operation.786		/// - Up to one account-lookup operation.787		/// - Storage: 1 read `O(R)`, 1 mutate `O(R + X)`.788		/// - One event.789		/// # </weight>790		#[pallet::call_index(9)]791		#[pallet::weight(T::WeightInfo::provide_judgement(792			T::MaxRegistrars::get(), // R793			T::MaxAdditionalFields::get(), // X794		))]795		pub fn provide_judgement(796			origin: OriginFor<T>,797			#[pallet::compact] reg_index: RegistrarIndex,798			target: AccountIdLookupOf<T>,799			judgement: Judgement<BalanceOf<T>>,800			identity: T::Hash,801		) -> DispatchResultWithPostInfo {802			let sender = ensure_signed(origin)?;803			let target = T::Lookup::lookup(target)?;804			ensure!(!judgement.has_deposit(), Error::<T>::InvalidJudgement);805			<Registrars<T>>::get()806				.get(reg_index as usize)807				.and_then(Option::as_ref)808				.filter(|r| r.account == sender)809				.ok_or(Error::<T>::InvalidIndex)?;810			let mut id = <IdentityOf<T>>::get(&target).ok_or(Error::<T>::InvalidTarget)?;811812			if T::Hashing::hash_of(&id.info) != identity {813				return Err(Error::<T>::JudgementForDifferentIdentity.into())814			}815816			let item = (reg_index, judgement);817			match id.judgements.binary_search_by_key(&reg_index, |x| x.0) {818				Ok(position) => {819					if let Judgement::FeePaid(fee) = id.judgements[position].1 {820						T::Currency::repatriate_reserved(821							&target,822							&sender,823							fee,824							BalanceStatus::Free,825						)826						.map_err(|_| Error::<T>::JudgementPaymentFailed)?;827					}828					id.judgements[position] = item829				},830				Err(position) => id831					.judgements832					.try_insert(position, item)833					.map_err(|_| Error::<T>::TooManyRegistrars)?,834			}835836			let judgements = id.judgements.len();837			let extra_fields = id.info.additional.len();838			<IdentityOf<T>>::insert(&target, id);839			Self::deposit_event(Event::JudgementGiven { target, registrar_index: reg_index });840841			Ok(Some(T::WeightInfo::provide_judgement(judgements as u32, extra_fields as u32))842				.into())843		}844845		/// Remove an account's identity and sub-account information and slash the deposits.846		///847		/// Payment: Reserved balances from `set_subs` and `set_identity` are slashed and handled by848		/// `Slash`. Verification request deposits are not returned; they should be cancelled849		/// manually using `cancel_request`.850		///851		/// The dispatch origin for this call must match `T::ForceOrigin`.852		///853		/// - `target`: the account whose identity the judgement is upon. This must be an account854		///   with a registered identity.855		///856		/// Emits `IdentityKilled` if successful.857		///858		/// # <weight>859		/// - `O(R + S + X)`.860		/// - One balance-reserve operation.861		/// - `S + 2` storage mutations.862		/// - One event.863		/// # </weight>864		#[pallet::call_index(10)]865		#[pallet::weight(T::WeightInfo::kill_identity(866			T::MaxRegistrars::get(), // R867			T::MaxSubAccounts::get(), // S868			T::MaxAdditionalFields::get(), // X869		))]870		pub fn kill_identity(871			origin: OriginFor<T>,872			target: AccountIdLookupOf<T>,873		) -> DispatchResultWithPostInfo {874			T::ForceOrigin::ensure_origin(origin)?;875876			// Figure out who we're meant to be clearing.877			let target = T::Lookup::lookup(target)?;878			// Grab their deposit (and check that they have one).879			let (subs_deposit, sub_ids) = <SubsOf<T>>::take(&target);880			let id = <IdentityOf<T>>::take(&target).ok_or(Error::<T>::NotNamed)?;881			let deposit = id.total_deposit() + subs_deposit;882			for sub in sub_ids.iter() {883				<SuperOf<T>>::remove(sub);884			}885			// Slash their deposit from them.886			T::Slashed::on_unbalanced(T::Currency::slash_reserved(&target, deposit).0);887888			Self::deposit_event(Event::IdentityKilled { who: target, deposit });889890			Ok(Some(T::WeightInfo::kill_identity(891				id.judgements.len() as u32,      // R892				sub_ids.len() as u32,            // S893				id.info.additional.len() as u32, // X894			))895			.into())896		}897898		/// Add the given account to the sender's subs.899		///900		/// Payment: Balance reserved by a previous `set_subs` call for one sub will be repatriated901		/// to the sender.902		///903		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered904		/// sub identity of `sub`.905		#[pallet::call_index(11)]906		#[pallet::weight(T::WeightInfo::add_sub(T::MaxSubAccounts::get()))]907		pub fn add_sub(908			origin: OriginFor<T>,909			sub: AccountIdLookupOf<T>,910			data: Data,911		) -> DispatchResult {912			let sender = ensure_signed(origin)?;913			let sub = T::Lookup::lookup(sub)?;914			ensure!(IdentityOf::<T>::contains_key(&sender), Error::<T>::NoIdentity);915916			// Check if it's already claimed as sub-identity.917			ensure!(!SuperOf::<T>::contains_key(&sub), Error::<T>::AlreadyClaimed);918919			SubsOf::<T>::try_mutate(&sender, |(ref mut subs_deposit, ref mut sub_ids)| {920				// Ensure there is space and that the deposit is paid.921				ensure!(922					sub_ids.len() < T::MaxSubAccounts::get() as usize,923					Error::<T>::TooManySubAccounts924				);925				let deposit = T::SubAccountDeposit::get();926				T::Currency::reserve(&sender, deposit)?;927928				SuperOf::<T>::insert(&sub, (sender.clone(), data));929				sub_ids.try_push(sub.clone()).expect("sub ids length checked above; qed");930				*subs_deposit = subs_deposit.saturating_add(deposit);931932				Self::deposit_event(Event::SubIdentityAdded { sub, main: sender.clone(), deposit });933				Ok(())934			})935		}936937		/// Alter the associated name of the given sub-account.938		///939		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered940		/// sub identity of `sub`.941		#[pallet::call_index(12)]942		#[pallet::weight(T::WeightInfo::rename_sub(T::MaxSubAccounts::get()))]943		pub fn rename_sub(944			origin: OriginFor<T>,945			sub: AccountIdLookupOf<T>,946			data: Data,947		) -> DispatchResult {948			let sender = ensure_signed(origin)?;949			let sub = T::Lookup::lookup(sub)?;950			ensure!(IdentityOf::<T>::contains_key(&sender), Error::<T>::NoIdentity);951			ensure!(SuperOf::<T>::get(&sub).map_or(false, |x| x.0 == sender), Error::<T>::NotOwned);952			SuperOf::<T>::insert(&sub, (sender, data));953			Ok(())954		}955956		/// Remove the given account from the sender's subs.957		///958		/// Payment: Balance reserved by a previous `set_subs` call for one sub will be repatriated959		/// to the sender.960		///961		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered962		/// sub identity of `sub`.963		#[pallet::call_index(13)]964		#[pallet::weight(T::WeightInfo::remove_sub(T::MaxSubAccounts::get()))]965		pub fn remove_sub(origin: OriginFor<T>, sub: AccountIdLookupOf<T>) -> DispatchResult {966			let sender = ensure_signed(origin)?;967			ensure!(IdentityOf::<T>::contains_key(&sender), Error::<T>::NoIdentity);968			let sub = T::Lookup::lookup(sub)?;969			let (sup, _) = SuperOf::<T>::get(&sub).ok_or(Error::<T>::NotSub)?;970			ensure!(sup == sender, Error::<T>::NotOwned);971			SuperOf::<T>::remove(&sub);972			SubsOf::<T>::mutate(&sup, |(ref mut subs_deposit, ref mut sub_ids)| {973				sub_ids.retain(|x| x != &sub);974				let deposit = T::SubAccountDeposit::get().min(*subs_deposit);975				*subs_deposit -= deposit;976				let err_amount = T::Currency::unreserve(&sender, deposit);977				debug_assert!(err_amount.is_zero());978				Self::deposit_event(Event::SubIdentityRemoved { sub, main: sender, deposit });979			});980			Ok(())981		}982983		/// Remove the sender as a sub-account.984		///985		/// Payment: Balance reserved by a previous `set_subs` call for one sub will be repatriated986		/// to the sender (*not* the original depositor).987		///988		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered989		/// super-identity.990		///991		/// NOTE: This should not normally be used, but is provided in the case that the non-992		/// controller of an account is maliciously registered as a sub-account.993		#[pallet::call_index(14)]994		#[pallet::weight(T::WeightInfo::quit_sub(T::MaxSubAccounts::get()))]995		pub fn quit_sub(origin: OriginFor<T>) -> DispatchResult {996			let sender = ensure_signed(origin)?;997			let (sup, _) = SuperOf::<T>::take(&sender).ok_or(Error::<T>::NotSub)?;998			SubsOf::<T>::mutate(&sup, |(ref mut subs_deposit, ref mut sub_ids)| {999				sub_ids.retain(|x| x != &sender);1000				let deposit = T::SubAccountDeposit::get().min(*subs_deposit);1001				*subs_deposit -= deposit;1002				let _ =1003					T::Currency::repatriate_reserved(&sup, &sender, deposit, BalanceStatus::Free);1004				Self::deposit_event(Event::SubIdentityRevoked {1005					sub: sender,1006					main: sup.clone(),1007					deposit,1008				});1009			});1010			Ok(())1011		}1012	}1013}10141015impl<T: Config> Pallet<T> {1016	/// Get the subs of an account.1017	pub fn subs(who: &T::AccountId) -> Vec<(T::AccountId, Data)> {1018		SubsOf::<T>::get(who)1019			.11020			.into_iter()1021			.filter_map(|a| SuperOf::<T>::get(&a).map(|x| (a, x.1)))1022			.collect()1023	}10241025	/// Check if the account has corresponding identity information by the identity field.1026	pub fn has_identity(who: &T::AccountId, fields: u64) -> bool {1027		IdentityOf::<T>::get(who)1028			.map_or(false, |registration| (registration.info.fields().0.bits() & fields) == fields)1029	}1030}
after · pallets/identity/src/lib.rs
1// 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/>.1617// Original license:18// This file is part of Substrate.1920// Copyright (C) 2019-2022 Parity Technologies (UK) Ltd.21// SPDX-License-Identifier: Apache-2.02223// Licensed under the Apache License, Version 2.0 (the "License");24// you may not use this file except in compliance with the License.25// You may obtain a copy of the License at26//27// 	http://www.apache.org/licenses/LICENSE-2.028//29// Unless required by applicable law or agreed to in writing, software30// distributed under the License is distributed on an "AS IS" BASIS,31// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.32// See the License for the specific language governing permissions and33// limitations under the License.3435//! # Identity Pallet36//!37//! - [`Config`]38//! - [`Call`]39//!40//! ## Overview41//!42//! A federated naming system, allowing for multiple registrars to be added from a specified origin.43//! Registrars can set a fee to provide identity-verification service. Anyone can put forth a44//! proposed identity for a fixed deposit and ask for review by any number of registrars (paying45//! each of their fees). Registrar judgements are given as an `enum`, allowing for sophisticated,46//! multi-tier opinions.47//!48//! Some judgements are identified as *sticky*, which means they cannot be removed except by49//! complete removal of the identity, or by the registrar. Judgements are allowed to represent a50//! portion of funds that have been reserved for the registrar.51//!52//! A super-user can remove accounts and in doing so, slash the deposit.53//!54//! All accounts may also have a limited number of sub-accounts which may be specified by the owner;55//! by definition, these have equivalent ownership and each has an individual name.56//!57//! The number of registrars should be limited, and the deposit made sufficiently large, to ensure58//! no state-bloat attack is viable.59//!60//! ## Interface61//!62//! ### Dispatchable Functions63//!64//! #### For general users65//! * `set_identity` - Set the associated identity of an account; a small deposit is reserved if not66//!   already taken.67//! * `clear_identity` - Remove an account's associated identity; the deposit is returned.68//! * `request_judgement` - Request a judgement from a registrar, paying a fee.69//! * `cancel_request` - Cancel the previous request for a judgement.70//!71//! #### For general users with sub-identities72//! * `set_subs` - Set the sub-accounts of an identity.73//! * `add_sub` - Add a sub-identity to an identity.74//! * `remove_sub` - Remove a sub-identity of an identity.75//! * `rename_sub` - Rename a sub-identity of an identity.76//! * `quit_sub` - Remove a sub-identity of an identity (called by the sub-identity).77//!78//! #### For registrars79//! * `set_fee` - Set the fee required to be paid for a judgement to be given by the registrar.80//! * `set_fields` - Set the fields that a registrar cares about in their judgements.81//! * `provide_judgement` - Provide a judgement to an identity.82//!83//! #### For super-users84//! * `add_registrar` - Add a new registrar to the system.85//! * `kill_identity` - Forcibly remove the associated identity; the deposit is lost.86//!87//! [`Call`]: ./enum.Call.html88//! [`Config`]: ./trait.Config.html8990#![cfg_attr(not(feature = "std"), no_std)]9192mod benchmarking;93#[cfg(test)]94mod tests;95mod types;96pub mod weights;9798use frame_support::traits::{BalanceStatus, Currency, OnUnbalanced, ReservableCurrency};99use sp_runtime::traits::{AppendZerosInput, Hash, Saturating, StaticLookup, Zero};100use sp_std::prelude::*;101pub use weights::WeightInfo;102103pub use pallet::*;104pub use types::{105	Data, IdentityField, IdentityFields, IdentityInfo, Judgement, RegistrarIndex, RegistrarInfo,106	Registration,107};108109pub type BalanceOf<T> =110	<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;111type NegativeImbalanceOf<T> = <<T as Config>::Currency as Currency<112	<T as frame_system::Config>::AccountId,113>>::NegativeImbalance;114type AccountIdLookupOf<T> = <<T as frame_system::Config>::Lookup as StaticLookup>::Source;115116#[frame_support::pallet]117pub mod pallet {118	use super::*;119	use frame_support::pallet_prelude::*;120	use frame_system::pallet_prelude::*;121122	#[pallet::config]123	pub trait Config: frame_system::Config {124		/// The overarching event type.125		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;126127		/// The currency trait.128		type Currency: ReservableCurrency<Self::AccountId>;129130		/// The amount held on deposit for a registered identity131		#[pallet::constant]132		type BasicDeposit: Get<BalanceOf<Self>>;133134		/// The amount held on deposit per additional field for a registered identity.135		#[pallet::constant]136		type FieldDeposit: Get<BalanceOf<Self>>;137138		/// The amount held on deposit for a registered subaccount. This should account for the fact139		/// that one storage item's value will increase by the size of an account ID, and there will140		/// be another trie item whose value is the size of an account ID plus 32 bytes.141		#[pallet::constant]142		type SubAccountDeposit: Get<BalanceOf<Self>>;143144		/// The maximum number of sub-accounts allowed per identified account.145		#[pallet::constant]146		type MaxSubAccounts: Get<u32>;147148		/// Maximum number of additional fields that may be stored in an ID. Needed to bound the I/O149		/// required to access an identity, but can be pretty high.150		#[pallet::constant]151		type MaxAdditionalFields: Get<u32>;152153		/// Maxmimum number of registrars allowed in the system. Needed to bound the complexity154		/// of, e.g., updating judgements.155		#[pallet::constant]156		type MaxRegistrars: Get<u32>;157158		/// What to do with slashed funds.159		type Slashed: OnUnbalanced<NegativeImbalanceOf<Self>>;160161		/// The origin which may forcibly set or remove a name. Root can always do this.162		type ForceOrigin: EnsureOrigin<Self::RuntimeOrigin>;163164		/// The origin which may add or remove registrars. Root can always do this.165		type RegistrarOrigin: EnsureOrigin<Self::RuntimeOrigin>;166167		/// Weight information for extrinsics in this pallet.168		type WeightInfo: WeightInfo;169	}170171	#[pallet::pallet]172	#[pallet::generate_store(pub(super) trait Store)]173	pub struct Pallet<T>(_);174175	/// Information that is pertinent to identify the entity behind an account.176	///177	/// TWOX-NOTE: OK ― `AccountId` is a secure hash.178	#[pallet::storage]179	#[pallet::getter(fn identity)]180	pub type IdentityOf<T: Config> = StorageMap<181		_,182		Twox64Concat,183		T::AccountId,184		Registration<BalanceOf<T>, T::MaxRegistrars, T::MaxAdditionalFields>,185		OptionQuery,186	>;187188	/// The super-identity of an alternative "sub" identity together with its name, within that189	/// context. If the account is not some other account's sub-identity, then just `None`.190	#[pallet::storage]191	#[pallet::getter(fn super_of)]192	pub(super) type SuperOf<T: Config> =193		StorageMap<_, Blake2_128Concat, T::AccountId, (T::AccountId, Data), OptionQuery>;194195	/// Alternative "sub" identities of this account.196	///197	/// The first item is the deposit, the second is a vector of the accounts.198	///199	/// TWOX-NOTE: OK ― `AccountId` is a secure hash.200	#[pallet::storage]201	#[pallet::getter(fn subs_of)]202	pub(super) type SubsOf<T: Config> = StorageMap<203		_,204		Twox64Concat,205		T::AccountId,206		(BalanceOf<T>, BoundedVec<T::AccountId, T::MaxSubAccounts>),207		ValueQuery,208	>;209210	/// The set of registrars. Not expected to get very big as can only be added through a211	/// special origin (likely a council motion).212	///213	/// The index into this can be cast to `RegistrarIndex` to get a valid value.214	#[pallet::storage]215	#[pallet::getter(fn registrars)]216	pub(super) type Registrars<T: Config> = StorageValue<217		_,218		BoundedVec<Option<RegistrarInfo<BalanceOf<T>, T::AccountId>>, T::MaxRegistrars>,219		ValueQuery,220	>;221222	#[pallet::error]223	pub enum Error<T> {224		/// Too many subs-accounts.225		TooManySubAccounts,226		/// Account isn't found.227		NotFound,228		/// Account isn't named.229		NotNamed,230		/// Empty index.231		EmptyIndex,232		/// Fee is changed.233		FeeChanged,234		/// No identity found.235		NoIdentity,236		/// Sticky judgement.237		StickyJudgement,238		/// Judgement given.239		JudgementGiven,240		/// Invalid judgement.241		InvalidJudgement,242		/// The index is invalid.243		InvalidIndex,244		/// The target is invalid.245		InvalidTarget,246		/// Too many additional fields.247		TooManyFields,248		/// Maximum amount of registrars reached. Cannot add any more.249		TooManyRegistrars,250		/// Account ID is already named.251		AlreadyClaimed,252		/// Sender is not a sub-account.253		NotSub,254		/// Sub-account isn't owned by sender.255		NotOwned,256		/// The provided judgement was for a different identity.257		JudgementForDifferentIdentity,258		/// Error that occurs when there is an issue paying for judgement.259		JudgementPaymentFailed,260	}261262	#[pallet::event]263	#[pallet::generate_deposit(pub(super) fn deposit_event)]264	pub enum Event<T: Config> {265		/// A name was set or reset (which will remove all judgements).266		IdentitySet { who: T::AccountId },267		/// A name was cleared, and the given balance returned.268		IdentityCleared {269			who: T::AccountId,270			deposit: BalanceOf<T>,271		},272		/// A name was removed and the given balance slashed.273		IdentityKilled {274			who: T::AccountId,275			deposit: BalanceOf<T>,276		},277		/// A judgement was asked from a registrar.278		JudgementRequested {279			who: T::AccountId,280			registrar_index: RegistrarIndex,281		},282		/// A judgement request was retracted.283		JudgementUnrequested {284			who: T::AccountId,285			registrar_index: RegistrarIndex,286		},287		/// A judgement was given by a registrar.288		JudgementGiven {289			target: T::AccountId,290			registrar_index: RegistrarIndex,291		},292		/// A registrar was added.293		RegistrarAdded { registrar_index: RegistrarIndex },294		/// A sub-identity was added to an identity and the deposit paid.295		SubIdentityAdded {296			sub: T::AccountId,297			main: T::AccountId,298			deposit: BalanceOf<T>,299		},300		/// A sub-identity was removed from an identity and the deposit freed.301		SubIdentityRemoved {302			sub: T::AccountId,303			main: T::AccountId,304			deposit: BalanceOf<T>,305		},306		/// A sub-identity was cleared, and the given deposit repatriated from the307		/// main identity account to the sub-identity account.308		SubIdentityRevoked {309			sub: T::AccountId,310			main: T::AccountId,311			deposit: BalanceOf<T>,312		},313	}314315	#[pallet::call]316	/// Identity pallet declaration.317	impl<T: Config> Pallet<T> {318		/// Add a registrar to the system.319		///320		/// The dispatch origin for this call must be `T::RegistrarOrigin`.321		///322		/// - `account`: the account of the registrar.323		///324		/// Emits `RegistrarAdded` if successful.325		///326		/// # <weight>327		/// - `O(R)` where `R` registrar-count (governance-bounded and code-bounded).328		/// - One storage mutation (codec `O(R)`).329		/// - One event.330		/// # </weight>331		#[pallet::call_index(0)]332		#[pallet::weight(T::WeightInfo::add_registrar(T::MaxRegistrars::get()))]333		pub fn add_registrar(334			origin: OriginFor<T>,335			account: AccountIdLookupOf<T>,336		) -> DispatchResultWithPostInfo {337			T::RegistrarOrigin::ensure_origin(origin)?;338			let account = T::Lookup::lookup(account)?;339340			let (i, registrar_count) = <Registrars<T>>::try_mutate(341				|registrars| -> Result<(RegistrarIndex, usize), DispatchError> {342					registrars343						.try_push(Some(RegistrarInfo {344							account,345							fee: Zero::zero(),346							fields: Default::default(),347						}))348						.map_err(|_| Error::<T>::TooManyRegistrars)?;349					Ok(((registrars.len() - 1) as RegistrarIndex, registrars.len()))350				},351			)?;352353			Self::deposit_event(Event::RegistrarAdded { registrar_index: i });354355			Ok(Some(T::WeightInfo::add_registrar(registrar_count as u32)).into())356		}357358		/// Set an account's identity information and reserve the appropriate deposit.359		///360		/// If the account already has identity information, the deposit is taken as part payment361		/// for the new deposit.362		///363		/// The dispatch origin for this call must be _Signed_.364		///365		/// - `info`: The identity information.366		///367		/// Emits `IdentitySet` if successful.368		///369		/// # <weight>370		/// - `O(X + X' + R)`371		///   - where `X` additional-field-count (deposit-bounded and code-bounded)372		///   - where `R` judgements-count (registrar-count-bounded)373		/// - One balance reserve operation.374		/// - One storage mutation (codec-read `O(X' + R)`, codec-write `O(X + R)`).375		/// - One event.376		/// # </weight>377		#[pallet::call_index(1)]378		#[pallet::weight( T::WeightInfo::set_identity(379			T::MaxRegistrars::get(), // R380			T::MaxAdditionalFields::get(), // X381		))]382		pub fn set_identity(383			origin: OriginFor<T>,384			info: Box<IdentityInfo<T::MaxAdditionalFields>>,385		) -> DispatchResultWithPostInfo {386			let sender = ensure_signed(origin)?;387			let extra_fields = info.additional.len() as u32;388			ensure!(389				extra_fields <= T::MaxAdditionalFields::get(),390				Error::<T>::TooManyFields391			);392			let fd = <BalanceOf<T>>::from(extra_fields) * T::FieldDeposit::get();393394			let mut id = match <IdentityOf<T>>::get(&sender) {395				Some(mut id) => {396					// Only keep non-positive judgements.397					id.judgements.retain(|j| j.1.is_sticky());398					id.info = *info;399					id400				}401				None => Registration {402					info: *info,403					judgements: BoundedVec::default(),404					deposit: Zero::zero(),405				},406			};407408			let old_deposit = id.deposit;409			id.deposit = T::BasicDeposit::get() + fd;410			if id.deposit > old_deposit {411				T::Currency::reserve(&sender, id.deposit - old_deposit)?;412			}413			if old_deposit > id.deposit {414				let err_amount = T::Currency::unreserve(&sender, old_deposit - id.deposit);415				debug_assert!(err_amount.is_zero());416			}417418			let judgements = id.judgements.len();419			<IdentityOf<T>>::insert(&sender, id);420			Self::deposit_event(Event::IdentitySet { who: sender });421422			Ok(Some(T::WeightInfo::set_identity(423				judgements as u32, // R424				extra_fields,      // X425			))426			.into())427		}428429		/// Set the sub-accounts of the sender.430		///431		/// Payment: Any aggregate balance reserved by previous `set_subs` calls will be returned432		/// and an amount `SubAccountDeposit` will be reserved for each item in `subs`.433		///434		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered435		/// identity.436		///437		/// - `subs`: The identity's (new) sub-accounts.438		///439		/// # <weight>440		/// - `O(P + S)`441		///   - where `P` old-subs-count (hard- and deposit-bounded).442		///   - where `S` subs-count (hard- and deposit-bounded).443		/// - At most one balance operations.444		/// - DB:445		///   - `P + S` storage mutations (codec complexity `O(1)`)446		///   - One storage read (codec complexity `O(P)`).447		///   - One storage write (codec complexity `O(S)`).448		///   - One storage-exists (`IdentityOf::contains_key`).449		/// # </weight>450		// TODO: This whole extrinsic screams "not optimized". For example we could451		// filter any overlap between new and old subs, and avoid reading/writing452		// to those values... We could also ideally avoid needing to write to453		// N storage items for N sub accounts. Right now the weight on this function454		// is a large overestimate due to the fact that it could potentially write455		// to 2 x T::MaxSubAccounts::get().456		#[pallet::call_index(2)]457		#[pallet::weight(T::WeightInfo::set_subs_old(T::MaxSubAccounts::get()) // P: Assume max sub accounts removed.458			.saturating_add(T::WeightInfo::set_subs_new(subs.len() as u32)) // S: Assume all subs are new.459		)]460		pub fn set_subs(461			origin: OriginFor<T>,462			subs: Vec<(T::AccountId, Data)>,463		) -> DispatchResultWithPostInfo {464			let sender = ensure_signed(origin)?;465			ensure!(<IdentityOf<T>>::contains_key(&sender), Error::<T>::NotFound);466			ensure!(467				subs.len() <= T::MaxSubAccounts::get() as usize,468				Error::<T>::TooManySubAccounts469			);470471			let (old_deposit, old_ids) = <SubsOf<T>>::get(&sender);472			let new_deposit = T::SubAccountDeposit::get() * <BalanceOf<T>>::from(subs.len() as u32);473474			let not_other_sub = subs475				.iter()476				.filter_map(|i| SuperOf::<T>::get(&i.0))477				.all(|i| i.0 == sender);478			ensure!(not_other_sub, Error::<T>::AlreadyClaimed);479480			if old_deposit < new_deposit {481				T::Currency::reserve(&sender, new_deposit - old_deposit)?;482			} else if old_deposit > new_deposit {483				let err_amount = T::Currency::unreserve(&sender, old_deposit - new_deposit);484				debug_assert!(err_amount.is_zero());485			}486			// do nothing if they're equal.487488			for s in old_ids.iter() {489				<SuperOf<T>>::remove(s);490			}491			let mut ids = BoundedVec::<T::AccountId, T::MaxSubAccounts>::default();492			for (id, name) in subs {493				<SuperOf<T>>::insert(&id, (sender.clone(), name));494				ids.try_push(id)495					.expect("subs length is less than T::MaxSubAccounts; qed");496			}497			let new_subs = ids.len();498499			if ids.is_empty() {500				<SubsOf<T>>::remove(&sender);501			} else {502				<SubsOf<T>>::insert(&sender, (new_deposit, ids));503			}504505			Ok(Some(506				T::WeightInfo::set_subs_old(old_ids.len() as u32) // P: Real number of old accounts removed.507					// S: New subs added508					.saturating_add(T::WeightInfo::set_subs_new(new_subs as u32)),509			)510			.into())511		}512513		/// Clear an account's identity info and all sub-accounts and return all deposits.514		///515		/// Payment: All reserved balances on the account are returned.516		///517		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered518		/// identity.519		///520		/// Emits `IdentityCleared` if successful.521		///522		/// # <weight>523		/// - `O(R + S + X)`524		///   - where `R` registrar-count (governance-bounded).525		///   - where `S` subs-count (hard- and deposit-bounded).526		///   - where `X` additional-field-count (deposit-bounded and code-bounded).527		/// - One balance-unreserve operation.528		/// - `2` storage reads and `S + 2` storage deletions.529		/// - One event.530		/// # </weight>531		#[pallet::call_index(3)]532		#[pallet::weight(T::WeightInfo::clear_identity(533			T::MaxRegistrars::get(), // R534			T::MaxSubAccounts::get(), // S535			T::MaxAdditionalFields::get(), // X536		))]537		pub fn clear_identity(origin: OriginFor<T>) -> DispatchResultWithPostInfo {538			let sender = ensure_signed(origin)?;539540			let (subs_deposit, sub_ids) = <SubsOf<T>>::take(&sender);541			let id = <IdentityOf<T>>::take(&sender).ok_or(Error::<T>::NotNamed)?;542			let deposit = id.total_deposit() + subs_deposit;543			for sub in sub_ids.iter() {544				<SuperOf<T>>::remove(sub);545			}546547			let err_amount = T::Currency::unreserve(&sender, deposit);548			debug_assert!(err_amount.is_zero());549550			Self::deposit_event(Event::IdentityCleared {551				who: sender,552				deposit,553			});554555			Ok(Some(T::WeightInfo::clear_identity(556				id.judgements.len() as u32,      // R557				sub_ids.len() as u32,            // S558				id.info.additional.len() as u32, // X559			))560			.into())561		}562563		/// Request a judgement from a registrar.564		///565		/// Payment: At most `max_fee` will be reserved for payment to the registrar if judgement566		/// given.567		///568		/// The dispatch origin for this call must be _Signed_ and the sender must have a569		/// registered identity.570		///571		/// - `reg_index`: The index of the registrar whose judgement is requested.572		/// - `max_fee`: The maximum fee that may be paid. This should just be auto-populated as:573		///574		/// ```nocompile575		/// Self::registrars().get(reg_index).unwrap().fee576		/// ```577		///578		/// Emits `JudgementRequested` if successful.579		///580		/// # <weight>581		/// - `O(R + X)`.582		/// - One balance-reserve operation.583		/// - Storage: 1 read `O(R)`, 1 mutate `O(X + R)`.584		/// - One event.585		/// # </weight>586		#[pallet::call_index(4)]587		#[pallet::weight(T::WeightInfo::request_judgement(588			T::MaxRegistrars::get(), // R589			T::MaxAdditionalFields::get(), // X590		))]591		pub fn request_judgement(592			origin: OriginFor<T>,593			#[pallet::compact] reg_index: RegistrarIndex,594			#[pallet::compact] max_fee: BalanceOf<T>,595		) -> DispatchResultWithPostInfo {596			let sender = ensure_signed(origin)?;597			let registrars = <Registrars<T>>::get();598			let registrar = registrars599				.get(reg_index as usize)600				.and_then(Option::as_ref)601				.ok_or(Error::<T>::EmptyIndex)?;602			ensure!(max_fee >= registrar.fee, Error::<T>::FeeChanged);603			let mut id = <IdentityOf<T>>::get(&sender).ok_or(Error::<T>::NoIdentity)?;604605			let item = (reg_index, Judgement::FeePaid(registrar.fee));606			match id.judgements.binary_search_by_key(&reg_index, |x| x.0) {607				Ok(i) => {608					if id.judgements[i].1.is_sticky() {609						return Err(Error::<T>::StickyJudgement.into());610					} else {611						id.judgements[i] = item612					}613				}614				Err(i) => id615					.judgements616					.try_insert(i, item)617					.map_err(|_| Error::<T>::TooManyRegistrars)?,618			}619620			T::Currency::reserve(&sender, registrar.fee)?;621622			let judgements = id.judgements.len();623			let extra_fields = id.info.additional.len();624			<IdentityOf<T>>::insert(&sender, id);625626			Self::deposit_event(Event::JudgementRequested {627				who: sender,628				registrar_index: reg_index,629			});630631			Ok(Some(T::WeightInfo::request_judgement(632				judgements as u32,633				extra_fields as u32,634			))635			.into())636		}637638		/// Cancel a previous request.639		///640		/// Payment: A previously reserved deposit is returned on success.641		///642		/// The dispatch origin for this call must be _Signed_ and the sender must have a643		/// registered identity.644		///645		/// - `reg_index`: The index of the registrar whose judgement is no longer requested.646		///647		/// Emits `JudgementUnrequested` if successful.648		///649		/// # <weight>650		/// - `O(R + X)`.651		/// - One balance-reserve operation.652		/// - One storage mutation `O(R + X)`.653		/// - One event654		/// # </weight>655		#[pallet::call_index(5)]656		#[pallet::weight(T::WeightInfo::cancel_request(657			T::MaxRegistrars::get(), // R658			T::MaxAdditionalFields::get(), // X659		))]660		pub fn cancel_request(661			origin: OriginFor<T>,662			reg_index: RegistrarIndex,663		) -> DispatchResultWithPostInfo {664			let sender = ensure_signed(origin)?;665			let mut id = <IdentityOf<T>>::get(&sender).ok_or(Error::<T>::NoIdentity)?;666667			let pos = id668				.judgements669				.binary_search_by_key(&reg_index, |x| x.0)670				.map_err(|_| Error::<T>::NotFound)?;671			let fee = if let Judgement::FeePaid(fee) = id.judgements.remove(pos).1 {672				fee673			} else {674				return Err(Error::<T>::JudgementGiven.into());675			};676677			let err_amount = T::Currency::unreserve(&sender, fee);678			debug_assert!(err_amount.is_zero());679			let judgements = id.judgements.len();680			let extra_fields = id.info.additional.len();681			<IdentityOf<T>>::insert(&sender, id);682683			Self::deposit_event(Event::JudgementUnrequested {684				who: sender,685				registrar_index: reg_index,686			});687688			Ok(Some(T::WeightInfo::cancel_request(689				judgements as u32,690				extra_fields as u32,691			))692			.into())693		}694695		/// Set the fee required for a judgement to be requested from a registrar.696		///697		/// The dispatch origin for this call must be _Signed_ and the sender must be the account698		/// of the registrar whose index is `index`.699		///700		/// - `index`: the index of the registrar whose fee is to be set.701		/// - `fee`: the new fee.702		///703		/// # <weight>704		/// - `O(R)`.705		/// - One storage mutation `O(R)`.706		/// - Benchmark: 7.315 + R * 0.329 µs (min squares analysis)707		/// # </weight>708		#[pallet::call_index(6)]709		#[pallet::weight(T::WeightInfo::set_fee(T::MaxRegistrars::get()))] // R710		pub fn set_fee(711			origin: OriginFor<T>,712			#[pallet::compact] index: RegistrarIndex,713			#[pallet::compact] fee: BalanceOf<T>,714		) -> DispatchResultWithPostInfo {715			let who = ensure_signed(origin)?;716717			let registrars = <Registrars<T>>::mutate(|rs| -> Result<usize, DispatchError> {718				rs.get_mut(index as usize)719					.and_then(|x| x.as_mut())720					.and_then(|r| {721						if r.account == who {722							r.fee = fee;723							Some(())724						} else {725							None726						}727					})728					.ok_or_else(|| DispatchError::from(Error::<T>::InvalidIndex))?;729				Ok(rs.len())730			})?;731			Ok(Some(T::WeightInfo::set_fee(registrars as u32)).into()) // R732		}733734		/// Change the account associated with a registrar.735		///736		/// The dispatch origin for this call must be _Signed_ and the sender must be the account737		/// of the registrar whose index is `index`.738		///739		/// - `index`: the index of the registrar whose fee is to be set.740		/// - `new`: the new account ID.741		///742		/// # <weight>743		/// - `O(R)`.744		/// - One storage mutation `O(R)`.745		/// - Benchmark: 8.823 + R * 0.32 µs (min squares analysis)746		/// # </weight>747		#[pallet::call_index(7)]748		#[pallet::weight(T::WeightInfo::set_account_id(T::MaxRegistrars::get()))] // R749		pub fn set_account_id(750			origin: OriginFor<T>,751			#[pallet::compact] index: RegistrarIndex,752			new: AccountIdLookupOf<T>,753		) -> DispatchResultWithPostInfo {754			let who = ensure_signed(origin)?;755			let new = T::Lookup::lookup(new)?;756757			let registrars = <Registrars<T>>::mutate(|rs| -> Result<usize, DispatchError> {758				rs.get_mut(index as usize)759					.and_then(|x| x.as_mut())760					.and_then(|r| {761						if r.account == who {762							r.account = new;763							Some(())764						} else {765							None766						}767					})768					.ok_or_else(|| DispatchError::from(Error::<T>::InvalidIndex))?;769				Ok(rs.len())770			})?;771			Ok(Some(T::WeightInfo::set_account_id(registrars as u32)).into()) // R772		}773774		/// Set the field information for a registrar.775		///776		/// The dispatch origin for this call must be _Signed_ and the sender must be the account777		/// of the registrar whose index is `index`.778		///779		/// - `index`: the index of the registrar whose fee is to be set.780		/// - `fields`: the fields that the registrar concerns themselves with.781		///782		/// # <weight>783		/// - `O(R)`.784		/// - One storage mutation `O(R)`.785		/// - Benchmark: 7.464 + R * 0.325 µs (min squares analysis)786		/// # </weight>787		#[pallet::call_index(8)]788		#[pallet::weight(T::WeightInfo::set_fields(T::MaxRegistrars::get()))] // R789		pub fn set_fields(790			origin: OriginFor<T>,791			#[pallet::compact] index: RegistrarIndex,792			fields: IdentityFields,793		) -> DispatchResultWithPostInfo {794			let who = ensure_signed(origin)?;795796			let registrars = <Registrars<T>>::mutate(|rs| -> Result<usize, DispatchError> {797				rs.get_mut(index as usize)798					.and_then(|x| x.as_mut())799					.and_then(|r| {800						if r.account == who {801							r.fields = fields;802							Some(())803						} else {804							None805						}806					})807					.ok_or_else(|| DispatchError::from(Error::<T>::InvalidIndex))?;808				Ok(rs.len())809			})?;810			Ok(Some(T::WeightInfo::set_fields(811				registrars as u32, // R812			))813			.into())814		}815816		/// Provide a judgement for an account's identity.817		///818		/// The dispatch origin for this call must be _Signed_ and the sender must be the account819		/// of the registrar whose index is `reg_index`.820		///821		/// - `reg_index`: the index of the registrar whose judgement is being made.822		/// - `target`: the account whose identity the judgement is upon. This must be an account823		///   with a registered identity.824		/// - `judgement`: the judgement of the registrar of index `reg_index` about `target`.825		/// - `identity`: The hash of the [`IdentityInfo`] for that the judgement is provided.826		///827		/// Emits `JudgementGiven` if successful.828		///829		/// # <weight>830		/// - `O(R + X)`.831		/// - One balance-transfer operation.832		/// - Up to one account-lookup operation.833		/// - Storage: 1 read `O(R)`, 1 mutate `O(R + X)`.834		/// - One event.835		/// # </weight>836		#[pallet::call_index(9)]837		#[pallet::weight(T::WeightInfo::provide_judgement(838			T::MaxRegistrars::get(), // R839			T::MaxAdditionalFields::get(), // X840		))]841		pub fn provide_judgement(842			origin: OriginFor<T>,843			#[pallet::compact] reg_index: RegistrarIndex,844			target: AccountIdLookupOf<T>,845			judgement: Judgement<BalanceOf<T>>,846			identity: T::Hash,847		) -> DispatchResultWithPostInfo {848			let sender = ensure_signed(origin)?;849			let target = T::Lookup::lookup(target)?;850			ensure!(!judgement.has_deposit(), Error::<T>::InvalidJudgement);851			<Registrars<T>>::get()852				.get(reg_index as usize)853				.and_then(Option::as_ref)854				.filter(|r| r.account == sender)855				.ok_or(Error::<T>::InvalidIndex)?;856			let mut id = <IdentityOf<T>>::get(&target).ok_or(Error::<T>::InvalidTarget)?;857858			if T::Hashing::hash_of(&id.info) != identity {859				return Err(Error::<T>::JudgementForDifferentIdentity.into());860			}861862			let item = (reg_index, judgement);863			match id.judgements.binary_search_by_key(&reg_index, |x| x.0) {864				Ok(position) => {865					if let Judgement::FeePaid(fee) = id.judgements[position].1 {866						T::Currency::repatriate_reserved(867							&target,868							&sender,869							fee,870							BalanceStatus::Free,871						)872						.map_err(|_| Error::<T>::JudgementPaymentFailed)?;873					}874					id.judgements[position] = item875				}876				Err(position) => id877					.judgements878					.try_insert(position, item)879					.map_err(|_| Error::<T>::TooManyRegistrars)?,880			}881882			let judgements = id.judgements.len();883			let extra_fields = id.info.additional.len();884			<IdentityOf<T>>::insert(&target, id);885			Self::deposit_event(Event::JudgementGiven {886				target,887				registrar_index: reg_index,888			});889890			Ok(Some(T::WeightInfo::provide_judgement(891				judgements as u32,892				extra_fields as u32,893			))894			.into())895		}896897		/// Remove an account's identity and sub-account information and slash the deposits.898		///899		/// Payment: Reserved balances from `set_subs` and `set_identity` are slashed and handled by900		/// `Slash`. Verification request deposits are not returned; they should be cancelled901		/// manually using `cancel_request`.902		///903		/// The dispatch origin for this call must match `T::ForceOrigin`.904		///905		/// - `target`: the account whose identity the judgement is upon. This must be an account906		///   with a registered identity.907		///908		/// Emits `IdentityKilled` if successful.909		///910		/// # <weight>911		/// - `O(R + S + X)`.912		/// - One balance-reserve operation.913		/// - `S + 2` storage mutations.914		/// - One event.915		/// # </weight>916		#[pallet::call_index(10)]917		#[pallet::weight(T::WeightInfo::kill_identity(918			T::MaxRegistrars::get(), // R919			T::MaxSubAccounts::get(), // S920			T::MaxAdditionalFields::get(), // X921		))]922		pub fn kill_identity(923			origin: OriginFor<T>,924			target: AccountIdLookupOf<T>,925		) -> DispatchResultWithPostInfo {926			T::ForceOrigin::ensure_origin(origin)?;927928			// Figure out who we're meant to be clearing.929			let target = T::Lookup::lookup(target)?;930			// Grab their deposit (and check that they have one).931			let (subs_deposit, sub_ids) = <SubsOf<T>>::take(&target);932			let id = <IdentityOf<T>>::take(&target).ok_or(Error::<T>::NotNamed)?;933			let deposit = id.total_deposit() + subs_deposit;934			for sub in sub_ids.iter() {935				<SuperOf<T>>::remove(sub);936			}937			// Slash their deposit from them.938			T::Slashed::on_unbalanced(T::Currency::slash_reserved(&target, deposit).0);939940			Self::deposit_event(Event::IdentityKilled {941				who: target,942				deposit,943			});944945			Ok(Some(T::WeightInfo::kill_identity(946				id.judgements.len() as u32,      // R947				sub_ids.len() as u32,            // S948				id.info.additional.len() as u32, // X949			))950			.into())951		}952953		/// Add the given account to the sender's subs.954		///955		/// Payment: Balance reserved by a previous `set_subs` call for one sub will be repatriated956		/// to the sender.957		///958		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered959		/// sub identity of `sub`.960		#[pallet::call_index(11)]961		#[pallet::weight(T::WeightInfo::add_sub(T::MaxSubAccounts::get()))]962		pub fn add_sub(963			origin: OriginFor<T>,964			sub: AccountIdLookupOf<T>,965			data: Data,966		) -> DispatchResult {967			let sender = ensure_signed(origin)?;968			let sub = T::Lookup::lookup(sub)?;969			ensure!(970				IdentityOf::<T>::contains_key(&sender),971				Error::<T>::NoIdentity972			);973974			// Check if it's already claimed as sub-identity.975			ensure!(976				!SuperOf::<T>::contains_key(&sub),977				Error::<T>::AlreadyClaimed978			);979980			SubsOf::<T>::try_mutate(&sender, |(ref mut subs_deposit, ref mut sub_ids)| {981				// Ensure there is space and that the deposit is paid.982				ensure!(983					sub_ids.len() < T::MaxSubAccounts::get() as usize,984					Error::<T>::TooManySubAccounts985				);986				let deposit = T::SubAccountDeposit::get();987				T::Currency::reserve(&sender, deposit)?;988989				SuperOf::<T>::insert(&sub, (sender.clone(), data));990				sub_ids991					.try_push(sub.clone())992					.expect("sub ids length checked above; qed");993				*subs_deposit = subs_deposit.saturating_add(deposit);994995				Self::deposit_event(Event::SubIdentityAdded {996					sub,997					main: sender.clone(),998					deposit,999				});1000				Ok(())1001			})1002		}10031004		/// Alter the associated name of the given sub-account.1005		///1006		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered1007		/// sub identity of `sub`.1008		#[pallet::call_index(12)]1009		#[pallet::weight(T::WeightInfo::rename_sub(T::MaxSubAccounts::get()))]1010		pub fn rename_sub(1011			origin: OriginFor<T>,1012			sub: AccountIdLookupOf<T>,1013			data: Data,1014		) -> DispatchResult {1015			let sender = ensure_signed(origin)?;1016			let sub = T::Lookup::lookup(sub)?;1017			ensure!(1018				IdentityOf::<T>::contains_key(&sender),1019				Error::<T>::NoIdentity1020			);1021			ensure!(1022				SuperOf::<T>::get(&sub).map_or(false, |x| x.0 == sender),1023				Error::<T>::NotOwned1024			);1025			SuperOf::<T>::insert(&sub, (sender, data));1026			Ok(())1027		}10281029		/// Remove the given account from the sender's subs.1030		///1031		/// Payment: Balance reserved by a previous `set_subs` call for one sub will be repatriated1032		/// to the sender.1033		///1034		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered1035		/// sub identity of `sub`.1036		#[pallet::call_index(13)]1037		#[pallet::weight(T::WeightInfo::remove_sub(T::MaxSubAccounts::get()))]1038		pub fn remove_sub(origin: OriginFor<T>, sub: AccountIdLookupOf<T>) -> DispatchResult {1039			let sender = ensure_signed(origin)?;1040			ensure!(1041				IdentityOf::<T>::contains_key(&sender),1042				Error::<T>::NoIdentity1043			);1044			let sub = T::Lookup::lookup(sub)?;1045			let (sup, _) = SuperOf::<T>::get(&sub).ok_or(Error::<T>::NotSub)?;1046			ensure!(sup == sender, Error::<T>::NotOwned);1047			SuperOf::<T>::remove(&sub);1048			SubsOf::<T>::mutate(&sup, |(ref mut subs_deposit, ref mut sub_ids)| {1049				sub_ids.retain(|x| x != &sub);1050				let deposit = T::SubAccountDeposit::get().min(*subs_deposit);1051				*subs_deposit -= deposit;1052				let err_amount = T::Currency::unreserve(&sender, deposit);1053				debug_assert!(err_amount.is_zero());1054				Self::deposit_event(Event::SubIdentityRemoved {1055					sub,1056					main: sender,1057					deposit,1058				});1059			});1060			Ok(())1061		}10621063		/// Remove the sender as a sub-account.1064		///1065		/// Payment: Balance reserved by a previous `set_subs` call for one sub will be repatriated1066		/// to the sender (*not* the original depositor).1067		///1068		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered1069		/// super-identity.1070		///1071		/// NOTE: This should not normally be used, but is provided in the case that the non-1072		/// controller of an account is maliciously registered as a sub-account.1073		#[pallet::call_index(14)]1074		#[pallet::weight(T::WeightInfo::quit_sub(T::MaxSubAccounts::get()))]1075		pub fn quit_sub(origin: OriginFor<T>) -> DispatchResult {1076			let sender = ensure_signed(origin)?;1077			let (sup, _) = SuperOf::<T>::take(&sender).ok_or(Error::<T>::NotSub)?;1078			SubsOf::<T>::mutate(&sup, |(ref mut subs_deposit, ref mut sub_ids)| {1079				sub_ids.retain(|x| x != &sender);1080				let deposit = T::SubAccountDeposit::get().min(*subs_deposit);1081				*subs_deposit -= deposit;1082				let _ =1083					T::Currency::repatriate_reserved(&sup, &sender, deposit, BalanceStatus::Free);1084				Self::deposit_event(Event::SubIdentityRevoked {1085					sub: sender,1086					main: sup.clone(),1087					deposit,1088				});1089			});1090			Ok(())1091		}1092	}1093}10941095impl<T: Config> Pallet<T> {1096	/// Get the subs of an account.1097	pub fn subs(who: &T::AccountId) -> Vec<(T::AccountId, Data)> {1098		SubsOf::<T>::get(who)1099			.11100			.into_iter()1101			.filter_map(|a| SuperOf::<T>::get(&a).map(|x| (a, x.1)))1102			.collect()1103	}11041105	/// Check if the account has corresponding identity information by the identity field.1106	pub fn has_identity(who: &T::AccountId, fields: u64) -> bool {1107		IdentityOf::<T>::get(who).map_or(false, |registration| {1108			(registration.info.fields().0.bits() & fields) == fields1109		})1110	}1111}
modifiedpallets/identity/src/tests.rsdiffbeforeafterboth
--- a/pallets/identity/src/tests.rs
+++ b/pallets/identity/src/tests.rs
@@ -135,7 +135,9 @@
 }
 
 pub fn new_test_ext() -> sp_io::TestExternalities {
-	let mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
+	let mut t = frame_system::GenesisConfig::default()
+		.build_storage::<Test>()
+		.unwrap();
 	pallet_balances::GenesisConfig::<Test> {
 		balances: vec![(1, 10), (2, 10), (3, 10), (10, 100), (20, 100), (30, 100)],
 	}
@@ -155,7 +157,12 @@
 fn twenty() -> IdentityInfo<MaxAdditionalFields> {
 	IdentityInfo {
 		display: Data::Raw(b"twenty".to_vec().try_into().unwrap()),
-		legal: Data::Raw(b"The Right Ordinal Twenty, Esq.".to_vec().try_into().unwrap()),
+		legal: Data::Raw(
+			b"The Right Ordinal Twenty, Esq."
+				.to_vec()
+				.try_into()
+				.unwrap(),
+		),
 		..Default::default()
 	}
 }
@@ -170,7 +177,10 @@
 			Error::<Test>::NoIdentity
 		);
 
-		assert_ok!(Identity::set_identity(RuntimeOrigin::signed(10), Box::new(ten())));
+		assert_ok!(Identity::set_identity(
+			RuntimeOrigin::signed(10),
+			Box::new(ten())
+		));
 
 		// first sub account
 		assert_ok!(Identity::add_sub(RuntimeOrigin::signed(10), 1, data(1)));
@@ -215,8 +225,14 @@
 	new_test_ext().execute_with(|| {
 		let data = |x| Data::Raw(vec![x; 1].try_into().unwrap());
 
-		assert_ok!(Identity::set_identity(RuntimeOrigin::signed(10), Box::new(ten())));
-		assert_ok!(Identity::set_identity(RuntimeOrigin::signed(20), Box::new(twenty())));
+		assert_ok!(Identity::set_identity(
+			RuntimeOrigin::signed(10),
+			Box::new(ten())
+		));
+		assert_ok!(Identity::set_identity(
+			RuntimeOrigin::signed(20),
+			Box::new(twenty())
+		));
 
 		// 10 claims 1 as a subaccount
 		assert_ok!(Identity::add_sub(RuntimeOrigin::signed(10), 1, data(1)));
@@ -258,7 +274,11 @@
 		assert_ok!(Identity::set_fields(RuntimeOrigin::signed(3), 0, fields));
 		assert_eq!(
 			Identity::registrars(),
-			vec![Some(RegistrarInfo { account: 3, fee: 10, fields })]
+			vec![Some(RegistrarInfo {
+				account: 3,
+				fee: 10,
+				fields
+			})]
 		);
 	});
 }
@@ -283,15 +303,30 @@
 		assert_ok!(Identity::add_registrar(RuntimeOrigin::signed(1), 3));
 		assert_ok!(Identity::set_fee(RuntimeOrigin::signed(3), 0, 10));
 		let mut three_fields = ten();
-		three_fields.additional.try_push(Default::default()).unwrap();
-		three_fields.additional.try_push(Default::default()).unwrap();
-		assert!(three_fields.additional.try_push(Default::default()).is_err());
-		assert_ok!(Identity::set_identity(RuntimeOrigin::signed(10), Box::new(ten())));
+		three_fields
+			.additional
+			.try_push(Default::default())
+			.unwrap();
+		three_fields
+			.additional
+			.try_push(Default::default())
+			.unwrap();
+		assert!(three_fields
+			.additional
+			.try_push(Default::default())
+			.is_err());
+		assert_ok!(Identity::set_identity(
+			RuntimeOrigin::signed(10),
+			Box::new(ten())
+		));
 		assert_eq!(Identity::identity(10).unwrap().info, ten());
 		assert_eq!(Balances::free_balance(10), 90);
 		assert_ok!(Identity::clear_identity(RuntimeOrigin::signed(10)));
 		assert_eq!(Balances::free_balance(10), 100);
-		assert_noop!(Identity::clear_identity(RuntimeOrigin::signed(10)), Error::<Test>::NotNamed);
+		assert_noop!(
+			Identity::clear_identity(RuntimeOrigin::signed(10)),
+			Error::<Test>::NotNamed
+		);
 	});
 }
 
@@ -321,7 +356,10 @@
 			Error::<Test>::InvalidTarget
 		);
 
-		assert_ok!(Identity::set_identity(RuntimeOrigin::signed(10), Box::new(ten())));
+		assert_ok!(Identity::set_identity(
+			RuntimeOrigin::signed(10),
+			Box::new(ten())
+		));
 		assert_noop!(
 			Identity::provide_judgement(
 				RuntimeOrigin::signed(3),
@@ -363,7 +401,10 @@
 			Judgement::Reasonable,
 			identity_hash
 		));
-		assert_eq!(Identity::identity(10).unwrap().judgements, vec![(0, Judgement::Reasonable)]);
+		assert_eq!(
+			Identity::identity(10).unwrap().judgements,
+			vec![(0, Judgement::Reasonable)]
+		);
 	});
 }
 
@@ -371,7 +412,10 @@
 fn clearing_judgement_should_work() {
 	new_test_ext().execute_with(|| {
 		assert_ok!(Identity::add_registrar(RuntimeOrigin::signed(1), 3));
-		assert_ok!(Identity::set_identity(RuntimeOrigin::signed(10), Box::new(ten())));
+		assert_ok!(Identity::set_identity(
+			RuntimeOrigin::signed(10),
+			Box::new(ten())
+		));
 		assert_ok!(Identity::provide_judgement(
 			RuntimeOrigin::signed(3),
 			0,
@@ -387,8 +431,14 @@
 #[test]
 fn killing_slashing_should_work() {
 	new_test_ext().execute_with(|| {
-		assert_ok!(Identity::set_identity(RuntimeOrigin::signed(10), Box::new(ten())));
-		assert_noop!(Identity::kill_identity(RuntimeOrigin::signed(1), 10), BadOrigin);
+		assert_ok!(Identity::set_identity(
+			RuntimeOrigin::signed(10),
+			Box::new(ten())
+		));
+		assert_noop!(
+			Identity::kill_identity(RuntimeOrigin::signed(1), 10),
+			BadOrigin
+		);
 		assert_ok!(Identity::kill_identity(RuntimeOrigin::signed(2), 10));
 		assert_eq!(Identity::identity(10), None);
 		assert_eq!(Balances::free_balance(10), 90);
@@ -408,28 +458,52 @@
 			Error::<Test>::NotFound
 		);
 
-		assert_ok!(Identity::set_identity(RuntimeOrigin::signed(10), Box::new(ten())));
+		assert_ok!(Identity::set_identity(
+			RuntimeOrigin::signed(10),
+			Box::new(ten())
+		));
 		assert_ok!(Identity::set_subs(RuntimeOrigin::signed(10), subs.clone()));
 		assert_eq!(Balances::free_balance(10), 80);
 		assert_eq!(Identity::subs_of(10), (10, vec![20].try_into().unwrap()));
-		assert_eq!(Identity::super_of(20), Some((10, Data::Raw(vec![40; 1].try_into().unwrap()))));
+		assert_eq!(
+			Identity::super_of(20),
+			Some((10, Data::Raw(vec![40; 1].try_into().unwrap())))
+		);
 
 		// push another item and re-set it.
 		subs.push((30, Data::Raw(vec![50; 1].try_into().unwrap())));
 		assert_ok!(Identity::set_subs(RuntimeOrigin::signed(10), subs.clone()));
 		assert_eq!(Balances::free_balance(10), 70);
-		assert_eq!(Identity::subs_of(10), (20, vec![20, 30].try_into().unwrap()));
-		assert_eq!(Identity::super_of(20), Some((10, Data::Raw(vec![40; 1].try_into().unwrap()))));
-		assert_eq!(Identity::super_of(30), Some((10, Data::Raw(vec![50; 1].try_into().unwrap()))));
+		assert_eq!(
+			Identity::subs_of(10),
+			(20, vec![20, 30].try_into().unwrap())
+		);
+		assert_eq!(
+			Identity::super_of(20),
+			Some((10, Data::Raw(vec![40; 1].try_into().unwrap())))
+		);
+		assert_eq!(
+			Identity::super_of(30),
+			Some((10, Data::Raw(vec![50; 1].try_into().unwrap())))
+		);
 
 		// switch out one of the items and re-set.
 		subs[0] = (40, Data::Raw(vec![60; 1].try_into().unwrap()));
 		assert_ok!(Identity::set_subs(RuntimeOrigin::signed(10), subs.clone()));
 		assert_eq!(Balances::free_balance(10), 70); // no change in the balance
-		assert_eq!(Identity::subs_of(10), (20, vec![40, 30].try_into().unwrap()));
+		assert_eq!(
+			Identity::subs_of(10),
+			(20, vec![40, 30].try_into().unwrap())
+		);
 		assert_eq!(Identity::super_of(20), None);
-		assert_eq!(Identity::super_of(30), Some((10, Data::Raw(vec![50; 1].try_into().unwrap()))));
-		assert_eq!(Identity::super_of(40), Some((10, Data::Raw(vec![60; 1].try_into().unwrap()))));
+		assert_eq!(
+			Identity::super_of(30),
+			Some((10, Data::Raw(vec![50; 1].try_into().unwrap())))
+		);
+		assert_eq!(
+			Identity::super_of(40),
+			Some((10, Data::Raw(vec![60; 1].try_into().unwrap())))
+		);
 
 		// clear
 		assert_ok!(Identity::set_subs(RuntimeOrigin::signed(10), vec![]));
@@ -449,7 +523,10 @@
 #[test]
 fn clearing_account_should_remove_subaccounts_and_refund() {
 	new_test_ext().execute_with(|| {
-		assert_ok!(Identity::set_identity(RuntimeOrigin::signed(10), Box::new(ten())));
+		assert_ok!(Identity::set_identity(
+			RuntimeOrigin::signed(10),
+			Box::new(ten())
+		));
 		assert_ok!(Identity::set_subs(
 			RuntimeOrigin::signed(10),
 			vec![(20, Data::Raw(vec![40; 1].try_into().unwrap()))]
@@ -463,7 +540,10 @@
 #[test]
 fn killing_account_should_remove_subaccounts_and_not_refund() {
 	new_test_ext().execute_with(|| {
-		assert_ok!(Identity::set_identity(RuntimeOrigin::signed(10), Box::new(ten())));
+		assert_ok!(Identity::set_identity(
+			RuntimeOrigin::signed(10),
+			Box::new(ten())
+		));
 		assert_ok!(Identity::set_subs(
 			RuntimeOrigin::signed(10),
 			vec![(20, Data::Raw(vec![40; 1].try_into().unwrap()))]
@@ -483,8 +563,15 @@
 			Identity::cancel_request(RuntimeOrigin::signed(10), 0),
 			Error::<Test>::NoIdentity
 		);
-		assert_ok!(Identity::set_identity(RuntimeOrigin::signed(10), Box::new(ten())));
-		assert_ok!(Identity::request_judgement(RuntimeOrigin::signed(10), 0, 10));
+		assert_ok!(Identity::set_identity(
+			RuntimeOrigin::signed(10),
+			Box::new(ten())
+		));
+		assert_ok!(Identity::request_judgement(
+			RuntimeOrigin::signed(10),
+			0,
+			10
+		));
 		assert_ok!(Identity::cancel_request(RuntimeOrigin::signed(10), 0));
 		assert_eq!(Balances::free_balance(10), 90);
 		assert_noop!(
@@ -511,12 +598,19 @@
 	new_test_ext().execute_with(|| {
 		assert_ok!(Identity::add_registrar(RuntimeOrigin::signed(1), 3));
 		assert_ok!(Identity::set_fee(RuntimeOrigin::signed(3), 0, 10));
-		assert_ok!(Identity::set_identity(RuntimeOrigin::signed(10), Box::new(ten())));
+		assert_ok!(Identity::set_identity(
+			RuntimeOrigin::signed(10),
+			Box::new(ten())
+		));
 		assert_noop!(
 			Identity::request_judgement(RuntimeOrigin::signed(10), 0, 9),
 			Error::<Test>::FeeChanged
 		);
-		assert_ok!(Identity::request_judgement(RuntimeOrigin::signed(10), 0, 10));
+		assert_ok!(Identity::request_judgement(
+			RuntimeOrigin::signed(10),
+			0,
+			10
+		));
 		// 10 for the judgement request, 10 for the identity.
 		assert_eq!(Balances::free_balance(10), 80);
 
@@ -543,7 +637,11 @@
 
 		// Requesting from a second registrar still works.
 		assert_ok!(Identity::add_registrar(RuntimeOrigin::signed(1), 4));
-		assert_ok!(Identity::request_judgement(RuntimeOrigin::signed(10), 1, 10));
+		assert_ok!(Identity::request_judgement(
+			RuntimeOrigin::signed(10),
+			1,
+			10
+		));
 
 		// Re-requesting after the judgement has been reduced works.
 		assert_ok!(Identity::provide_judgement(
@@ -553,7 +651,11 @@
 			Judgement::OutOfDate,
 			BlakeTwo256::hash_of(&ten())
 		));
-		assert_ok!(Identity::request_judgement(RuntimeOrigin::signed(10), 0, 10));
+		assert_ok!(Identity::request_judgement(
+			RuntimeOrigin::signed(10),
+			0,
+			10
+		));
 	});
 }
 
@@ -562,8 +664,15 @@
 	new_test_ext().execute_with(|| {
 		assert_ok!(Identity::add_registrar(RuntimeOrigin::signed(1), 3));
 		assert_ok!(Identity::set_fee(RuntimeOrigin::signed(3), 0, 10));
-		assert_ok!(Identity::set_identity(RuntimeOrigin::signed(10), Box::new(ten())));
-		assert_ok!(Identity::request_judgement(RuntimeOrigin::signed(10), 0, 10));
+		assert_ok!(Identity::set_identity(
+			RuntimeOrigin::signed(10),
+			Box::new(ten())
+		));
+		assert_ok!(Identity::request_judgement(
+			RuntimeOrigin::signed(10),
+			0,
+			10
+		));
 		// 10 for the judgement request, 10 for the identity.
 		assert_eq!(Balances::free_balance(10), 80);
 
@@ -628,7 +737,10 @@
 #[test]
 fn test_has_identity() {
 	new_test_ext().execute_with(|| {
-		assert_ok!(Identity::set_identity(RuntimeOrigin::signed(10), Box::new(ten())));
+		assert_ok!(Identity::set_identity(
+			RuntimeOrigin::signed(10),
+			Box::new(ten())
+		));
 		assert!(Identity::has_identity(&10, IdentityField::Display as u64));
 		assert!(Identity::has_identity(&10, IdentityField::Legal as u64));
 		assert!(Identity::has_identity(
modifiedpallets/identity/src/types.rsdiffbeforeafterboth
--- a/pallets/identity/src/types.rs
+++ b/pallets/identity/src/types.rs
@@ -87,7 +87,7 @@
 					.expect("bound checked in match arm condition; qed");
 				input.read(&mut r[..])?;
 				Data::Raw(r)
-			},
+			}
 			34 => Data::BlakeTwo256(<[u8; 32]>::decode(input)?),
 			35 => Data::Sha256(<[u8; 32]>::decode(input)?),
 			36 => Data::Keccak256(<[u8; 32]>::decode(input)?),
@@ -106,7 +106,7 @@
 				let mut r = vec![l as u8 + 1; l + 1];
 				r[1..].copy_from_slice(&x[..l as usize]);
 				r
-			},
+			}
 			Data::BlakeTwo256(ref h) => once(34u8).chain(h.iter().cloned()).collect(),
 			Data::Sha256(ref h) => once(35u8).chain(h.iter().cloned()).collect(),
 			Data::Keccak256(ref h) => once(36u8).chain(h.iter().cloned()).collect(),
@@ -175,19 +175,25 @@
 
 		let variants = variants
 			.variant("BlakeTwo256", |v| {
-				v.index(34).fields(Fields::unnamed().field(|f| f.ty::<[u8; 32]>()))
+				v.index(34)
+					.fields(Fields::unnamed().field(|f| f.ty::<[u8; 32]>()))
 			})
 			.variant("Sha256", |v| {
-				v.index(35).fields(Fields::unnamed().field(|f| f.ty::<[u8; 32]>()))
+				v.index(35)
+					.fields(Fields::unnamed().field(|f| f.ty::<[u8; 32]>()))
 			})
 			.variant("Keccak256", |v| {
-				v.index(36).fields(Fields::unnamed().field(|f| f.ty::<[u8; 32]>()))
+				v.index(36)
+					.fields(Fields::unnamed().field(|f| f.ty::<[u8; 32]>()))
 			})
 			.variant("ShaThree256", |v| {
-				v.index(37).fields(Fields::unnamed().field(|f| f.ty::<[u8; 32]>()))
+				v.index(37)
+					.fields(Fields::unnamed().field(|f| f.ty::<[u8; 32]>()))
 			});
 
-		Type::builder().path(Path::new("Data", module_path!())).variant(variants)
+		Type::builder()
+			.path(Path::new("Data", module_path!()))
+			.variant(variants)
 	}
 }
 
@@ -280,7 +286,9 @@
 impl Decode for IdentityFields {
 	fn decode<I: codec::Input>(input: &mut I) -> sp_std::result::Result<Self, codec::Error> {
 		let field = u64::decode(input)?;
-		Ok(Self(<BitFlags<IdentityField>>::from_bits(field as u64).map_err(|_| "invalid value")?))
+		Ok(Self(
+			<BitFlags<IdentityField>>::from_bits(field as u64).map_err(|_| "invalid value")?,
+		))
 	}
 }
 impl TypeInfo for IdentityFields {
@@ -289,7 +297,10 @@
 	fn type_info() -> Type {
 		Type::builder()
 			.path(Path::new("BitFlags", module_path!()))
-			.type_params(vec![TypeParameter::new("T", Some(meta_type::<IdentityField>()))])
+			.type_params(vec![TypeParameter::new(
+				"T",
+				Some(meta_type::<IdentityField>()),
+			)])
 			.composite(Fields::unnamed().field(|f| f.ty::<u64>().type_name("IdentityField")))
 	}
 }
@@ -413,10 +424,17 @@
 	> Registration<Balance, MaxJudgements, MaxAdditionalFields>
 {
 	pub(crate) fn total_deposit(&self) -> Balance {
-		self.deposit +
-			self.judgements
+		self.deposit
+			+ self
+				.judgements
 				.iter()
-				.map(|(_, ref j)| if let Judgement::FeePaid(fee) = j { *fee } else { Zero::zero() })
+				.map(|(_, ref j)| {
+					if let Judgement::FeePaid(fee) = j {
+						*fee
+					} else {
+						Zero::zero()
+					}
+				})
 				.fold(Zero::zero(), |a, i| a + i)
 	}
 }
@@ -429,7 +447,11 @@
 {
 	fn decode<I: codec::Input>(input: &mut I) -> sp_std::result::Result<Self, codec::Error> {
 		let (judgements, deposit, info) = Decode::decode(&mut AppendZerosInput::new(input))?;
-		Ok(Self { judgements, deposit, info })
+		Ok(Self {
+			judgements,
+			deposit,
+			info,
+		})
 	}
 }
 
modifiedruntime/common/config/pallets/collator_selection.rsdiffbeforeafterboth
--- a/runtime/common/config/pallets/collator_selection.rs
+++ b/runtime/common/config/pallets/collator_selection.rs
@@ -54,9 +54,10 @@
 }
 
 parameter_types! {
-	pub const BasicDeposit: Balance = 10 * UNIQUE; // todo:collator
+	// These do not matter as we forbid non-sudo operations with the identity pallet
+	pub const BasicDeposit: Balance = 10 * UNIQUE;
 	pub const FieldDeposit: Balance = 25 * MILLIUNIQUE;
-	pub const SubAccountDeposit: Balance = 2 * UNIQUE; // end todo
+	pub const SubAccountDeposit: Balance = 2 * UNIQUE;
 	pub const MaxSubAccounts: u32 = 100;
 	pub const MaxAdditionalFields: u32 = 100;
 	pub const MaxRegistrars: u32 = 20;
@@ -89,7 +90,6 @@
 	type TreasuryAccountId = TreasuryAccountId;
 	type PotId = PotId;
 	type MaxCollators = MaxCollators;
-	// todo:collator kick threshold should be in storage and configured only by root -- or rather UpdateOrigin
 	type SlashRatio = SlashRatio;
 	type ValidatorId = <Self as frame_system::Config>::AccountId;
 	type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
modifiedruntime/common/runtime_apis.rsdiffbeforeafterboth
--- a/runtime/common/runtime_apis.rs
+++ b/runtime/common/runtime_apis.rs
@@ -705,7 +705,6 @@
                     #[cfg(feature = "rmrk")]
                     list_benchmark!(list, extra, pallet_proxy_rmrk_equip, RmrkEquip);
 
-                    // todo:collator check benchmarks
                     #[cfg(feature = "collator-selection")]
                     list_benchmark!(list, extra, pallet_collator_selection, CollatorSelection);
 
@@ -772,7 +771,6 @@
                     #[cfg(feature = "rmrk")]
                     add_benchmark!(params, batches, pallet_proxy_rmrk_equip, RmrkEquip);
 
-                    // todo:collator check benchmarks
                     #[cfg(feature = "collator-selection")]
                     add_benchmark!(params, batches, pallet_collator_selection, CollatorSelection);
 
modifiedruntime/opal/Cargo.tomldiffbeforeafterboth
--- a/runtime/opal/Cargo.toml
+++ b/runtime/opal/Cargo.toml
@@ -39,6 +39,7 @@
     'pallet-unique/runtime-benchmarks',
     'pallet-inflation/runtime-benchmarks',
     'pallet-app-promotion/runtime-benchmarks',
+    'pallet-collator-selection/runtime-benchmarks',
     'pallet-unique-scheduler-v2/runtime-benchmarks',
     'pallet-xcm/runtime-benchmarks',
     'sp-runtime/runtime-benchmarks',
modifiedruntime/quartz/Cargo.tomldiffbeforeafterboth
--- a/runtime/quartz/Cargo.toml
+++ b/runtime/quartz/Cargo.toml
@@ -38,6 +38,7 @@
     'pallet-unique/runtime-benchmarks',
     'pallet-foreign-assets/runtime-benchmarks',
     'pallet-inflation/runtime-benchmarks',
+    'pallet-collator-selection/runtime-benchmarks',
     'pallet-app-promotion/runtime-benchmarks',
     'pallet-xcm/runtime-benchmarks',
     'sp-runtime/runtime-benchmarks',
modifiedruntime/unique/Cargo.tomldiffbeforeafterboth
--- a/runtime/unique/Cargo.toml
+++ b/runtime/unique/Cargo.toml
@@ -38,6 +38,7 @@
     'pallet-unique/runtime-benchmarks',
     'pallet-foreign-assets/runtime-benchmarks',
     'pallet-inflation/runtime-benchmarks',
+    'pallet-collator-selection/runtime-benchmarks',
     'pallet-app-promotion/runtime-benchmarks',
     'pallet-xcm/runtime-benchmarks',
     'sp-runtime/runtime-benchmarks',
modifiedtests/src/interfaces/augment-api-events.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-events.ts
+++ b/tests/src/interfaces/augment-api-events.ts
@@ -105,8 +105,8 @@
       CandidateRemoved: AugmentedEvent<ApiType, [accountId: AccountId32], { accountId: AccountId32 }>;
       InvulnerableAdded: AugmentedEvent<ApiType, [invulnerable: AccountId32], { invulnerable: AccountId32 }>;
       InvulnerableRemoved: AugmentedEvent<ApiType, [invulnerable: AccountId32], { invulnerable: AccountId32 }>;
-      LicenseForfeited: AugmentedEvent<ApiType, [accountId: AccountId32, depositReturned: u128], { accountId: AccountId32, depositReturned: u128 }>;
       LicenseObtained: AugmentedEvent<ApiType, [accountId: AccountId32, deposit: u128], { accountId: AccountId32, deposit: u128 }>;
+      LicenseReleased: AugmentedEvent<ApiType, [accountId: AccountId32, depositReturned: u128], { accountId: AccountId32, depositReturned: u128 }>;
       /**
        * Generic event
        **/
modifiedtests/src/interfaces/augment-api-tx.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-tx.ts
+++ b/tests/src/interfaces/augment-api-tx.ts
@@ -313,15 +313,15 @@
        **/
       insertEvents: AugmentedSubmittable<(events: Vec<Bytes> | (Bytes | string | Uint8Array)[]) => SubmittableExtrinsic<ApiType>, [Vec<Bytes>]>;
       /**
-       * Insert or remove identities.
-       **/
-      insertIdentities: AugmentedSubmittable<(identities: Vec<ITuple<[AccountId32, Option<PalletIdentityRegistration>]>> | ([AccountId32 | string | Uint8Array, Option<PalletIdentityRegistration> | null | Uint8Array | PalletIdentityRegistration | { judgements?: any; deposit?: any; info?: any } | string])[]) => SubmittableExtrinsic<ApiType>, [Vec<ITuple<[AccountId32, Option<PalletIdentityRegistration>]>>]>;
-      /**
        * Insert items into contract storage, this method can be called
        * multiple times
        **/
       setData: AugmentedSubmittable<(address: H160 | string | Uint8Array, data: Vec<ITuple<[H256, H256]>> | ([H256 | string | Uint8Array, H256 | string | Uint8Array])[]) => SubmittableExtrinsic<ApiType>, [H160, Vec<ITuple<[H256, H256]>>]>;
       /**
+       * Insert or remove identities.
+       **/
+      setIdentities: AugmentedSubmittable<(identities: Vec<ITuple<[AccountId32, Option<PalletIdentityRegistration>]>> | ([AccountId32 | string | Uint8Array, Option<PalletIdentityRegistration> | null | Uint8Array | PalletIdentityRegistration | { judgements?: any; deposit?: any; info?: any } | string])[]) => SubmittableExtrinsic<ApiType>, [Vec<ITuple<[AccountId32, Option<PalletIdentityRegistration>]>>]>;
+      /**
        * Generic tx
        **/
       [key: string]: SubmittableExtrinsicFunction<ApiType>;
modifiedtests/src/interfaces/default/types.tsdiffbeforeafterboth
--- a/tests/src/interfaces/default/types.ts
+++ b/tests/src/interfaces/default/types.ts
@@ -1283,8 +1283,8 @@
     readonly accountId: AccountId32;
     readonly deposit: u128;
   } & Struct;
-  readonly isLicenseForfeited: boolean;
-  readonly asLicenseForfeited: {
+  readonly isLicenseReleased: boolean;
+  readonly asLicenseReleased: {
     readonly accountId: AccountId32;
     readonly depositReturned: u128;
   } & Struct;
@@ -1296,7 +1296,7 @@
   readonly asCandidateRemoved: {
     readonly accountId: AccountId32;
   } & Struct;
-  readonly type: 'InvulnerableAdded' | 'InvulnerableRemoved' | 'LicenseObtained' | 'LicenseForfeited' | 'CandidateAdded' | 'CandidateRemoved';
+  readonly type: 'InvulnerableAdded' | 'InvulnerableRemoved' | 'LicenseObtained' | 'LicenseReleased' | 'CandidateAdded' | 'CandidateRemoved';
 }
 
 /** @name PalletCommonError */
@@ -1477,11 +1477,11 @@
   readonly asInsertEvents: {
     readonly events: Vec<Bytes>;
   } & Struct;
-  readonly isInsertIdentities: boolean;
-  readonly asInsertIdentities: {
+  readonly isSetIdentities: boolean;
+  readonly asSetIdentities: {
     readonly identities: Vec<ITuple<[AccountId32, Option<PalletIdentityRegistration>]>>;
   } & Struct;
-  readonly type: 'Begin' | 'SetData' | 'Finish' | 'InsertEthLogs' | 'InsertEvents' | 'InsertIdentities';
+  readonly type: 'Begin' | 'SetData' | 'Finish' | 'InsertEthLogs' | 'InsertEvents' | 'SetIdentities';
 }
 
 /** @name PalletDataManagementError */
modifiedtests/src/interfaces/lookup.tsdiffbeforeafterboth
--- a/tests/src/interfaces/lookup.ts
+++ b/tests/src/interfaces/lookup.ts
@@ -198,7 +198,7 @@
         accountId: 'AccountId32',
         deposit: 'u128',
       },
-      LicenseForfeited: {
+      LicenseReleased: {
         accountId: 'AccountId32',
         depositReturned: 'u128',
       },
modifiedtests/src/interfaces/types-lookup.tsdiffbeforeafterboth
--- a/tests/src/interfaces/types-lookup.ts
+++ b/tests/src/interfaces/types-lookup.ts
@@ -212,8 +212,8 @@
       readonly accountId: AccountId32;
       readonly deposit: u128;
     } & Struct;
-    readonly isLicenseForfeited: boolean;
-    readonly asLicenseForfeited: {
+    readonly isLicenseReleased: boolean;
+    readonly asLicenseReleased: {
       readonly accountId: AccountId32;
       readonly depositReturned: u128;
     } & Struct;
@@ -225,7 +225,7 @@
     readonly asCandidateRemoved: {
       readonly accountId: AccountId32;
     } & Struct;
-    readonly type: 'InvulnerableAdded' | 'InvulnerableRemoved' | 'LicenseObtained' | 'LicenseForfeited' | 'CandidateAdded' | 'CandidateRemoved';
+    readonly type: 'InvulnerableAdded' | 'InvulnerableRemoved' | 'LicenseObtained' | 'LicenseReleased' | 'CandidateAdded' | 'CandidateRemoved';
   }
 
   /** @name PalletSessionEvent (31) */
@@ -3513,11 +3513,11 @@
     readonly asInsertEvents: {
       readonly events: Vec<Bytes>;
     } & Struct;
-    readonly isInsertIdentities: boolean;
-    readonly asInsertIdentities: {
+    readonly isSetIdentities: boolean;
+    readonly asSetIdentities: {
       readonly identities: Vec<ITuple<[AccountId32, Option<PalletIdentityRegistration>]>>;
     } & Struct;
-    readonly type: 'Begin' | 'SetData' | 'Finish' | 'InsertEthLogs' | 'InsertEvents' | 'InsertIdentities';
+    readonly type: 'Begin' | 'SetData' | 'Finish' | 'InsertEthLogs' | 'InsertEvents' | 'SetIdentities';
   }
 
   /** @name PalletMaintenanceCall (418) */