git.delta.rocks / unique-network / refs/commits / 42b7bebae7e5

difftreelog

feat(identity) force set subs

Fahrrader2023-01-18parent: #9505eb6.patch.diff
in: master

4 files changed

modifiedMakefilediffbeforeafterboth
--- a/Makefile
+++ b/Makefile
@@ -146,5 +146,5 @@
 	make _bench PALLET=app-promotion PALLET_DIR=app-promotion
 	
 .PHONY: bench
-# Disabled: bench-scheduler, bench-collator-selection, bench-rmrk-core, bench-rmrk-equip
-bench: bench-evm-migration bench-unique bench-structure bench-fungible bench-refungible bench-nonfungible bench-configuration bench-foreign-assets bench-identity
+# Disabled: bench-scheduler, bench-collator-selection, bench-identity, bench-rmrk-core, bench-rmrk-equip
+bench: bench-evm-migration bench-unique bench-structure bench-fungible bench-refungible bench-nonfungible bench-configuration bench-foreign-assets
modifiedpallets/identity/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/identity/src/benchmarking.rs
+++ b/pallets/identity/src/benchmarking.rs
@@ -417,7 +417,7 @@
 		let n in 0..600;
 		use frame_benchmarking::account;
 		let identities = (0..n).map(|i| (
-			account("caller", i, 0),
+			account("caller", i, SEED),
 			Registration::<BalanceOf<T>, T::MaxRegistrars, T::MaxAdditionalFields> {
 				judgements: Default::default(),
 				deposit: Default::default(),
@@ -433,7 +433,7 @@
 		use frame_benchmarking::account;
 		let origin = T::ForceOrigin::successful_origin();
 		let identities = (0..n).map(|i| (
-			account("caller", i, 0),
+			account("caller", i, SEED),
 			Registration::<BalanceOf<T>, T::MaxRegistrars, T::MaxAdditionalFields> {
 				judgements: Default::default(),
 				deposit: Default::default(),
@@ -446,6 +446,20 @@
 		let identities = identities.into_iter().map(|(acc, _)| acc).collect::<Vec<_>>();
 	}: _<T::RuntimeOrigin>(origin, identities)
 
+	force_set_subs {
+		let s in 0 .. T::MaxSubAccounts::get();
+		let n in 0..600;
+		use frame_benchmarking::account;
+		let identities = (0..n).map(|i| (
+			account("caller", i, SEED),
+			(
+				BalanceOf::<T>::max_value(),
+				create_sub_accounts::<T>(&caller, s)?.try_into().unwrap(),
+			),
+		)).collect::<Vec<_>>();
+		let origin = T::ForceOrigin::successful_origin();
+	}: _<T::RuntimeOrigin>(origin, identities)
+
 	add_sub {
 		let s in 0 .. T::MaxSubAccounts::get() - 1;
 
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(super) 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 number of identities and associated info were forcibly inserted.278		IdentitiesInserted { amount: u32 },279		/// A number of identities and all associated info were forcibly removed.280		IdentitiesRemoved { amount: u32 },281		/// A judgement was asked from a registrar.282		JudgementRequested {283			who: T::AccountId,284			registrar_index: RegistrarIndex,285		},286		/// A judgement request was retracted.287		JudgementUnrequested {288			who: T::AccountId,289			registrar_index: RegistrarIndex,290		},291		/// A judgement was given by a registrar.292		JudgementGiven {293			target: T::AccountId,294			registrar_index: RegistrarIndex,295		},296		/// A registrar was added.297		RegistrarAdded { registrar_index: RegistrarIndex },298		/// A sub-identity was added to an identity and the deposit paid.299		SubIdentityAdded {300			sub: T::AccountId,301			main: T::AccountId,302			deposit: BalanceOf<T>,303		},304		/// A sub-identity was removed from an identity and the deposit freed.305		SubIdentityRemoved {306			sub: T::AccountId,307			main: T::AccountId,308			deposit: BalanceOf<T>,309		},310		/// A sub-identity was cleared, and the given deposit repatriated from the311		/// main identity account to the sub-identity account.312		SubIdentityRevoked {313			sub: T::AccountId,314			main: T::AccountId,315			deposit: BalanceOf<T>,316		},317	}318319	#[pallet::call]320	/// Identity pallet declaration.321	impl<T: Config> Pallet<T> {322		/// Add a registrar to the system.323		///324		/// The dispatch origin for this call must be `T::RegistrarOrigin`.325		///326		/// - `account`: the account of the registrar.327		///328		/// Emits `RegistrarAdded` if successful.329		///330		/// # <weight>331		/// - `O(R)` where `R` registrar-count (governance-bounded and code-bounded).332		/// - One storage mutation (codec `O(R)`).333		/// - One event.334		/// # </weight>335		#[pallet::call_index(0)]336		#[pallet::weight(T::WeightInfo::add_registrar(T::MaxRegistrars::get()))]337		pub fn add_registrar(338			origin: OriginFor<T>,339			account: AccountIdLookupOf<T>,340		) -> DispatchResultWithPostInfo {341			T::RegistrarOrigin::ensure_origin(origin)?;342			let account = T::Lookup::lookup(account)?;343344			let (i, registrar_count) = <Registrars<T>>::try_mutate(345				|registrars| -> Result<(RegistrarIndex, usize), DispatchError> {346					registrars347						.try_push(Some(RegistrarInfo {348							account,349							fee: Zero::zero(),350							fields: Default::default(),351						}))352						.map_err(|_| Error::<T>::TooManyRegistrars)?;353					Ok(((registrars.len() - 1) as RegistrarIndex, registrars.len()))354				},355			)?;356357			Self::deposit_event(Event::RegistrarAdded { registrar_index: i });358359			Ok(Some(T::WeightInfo::add_registrar(registrar_count as u32)).into())360		}361362		/// Set an account's identity information and reserve the appropriate deposit.363		///364		/// If the account already has identity information, the deposit is taken as part payment365		/// for the new deposit.366		///367		/// The dispatch origin for this call must be _Signed_.368		///369		/// - `info`: The identity information.370		///371		/// Emits `IdentitySet` if successful.372		///373		/// # <weight>374		/// - `O(X + X' + R)`375		///   - where `X` additional-field-count (deposit-bounded and code-bounded)376		///   - where `R` judgements-count (registrar-count-bounded)377		/// - One balance reserve operation.378		/// - One storage mutation (codec-read `O(X' + R)`, codec-write `O(X + R)`).379		/// - One event.380		/// # </weight>381		#[pallet::call_index(1)]382		#[pallet::weight( T::WeightInfo::set_identity(383			T::MaxRegistrars::get(), // R384			T::MaxAdditionalFields::get(), // X385		))]386		pub fn set_identity(387			origin: OriginFor<T>,388			info: Box<IdentityInfo<T::MaxAdditionalFields>>,389		) -> DispatchResultWithPostInfo {390			let sender = ensure_signed(origin)?;391			let extra_fields = info.additional.len() as u32;392			ensure!(393				extra_fields <= T::MaxAdditionalFields::get(),394				Error::<T>::TooManyFields395			);396			let fd = <BalanceOf<T>>::from(extra_fields) * T::FieldDeposit::get();397398			let mut id = match <IdentityOf<T>>::get(&sender) {399				Some(mut id) => {400					// Only keep non-positive judgements.401					id.judgements.retain(|j| j.1.is_sticky());402					id.info = *info;403					id404				}405				None => Registration {406					info: *info,407					judgements: BoundedVec::default(),408					deposit: Zero::zero(),409				},410			};411412			let old_deposit = id.deposit;413			id.deposit = T::BasicDeposit::get() + fd;414			if id.deposit > old_deposit {415				T::Currency::reserve(&sender, id.deposit - old_deposit)?;416			}417			if old_deposit > id.deposit {418				let err_amount = T::Currency::unreserve(&sender, old_deposit - id.deposit);419				debug_assert!(err_amount.is_zero());420			}421422			let judgements = id.judgements.len();423			<IdentityOf<T>>::insert(&sender, id);424			Self::deposit_event(Event::IdentitySet { who: sender });425426			Ok(Some(T::WeightInfo::set_identity(427				judgements as u32, // R428				extra_fields,      // X429			))430			.into())431		}432433		/// Set the sub-accounts of the sender.434		///435		/// Payment: Any aggregate balance reserved by previous `set_subs` calls will be returned436		/// and an amount `SubAccountDeposit` will be reserved for each item in `subs`.437		///438		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered439		/// identity.440		///441		/// - `subs`: The identity's (new) sub-accounts.442		///443		/// # <weight>444		/// - `O(P + S)`445		///   - where `P` old-subs-count (hard- and deposit-bounded).446		///   - where `S` subs-count (hard- and deposit-bounded).447		/// - At most one balance operations.448		/// - DB:449		///   - `P + S` storage mutations (codec complexity `O(1)`)450		///   - One storage read (codec complexity `O(P)`).451		///   - One storage write (codec complexity `O(S)`).452		///   - One storage-exists (`IdentityOf::contains_key`).453		/// # </weight>454		// TODO: This whole extrinsic screams "not optimized". For example we could455		// filter any overlap between new and old subs, and avoid reading/writing456		// to those values... We could also ideally avoid needing to write to457		// N storage items for N sub accounts. Right now the weight on this function458		// is a large overestimate due to the fact that it could potentially write459		// to 2 x T::MaxSubAccounts::get().460		#[pallet::call_index(2)]461		#[pallet::weight(T::WeightInfo::set_subs_old(T::MaxSubAccounts::get()) // P: Assume max sub accounts removed.462			.saturating_add(T::WeightInfo::set_subs_new(subs.len() as u32)) // S: Assume all subs are new.463		)]464		pub fn set_subs(465			origin: OriginFor<T>,466			subs: Vec<(T::AccountId, Data)>,467		) -> DispatchResultWithPostInfo {468			let sender = ensure_signed(origin)?;469			ensure!(<IdentityOf<T>>::contains_key(&sender), Error::<T>::NotFound);470			ensure!(471				subs.len() <= T::MaxSubAccounts::get() as usize,472				Error::<T>::TooManySubAccounts473			);474475			let (old_deposit, old_ids) = <SubsOf<T>>::get(&sender);476			let new_deposit = T::SubAccountDeposit::get() * <BalanceOf<T>>::from(subs.len() as u32);477478			let not_other_sub = subs479				.iter()480				.filter_map(|i| SuperOf::<T>::get(&i.0))481				.all(|i| i.0 == sender);482			ensure!(not_other_sub, Error::<T>::AlreadyClaimed);483484			if old_deposit < new_deposit {485				T::Currency::reserve(&sender, new_deposit - old_deposit)?;486			} else if old_deposit > new_deposit {487				let err_amount = T::Currency::unreserve(&sender, old_deposit - new_deposit);488				debug_assert!(err_amount.is_zero());489			}490			// do nothing if they're equal.491492			for s in old_ids.iter() {493				<SuperOf<T>>::remove(s);494			}495			let mut ids = BoundedVec::<T::AccountId, T::MaxSubAccounts>::default();496			for (id, name) in subs {497				<SuperOf<T>>::insert(&id, (sender.clone(), name));498				ids.try_push(id)499					.expect("subs length is less than T::MaxSubAccounts; qed");500			}501			let new_subs = ids.len();502503			if ids.is_empty() {504				<SubsOf<T>>::remove(&sender);505			} else {506				<SubsOf<T>>::insert(&sender, (new_deposit, ids));507			}508509			Ok(Some(510				T::WeightInfo::set_subs_old(old_ids.len() as u32) // P: Real number of old accounts removed.511					// S: New subs added512					.saturating_add(T::WeightInfo::set_subs_new(new_subs as u32)),513			)514			.into())515		}516517		/// Clear an account's identity info and all sub-accounts and return all deposits.518		///519		/// Payment: All reserved balances on the account are returned.520		///521		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered522		/// identity.523		///524		/// Emits `IdentityCleared` if successful.525		///526		/// # <weight>527		/// - `O(R + S + X)`528		///   - where `R` registrar-count (governance-bounded).529		///   - where `S` subs-count (hard- and deposit-bounded).530		///   - where `X` additional-field-count (deposit-bounded and code-bounded).531		/// - One balance-unreserve operation.532		/// - `2` storage reads and `S + 2` storage deletions.533		/// - One event.534		/// # </weight>535		#[pallet::call_index(3)]536		#[pallet::weight(T::WeightInfo::clear_identity(537			T::MaxRegistrars::get(), // R538			T::MaxSubAccounts::get(), // S539			T::MaxAdditionalFields::get(), // X540		))]541		pub fn clear_identity(origin: OriginFor<T>) -> DispatchResultWithPostInfo {542			let sender = ensure_signed(origin)?;543544			let (subs_deposit, sub_ids) = <SubsOf<T>>::take(&sender);545			let id = <IdentityOf<T>>::take(&sender).ok_or(Error::<T>::NotNamed)?;546			let deposit = id.total_deposit() + subs_deposit;547			for sub in sub_ids.iter() {548				<SuperOf<T>>::remove(sub);549			}550551			let err_amount = T::Currency::unreserve(&sender, deposit);552			debug_assert!(err_amount.is_zero());553554			Self::deposit_event(Event::IdentityCleared {555				who: sender,556				deposit,557			});558559			Ok(Some(T::WeightInfo::clear_identity(560				id.judgements.len() as u32,      // R561				sub_ids.len() as u32,            // S562				id.info.additional.len() as u32, // X563			))564			.into())565		}566567		/// Request a judgement from a registrar.568		///569		/// Payment: At most `max_fee` will be reserved for payment to the registrar if judgement570		/// given.571		///572		/// The dispatch origin for this call must be _Signed_ and the sender must have a573		/// registered identity.574		///575		/// - `reg_index`: The index of the registrar whose judgement is requested.576		/// - `max_fee`: The maximum fee that may be paid. This should just be auto-populated as:577		///578		/// ```nocompile579		/// Self::registrars().get(reg_index).unwrap().fee580		/// ```581		///582		/// Emits `JudgementRequested` if successful.583		///584		/// # <weight>585		/// - `O(R + X)`.586		/// - One balance-reserve operation.587		/// - Storage: 1 read `O(R)`, 1 mutate `O(X + R)`.588		/// - One event.589		/// # </weight>590		#[pallet::call_index(4)]591		#[pallet::weight(T::WeightInfo::request_judgement(592			T::MaxRegistrars::get(), // R593			T::MaxAdditionalFields::get(), // X594		))]595		pub fn request_judgement(596			origin: OriginFor<T>,597			#[pallet::compact] reg_index: RegistrarIndex,598			#[pallet::compact] max_fee: BalanceOf<T>,599		) -> DispatchResultWithPostInfo {600			let sender = ensure_signed(origin)?;601			let registrars = <Registrars<T>>::get();602			let registrar = registrars603				.get(reg_index as usize)604				.and_then(Option::as_ref)605				.ok_or(Error::<T>::EmptyIndex)?;606			ensure!(max_fee >= registrar.fee, Error::<T>::FeeChanged);607			let mut id = <IdentityOf<T>>::get(&sender).ok_or(Error::<T>::NoIdentity)?;608609			let item = (reg_index, Judgement::FeePaid(registrar.fee));610			match id.judgements.binary_search_by_key(&reg_index, |x| x.0) {611				Ok(i) => {612					if id.judgements[i].1.is_sticky() {613						return Err(Error::<T>::StickyJudgement.into());614					} else {615						id.judgements[i] = item616					}617				}618				Err(i) => id619					.judgements620					.try_insert(i, item)621					.map_err(|_| Error::<T>::TooManyRegistrars)?,622			}623624			T::Currency::reserve(&sender, registrar.fee)?;625626			let judgements = id.judgements.len();627			let extra_fields = id.info.additional.len();628			<IdentityOf<T>>::insert(&sender, id);629630			Self::deposit_event(Event::JudgementRequested {631				who: sender,632				registrar_index: reg_index,633			});634635			Ok(Some(T::WeightInfo::request_judgement(636				judgements as u32,637				extra_fields as u32,638			))639			.into())640		}641642		/// Cancel a previous request.643		///644		/// Payment: A previously reserved deposit is returned on success.645		///646		/// The dispatch origin for this call must be _Signed_ and the sender must have a647		/// registered identity.648		///649		/// - `reg_index`: The index of the registrar whose judgement is no longer requested.650		///651		/// Emits `JudgementUnrequested` if successful.652		///653		/// # <weight>654		/// - `O(R + X)`.655		/// - One balance-reserve operation.656		/// - One storage mutation `O(R + X)`.657		/// - One event658		/// # </weight>659		#[pallet::call_index(5)]660		#[pallet::weight(T::WeightInfo::cancel_request(661			T::MaxRegistrars::get(), // R662			T::MaxAdditionalFields::get(), // X663		))]664		pub fn cancel_request(665			origin: OriginFor<T>,666			reg_index: RegistrarIndex,667		) -> DispatchResultWithPostInfo {668			let sender = ensure_signed(origin)?;669			let mut id = <IdentityOf<T>>::get(&sender).ok_or(Error::<T>::NoIdentity)?;670671			let pos = id672				.judgements673				.binary_search_by_key(&reg_index, |x| x.0)674				.map_err(|_| Error::<T>::NotFound)?;675			let fee = if let Judgement::FeePaid(fee) = id.judgements.remove(pos).1 {676				fee677			} else {678				return Err(Error::<T>::JudgementGiven.into());679			};680681			let err_amount = T::Currency::unreserve(&sender, fee);682			debug_assert!(err_amount.is_zero());683			let judgements = id.judgements.len();684			let extra_fields = id.info.additional.len();685			<IdentityOf<T>>::insert(&sender, id);686687			Self::deposit_event(Event::JudgementUnrequested {688				who: sender,689				registrar_index: reg_index,690			});691692			Ok(Some(T::WeightInfo::cancel_request(693				judgements as u32,694				extra_fields as u32,695			))696			.into())697		}698699		/// Set the fee required for a judgement to be requested from a registrar.700		///701		/// The dispatch origin for this call must be _Signed_ and the sender must be the account702		/// of the registrar whose index is `index`.703		///704		/// - `index`: the index of the registrar whose fee is to be set.705		/// - `fee`: the new fee.706		///707		/// # <weight>708		/// - `O(R)`.709		/// - One storage mutation `O(R)`.710		/// - Benchmark: 7.315 + R * 0.329 µs (min squares analysis)711		/// # </weight>712		#[pallet::call_index(6)]713		#[pallet::weight(T::WeightInfo::set_fee(T::MaxRegistrars::get()))] // R714		pub fn set_fee(715			origin: OriginFor<T>,716			#[pallet::compact] index: RegistrarIndex,717			#[pallet::compact] fee: BalanceOf<T>,718		) -> DispatchResultWithPostInfo {719			let who = ensure_signed(origin)?;720721			let registrars = <Registrars<T>>::mutate(|rs| -> Result<usize, DispatchError> {722				rs.get_mut(index as usize)723					.and_then(|x| x.as_mut())724					.and_then(|r| {725						if r.account == who {726							r.fee = fee;727							Some(())728						} else {729							None730						}731					})732					.ok_or_else(|| DispatchError::from(Error::<T>::InvalidIndex))?;733				Ok(rs.len())734			})?;735			Ok(Some(T::WeightInfo::set_fee(registrars as u32)).into()) // R736		}737738		/// Change the account associated with a registrar.739		///740		/// The dispatch origin for this call must be _Signed_ and the sender must be the account741		/// of the registrar whose index is `index`.742		///743		/// - `index`: the index of the registrar whose fee is to be set.744		/// - `new`: the new account ID.745		///746		/// # <weight>747		/// - `O(R)`.748		/// - One storage mutation `O(R)`.749		/// - Benchmark: 8.823 + R * 0.32 µs (min squares analysis)750		/// # </weight>751		#[pallet::call_index(7)]752		#[pallet::weight(T::WeightInfo::set_account_id(T::MaxRegistrars::get()))] // R753		pub fn set_account_id(754			origin: OriginFor<T>,755			#[pallet::compact] index: RegistrarIndex,756			new: AccountIdLookupOf<T>,757		) -> DispatchResultWithPostInfo {758			let who = ensure_signed(origin)?;759			let new = T::Lookup::lookup(new)?;760761			let registrars = <Registrars<T>>::mutate(|rs| -> Result<usize, DispatchError> {762				rs.get_mut(index as usize)763					.and_then(|x| x.as_mut())764					.and_then(|r| {765						if r.account == who {766							r.account = new;767							Some(())768						} else {769							None770						}771					})772					.ok_or_else(|| DispatchError::from(Error::<T>::InvalidIndex))?;773				Ok(rs.len())774			})?;775			Ok(Some(T::WeightInfo::set_account_id(registrars as u32)).into()) // R776		}777778		/// Set the field information for a registrar.779		///780		/// The dispatch origin for this call must be _Signed_ and the sender must be the account781		/// of the registrar whose index is `index`.782		///783		/// - `index`: the index of the registrar whose fee is to be set.784		/// - `fields`: the fields that the registrar concerns themselves with.785		///786		/// # <weight>787		/// - `O(R)`.788		/// - One storage mutation `O(R)`.789		/// - Benchmark: 7.464 + R * 0.325 µs (min squares analysis)790		/// # </weight>791		#[pallet::call_index(8)]792		#[pallet::weight(T::WeightInfo::set_fields(T::MaxRegistrars::get()))] // R793		pub fn set_fields(794			origin: OriginFor<T>,795			#[pallet::compact] index: RegistrarIndex,796			fields: IdentityFields,797		) -> DispatchResultWithPostInfo {798			let who = ensure_signed(origin)?;799800			let registrars = <Registrars<T>>::mutate(|rs| -> Result<usize, DispatchError> {801				rs.get_mut(index as usize)802					.and_then(|x| x.as_mut())803					.and_then(|r| {804						if r.account == who {805							r.fields = fields;806							Some(())807						} else {808							None809						}810					})811					.ok_or_else(|| DispatchError::from(Error::<T>::InvalidIndex))?;812				Ok(rs.len())813			})?;814			Ok(Some(T::WeightInfo::set_fields(815				registrars as u32, // R816			))817			.into())818		}819820		/// Provide a judgement for an account's identity.821		///822		/// The dispatch origin for this call must be _Signed_ and the sender must be the account823		/// of the registrar whose index is `reg_index`.824		///825		/// - `reg_index`: the index of the registrar whose judgement is being made.826		/// - `target`: the account whose identity the judgement is upon. This must be an account827		///   with a registered identity.828		/// - `judgement`: the judgement of the registrar of index `reg_index` about `target`.829		/// - `identity`: The hash of the [`IdentityInfo`] for that the judgement is provided.830		///831		/// Emits `JudgementGiven` if successful.832		///833		/// # <weight>834		/// - `O(R + X)`.835		/// - One balance-transfer operation.836		/// - Up to one account-lookup operation.837		/// - Storage: 1 read `O(R)`, 1 mutate `O(R + X)`.838		/// - One event.839		/// # </weight>840		#[pallet::call_index(9)]841		#[pallet::weight(T::WeightInfo::provide_judgement(842			T::MaxRegistrars::get(), // R843			T::MaxAdditionalFields::get(), // X844		))]845		pub fn provide_judgement(846			origin: OriginFor<T>,847			#[pallet::compact] reg_index: RegistrarIndex,848			target: AccountIdLookupOf<T>,849			judgement: Judgement<BalanceOf<T>>,850			identity: T::Hash,851		) -> DispatchResultWithPostInfo {852			let sender = ensure_signed(origin)?;853			let target = T::Lookup::lookup(target)?;854			ensure!(!judgement.has_deposit(), Error::<T>::InvalidJudgement);855			<Registrars<T>>::get()856				.get(reg_index as usize)857				.and_then(Option::as_ref)858				.filter(|r| r.account == sender)859				.ok_or(Error::<T>::InvalidIndex)?;860			let mut id = <IdentityOf<T>>::get(&target).ok_or(Error::<T>::InvalidTarget)?;861862			if T::Hashing::hash_of(&id.info) != identity {863				return Err(Error::<T>::JudgementForDifferentIdentity.into());864			}865866			let item = (reg_index, judgement);867			match id.judgements.binary_search_by_key(&reg_index, |x| x.0) {868				Ok(position) => {869					if let Judgement::FeePaid(fee) = id.judgements[position].1 {870						T::Currency::repatriate_reserved(871							&target,872							&sender,873							fee,874							BalanceStatus::Free,875						)876						.map_err(|_| Error::<T>::JudgementPaymentFailed)?;877					}878					id.judgements[position] = item879				}880				Err(position) => id881					.judgements882					.try_insert(position, item)883					.map_err(|_| Error::<T>::TooManyRegistrars)?,884			}885886			let judgements = id.judgements.len();887			let extra_fields = id.info.additional.len();888			<IdentityOf<T>>::insert(&target, id);889			Self::deposit_event(Event::JudgementGiven {890				target,891				registrar_index: reg_index,892			});893894			Ok(Some(T::WeightInfo::provide_judgement(895				judgements as u32,896				extra_fields as u32,897			))898			.into())899		}900901		/// Remove an account's identity and sub-account information and slash the deposits.902		///903		/// Payment: Reserved balances from `set_subs` and `set_identity` are slashed and handled by904		/// `Slash`. Verification request deposits are not returned; they should be cancelled905		/// manually using `cancel_request`.906		///907		/// The dispatch origin for this call must match `T::ForceOrigin`.908		///909		/// - `target`: the account whose identity the judgement is upon. This must be an account910		///   with a registered identity.911		///912		/// Emits `IdentityKilled` if successful.913		///914		/// # <weight>915		/// - `O(R + S + X)`.916		/// - One balance-reserve operation.917		/// - `S + 2` storage mutations.918		/// - One event.919		/// # </weight>920		#[pallet::call_index(10)]921		#[pallet::weight(T::WeightInfo::kill_identity(922			T::MaxRegistrars::get(), // R923			T::MaxSubAccounts::get(), // S924			T::MaxAdditionalFields::get(), // X925		))]926		pub fn kill_identity(927			origin: OriginFor<T>,928			target: AccountIdLookupOf<T>,929		) -> DispatchResultWithPostInfo {930			T::ForceOrigin::ensure_origin(origin)?;931932			// Figure out who we're meant to be clearing.933			let target = T::Lookup::lookup(target)?;934			// Grab their deposit (and check that they have one).935			let (subs_deposit, sub_ids) = <SubsOf<T>>::take(&target);936			let id = <IdentityOf<T>>::take(&target).ok_or(Error::<T>::NotNamed)?;937			let deposit = id.total_deposit() + subs_deposit;938			for sub in sub_ids.iter() {939				<SuperOf<T>>::remove(sub);940			}941			// Slash their deposit from them.942			T::Slashed::on_unbalanced(T::Currency::slash_reserved(&target, deposit).0);943944			Self::deposit_event(Event::IdentityKilled {945				who: target,946				deposit,947			});948949			Ok(Some(T::WeightInfo::kill_identity(950				id.judgements.len() as u32,      // R951				sub_ids.len() as u32,            // S952				id.info.additional.len() as u32, // X953			))954			.into())955		}956957		/// Add the given account to the sender's subs.958		///959		/// Payment: Balance reserved by a previous `set_subs` call for one sub will be repatriated960		/// to the sender.961		///962		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered963		/// sub identity of `sub`.964		#[pallet::call_index(11)]965		#[pallet::weight(T::WeightInfo::add_sub(T::MaxSubAccounts::get()))]966		pub fn add_sub(967			origin: OriginFor<T>,968			sub: AccountIdLookupOf<T>,969			data: Data,970		) -> DispatchResult {971			let sender = ensure_signed(origin)?;972			let sub = T::Lookup::lookup(sub)?;973			ensure!(974				IdentityOf::<T>::contains_key(&sender),975				Error::<T>::NoIdentity976			);977978			// Check if it's already claimed as sub-identity.979			ensure!(980				!SuperOf::<T>::contains_key(&sub),981				Error::<T>::AlreadyClaimed982			);983984			SubsOf::<T>::try_mutate(&sender, |(ref mut subs_deposit, ref mut sub_ids)| {985				// Ensure there is space and that the deposit is paid.986				ensure!(987					sub_ids.len() < T::MaxSubAccounts::get() as usize,988					Error::<T>::TooManySubAccounts989				);990				let deposit = T::SubAccountDeposit::get();991				T::Currency::reserve(&sender, deposit)?;992993				SuperOf::<T>::insert(&sub, (sender.clone(), data));994				sub_ids995					.try_push(sub.clone())996					.expect("sub ids length checked above; qed");997				*subs_deposit = subs_deposit.saturating_add(deposit);998999				Self::deposit_event(Event::SubIdentityAdded {1000					sub,1001					main: sender.clone(),1002					deposit,1003				});1004				Ok(())1005			})1006		}10071008		/// Alter the associated name of the given sub-account.1009		///1010		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered1011		/// sub identity of `sub`.1012		#[pallet::call_index(12)]1013		#[pallet::weight(T::WeightInfo::rename_sub(T::MaxSubAccounts::get()))]1014		pub fn rename_sub(1015			origin: OriginFor<T>,1016			sub: AccountIdLookupOf<T>,1017			data: Data,1018		) -> DispatchResult {1019			let sender = ensure_signed(origin)?;1020			let sub = T::Lookup::lookup(sub)?;1021			ensure!(1022				IdentityOf::<T>::contains_key(&sender),1023				Error::<T>::NoIdentity1024			);1025			ensure!(1026				SuperOf::<T>::get(&sub).map_or(false, |x| x.0 == sender),1027				Error::<T>::NotOwned1028			);1029			SuperOf::<T>::insert(&sub, (sender, data));1030			Ok(())1031		}10321033		/// Remove the given account from the sender's subs.1034		///1035		/// Payment: Balance reserved by a previous `set_subs` call for one sub will be repatriated1036		/// to the sender.1037		///1038		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered1039		/// sub identity of `sub`.1040		#[pallet::call_index(13)]1041		#[pallet::weight(T::WeightInfo::remove_sub(T::MaxSubAccounts::get()))]1042		pub fn remove_sub(origin: OriginFor<T>, sub: AccountIdLookupOf<T>) -> DispatchResult {1043			let sender = ensure_signed(origin)?;1044			ensure!(1045				IdentityOf::<T>::contains_key(&sender),1046				Error::<T>::NoIdentity1047			);1048			let sub = T::Lookup::lookup(sub)?;1049			let (sup, _) = SuperOf::<T>::get(&sub).ok_or(Error::<T>::NotSub)?;1050			ensure!(sup == sender, Error::<T>::NotOwned);1051			SuperOf::<T>::remove(&sub);1052			SubsOf::<T>::mutate(&sup, |(ref mut subs_deposit, ref mut sub_ids)| {1053				sub_ids.retain(|x| x != &sub);1054				let deposit = T::SubAccountDeposit::get().min(*subs_deposit);1055				*subs_deposit -= deposit;1056				let err_amount = T::Currency::unreserve(&sender, deposit);1057				debug_assert!(err_amount.is_zero());1058				Self::deposit_event(Event::SubIdentityRemoved {1059					sub,1060					main: sender,1061					deposit,1062				});1063			});1064			Ok(())1065		}10661067		/// Remove the sender as a sub-account.1068		///1069		/// Payment: Balance reserved by a previous `set_subs` call for one sub will be repatriated1070		/// to the sender (*not* the original depositor).1071		///1072		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered1073		/// super-identity.1074		///1075		/// NOTE: This should not normally be used, but is provided in the case that the non-1076		/// controller of an account is maliciously registered as a sub-account.1077		#[pallet::call_index(14)]1078		#[pallet::weight(T::WeightInfo::quit_sub(T::MaxSubAccounts::get()))]1079		pub fn quit_sub(origin: OriginFor<T>) -> DispatchResult {1080			let sender = ensure_signed(origin)?;1081			let (sup, _) = SuperOf::<T>::take(&sender).ok_or(Error::<T>::NotSub)?;1082			SubsOf::<T>::mutate(&sup, |(ref mut subs_deposit, ref mut sub_ids)| {1083				sub_ids.retain(|x| x != &sender);1084				let deposit = T::SubAccountDeposit::get().min(*subs_deposit);1085				*subs_deposit -= deposit;1086				let _ =1087					T::Currency::repatriate_reserved(&sup, &sender, deposit, BalanceStatus::Free);1088				Self::deposit_event(Event::SubIdentityRevoked {1089					sub: sender,1090					main: sup.clone(),1091					deposit,1092				});1093			});1094			Ok(())1095		}10961097		/// Set identities to be associated with the provided accounts as force origin.1098		///1099		/// This is not meant to operate in tandem with the identity pallet as is,1100		/// and be instead used to keep identities made and verified externally,1101		/// forbidden from interacting with an ordinary user, since it ignores any safety mechanism.1102		#[pallet::call_index(15)]1103		#[pallet::weight(T::WeightInfo::force_insert_identities(1104			T::MaxAdditionalFields::get(), // X1105			identities.len() as u32, // N1106		))]1107		pub fn force_insert_identities(1108			origin: OriginFor<T>,1109			identities: Vec<(1110				T::AccountId,1111				Registration<BalanceOf<T>, T::MaxRegistrars, T::MaxAdditionalFields>,1112			)>,1113		) -> DispatchResult {1114			T::ForceOrigin::ensure_origin(origin)?;1115			for identity in identities.clone() {1116				IdentityOf::<T>::insert(identity.0, identity.1);1117			}1118			Self::deposit_event(Event::IdentitiesInserted {1119				amount: identities.len() as u32,1120			});1121			Ok(())1122		}11231124		/// Remove identities associated with the provided accounts as force origin.1125		///1126		/// This is not meant to operate in tandem with the identity pallet as is,1127		/// and be instead used to keep identities made and verified externally,1128		/// forbidden from interacting with an ordinary user, since it ignores any safety mechanism.1129		#[pallet::call_index(16)]1130		#[pallet::weight(T::WeightInfo::force_remove_identities(1131			T::MaxAdditionalFields::get(), // X1132			identities.len() as u32, // N1133		))]1134		pub fn force_remove_identities(1135			origin: OriginFor<T>,1136			identities: Vec<T::AccountId>,1137		) -> DispatchResult {1138			T::ForceOrigin::ensure_origin(origin)?;1139			for identity in identities.clone() {1140				IdentityOf::<T>::set(identity, None);1141			}1142			Self::deposit_event(Event::IdentitiesRemoved {1143				amount: identities.len() as u32,1144			});1145			Ok(())1146		}1147	}1148}11491150impl<T: Config> Pallet<T> {1151	/// Get the subs of an account.1152	pub fn subs(who: &T::AccountId) -> Vec<(T::AccountId, Data)> {1153		SubsOf::<T>::get(who)1154			.11155			.into_iter()1156			.filter_map(|a| SuperOf::<T>::get(&a).map(|x| (a, x.1)))1157			.collect()1158	}11591160	/// Check if the account has corresponding identity information by the identity field.1161	pub fn has_identity(who: &T::AccountId, fields: u64) -> bool {1162		IdentityOf::<T>::get(who).map_or(false, |registration| {1163			(registration.info.fields().0.bits() & fields) == fields1164		})1165	}1166}
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(super) 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 number of identities and associated info were forcibly inserted.278		IdentitiesInserted { amount: u32 },279		/// A number of identities and all associated info were forcibly removed.280		IdentitiesRemoved { amount: u32 },281		/// A judgement was asked from a registrar.282		JudgementRequested {283			who: T::AccountId,284			registrar_index: RegistrarIndex,285		},286		/// A judgement request was retracted.287		JudgementUnrequested {288			who: T::AccountId,289			registrar_index: RegistrarIndex,290		},291		/// A judgement was given by a registrar.292		JudgementGiven {293			target: T::AccountId,294			registrar_index: RegistrarIndex,295		},296		/// A registrar was added.297		RegistrarAdded { registrar_index: RegistrarIndex },298		/// A sub-identity was added to an identity and the deposit paid.299		SubIdentityAdded {300			sub: T::AccountId,301			main: T::AccountId,302			deposit: BalanceOf<T>,303		},304		/// A sub-identity was removed from an identity and the deposit freed.305		SubIdentityRemoved {306			sub: T::AccountId,307			main: T::AccountId,308			deposit: BalanceOf<T>,309		},310		/// A sub-identity was cleared, and the given deposit repatriated from the311		/// main identity account to the sub-identity account.312		SubIdentityRevoked {313			sub: T::AccountId,314			main: T::AccountId,315			deposit: BalanceOf<T>,316		},317		/// A number of identities were forcibly updated with new sub-identities.318		SubIdentitiesInserted { amount: u32 },319	}320321	#[pallet::call]322	/// Identity pallet declaration.323	impl<T: Config> Pallet<T> {324		/// Add a registrar to the system.325		///326		/// The dispatch origin for this call must be `T::RegistrarOrigin`.327		///328		/// - `account`: the account of the registrar.329		///330		/// Emits `RegistrarAdded` if successful.331		///332		/// # <weight>333		/// - `O(R)` where `R` registrar-count (governance-bounded and code-bounded).334		/// - One storage mutation (codec `O(R)`).335		/// - One event.336		/// # </weight>337		#[pallet::call_index(0)]338		#[pallet::weight(T::WeightInfo::add_registrar(T::MaxRegistrars::get()))]339		pub fn add_registrar(340			origin: OriginFor<T>,341			account: AccountIdLookupOf<T>,342		) -> DispatchResultWithPostInfo {343			T::RegistrarOrigin::ensure_origin(origin)?;344			let account = T::Lookup::lookup(account)?;345346			let (i, registrar_count) = <Registrars<T>>::try_mutate(347				|registrars| -> Result<(RegistrarIndex, usize), DispatchError> {348					registrars349						.try_push(Some(RegistrarInfo {350							account,351							fee: Zero::zero(),352							fields: Default::default(),353						}))354						.map_err(|_| Error::<T>::TooManyRegistrars)?;355					Ok(((registrars.len() - 1) as RegistrarIndex, registrars.len()))356				},357			)?;358359			Self::deposit_event(Event::RegistrarAdded { registrar_index: i });360361			Ok(Some(T::WeightInfo::add_registrar(registrar_count as u32)).into())362		}363364		/// Set an account's identity information and reserve the appropriate deposit.365		///366		/// If the account already has identity information, the deposit is taken as part payment367		/// for the new deposit.368		///369		/// The dispatch origin for this call must be _Signed_.370		///371		/// - `info`: The identity information.372		///373		/// Emits `IdentitySet` if successful.374		///375		/// # <weight>376		/// - `O(X + X' + R)`377		///   - where `X` additional-field-count (deposit-bounded and code-bounded)378		///   - where `R` judgements-count (registrar-count-bounded)379		/// - One balance reserve operation.380		/// - One storage mutation (codec-read `O(X' + R)`, codec-write `O(X + R)`).381		/// - One event.382		/// # </weight>383		#[pallet::call_index(1)]384		#[pallet::weight( T::WeightInfo::set_identity(385			T::MaxRegistrars::get(), // R386			T::MaxAdditionalFields::get(), // X387		))]388		pub fn set_identity(389			origin: OriginFor<T>,390			info: Box<IdentityInfo<T::MaxAdditionalFields>>,391		) -> DispatchResultWithPostInfo {392			let sender = ensure_signed(origin)?;393			let extra_fields = info.additional.len() as u32;394			ensure!(395				extra_fields <= T::MaxAdditionalFields::get(),396				Error::<T>::TooManyFields397			);398			let fd = <BalanceOf<T>>::from(extra_fields) * T::FieldDeposit::get();399400			let mut id = match <IdentityOf<T>>::get(&sender) {401				Some(mut id) => {402					// Only keep non-positive judgements.403					id.judgements.retain(|j| j.1.is_sticky());404					id.info = *info;405					id406				}407				None => Registration {408					info: *info,409					judgements: BoundedVec::default(),410					deposit: Zero::zero(),411				},412			};413414			let old_deposit = id.deposit;415			id.deposit = T::BasicDeposit::get() + fd;416			if id.deposit > old_deposit {417				T::Currency::reserve(&sender, id.deposit - old_deposit)?;418			}419			if old_deposit > id.deposit {420				let err_amount = T::Currency::unreserve(&sender, old_deposit - id.deposit);421				debug_assert!(err_amount.is_zero());422			}423424			let judgements = id.judgements.len();425			<IdentityOf<T>>::insert(&sender, id);426			Self::deposit_event(Event::IdentitySet { who: sender });427428			Ok(Some(T::WeightInfo::set_identity(429				judgements as u32, // R430				extra_fields,      // X431			))432			.into())433		}434435		/// Set the sub-accounts of the sender.436		///437		/// Payment: Any aggregate balance reserved by previous `set_subs` calls will be returned438		/// and an amount `SubAccountDeposit` will be reserved for each item in `subs`.439		///440		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered441		/// identity.442		///443		/// - `subs`: The identity's (new) sub-accounts.444		///445		/// # <weight>446		/// - `O(P + S)`447		///   - where `P` old-subs-count (hard- and deposit-bounded).448		///   - where `S` subs-count (hard- and deposit-bounded).449		/// - At most one balance operations.450		/// - DB:451		///   - `P + S` storage mutations (codec complexity `O(1)`)452		///   - One storage read (codec complexity `O(P)`).453		///   - One storage write (codec complexity `O(S)`).454		///   - One storage-exists (`IdentityOf::contains_key`).455		/// # </weight>456		// TODO: This whole extrinsic screams "not optimized". For example we could457		// filter any overlap between new and old subs, and avoid reading/writing458		// to those values... We could also ideally avoid needing to write to459		// N storage items for N sub accounts. Right now the weight on this function460		// is a large overestimate due to the fact that it could potentially write461		// to 2 x T::MaxSubAccounts::get().462		#[pallet::call_index(2)]463		#[pallet::weight(T::WeightInfo::set_subs_old(T::MaxSubAccounts::get()) // P: Assume max sub accounts removed.464			.saturating_add(T::WeightInfo::set_subs_new(subs.len() as u32)) // S: Assume all subs are new.465		)]466		pub fn set_subs(467			origin: OriginFor<T>,468			subs: Vec<(T::AccountId, Data)>,469		) -> DispatchResultWithPostInfo {470			let sender = ensure_signed(origin)?;471			ensure!(<IdentityOf<T>>::contains_key(&sender), Error::<T>::NotFound);472			ensure!(473				subs.len() <= T::MaxSubAccounts::get() as usize,474				Error::<T>::TooManySubAccounts475			);476477			let (old_deposit, old_ids) = <SubsOf<T>>::get(&sender);478			let new_deposit = T::SubAccountDeposit::get() * <BalanceOf<T>>::from(subs.len() as u32);479480			let not_other_sub = subs481				.iter()482				.filter_map(|i| SuperOf::<T>::get(&i.0))483				.all(|i| i.0 == sender);484			ensure!(not_other_sub, Error::<T>::AlreadyClaimed);485486			if old_deposit < new_deposit {487				T::Currency::reserve(&sender, new_deposit - old_deposit)?;488			} else if old_deposit > new_deposit {489				let err_amount = T::Currency::unreserve(&sender, old_deposit - new_deposit);490				debug_assert!(err_amount.is_zero());491			}492			// do nothing if they're equal.493494			for s in old_ids.iter() {495				<SuperOf<T>>::remove(s);496			}497			let mut ids = BoundedVec::<T::AccountId, T::MaxSubAccounts>::default();498			for (id, name) in subs {499				<SuperOf<T>>::insert(&id, (sender.clone(), name));500				ids.try_push(id)501					.expect("subs length is less than T::MaxSubAccounts; qed");502			}503			let new_subs = ids.len();504505			if ids.is_empty() {506				<SubsOf<T>>::remove(&sender);507			} else {508				<SubsOf<T>>::insert(&sender, (new_deposit, ids));509			}510511			Ok(Some(512				T::WeightInfo::set_subs_old(old_ids.len() as u32) // P: Real number of old accounts removed.513					// S: New subs added514					.saturating_add(T::WeightInfo::set_subs_new(new_subs as u32)),515			)516			.into())517		}518519		/// Clear an account's identity info and all sub-accounts and return all deposits.520		///521		/// Payment: All reserved balances on the account are returned.522		///523		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered524		/// identity.525		///526		/// Emits `IdentityCleared` if successful.527		///528		/// # <weight>529		/// - `O(R + S + X)`530		///   - where `R` registrar-count (governance-bounded).531		///   - where `S` subs-count (hard- and deposit-bounded).532		///   - where `X` additional-field-count (deposit-bounded and code-bounded).533		/// - One balance-unreserve operation.534		/// - `2` storage reads and `S + 2` storage deletions.535		/// - One event.536		/// # </weight>537		#[pallet::call_index(3)]538		#[pallet::weight(T::WeightInfo::clear_identity(539			T::MaxRegistrars::get(), // R540			T::MaxSubAccounts::get(), // S541			T::MaxAdditionalFields::get(), // X542		))]543		pub fn clear_identity(origin: OriginFor<T>) -> DispatchResultWithPostInfo {544			let sender = ensure_signed(origin)?;545546			let (subs_deposit, sub_ids) = <SubsOf<T>>::take(&sender);547			let id = <IdentityOf<T>>::take(&sender).ok_or(Error::<T>::NotNamed)?;548			let deposit = id.total_deposit() + subs_deposit;549			for sub in sub_ids.iter() {550				<SuperOf<T>>::remove(sub);551			}552553			let err_amount = T::Currency::unreserve(&sender, deposit);554			debug_assert!(err_amount.is_zero());555556			Self::deposit_event(Event::IdentityCleared {557				who: sender,558				deposit,559			});560561			Ok(Some(T::WeightInfo::clear_identity(562				id.judgements.len() as u32,      // R563				sub_ids.len() as u32,            // S564				id.info.additional.len() as u32, // X565			))566			.into())567		}568569		/// Request a judgement from a registrar.570		///571		/// Payment: At most `max_fee` will be reserved for payment to the registrar if judgement572		/// given.573		///574		/// The dispatch origin for this call must be _Signed_ and the sender must have a575		/// registered identity.576		///577		/// - `reg_index`: The index of the registrar whose judgement is requested.578		/// - `max_fee`: The maximum fee that may be paid. This should just be auto-populated as:579		///580		/// ```nocompile581		/// Self::registrars().get(reg_index).unwrap().fee582		/// ```583		///584		/// Emits `JudgementRequested` if successful.585		///586		/// # <weight>587		/// - `O(R + X)`.588		/// - One balance-reserve operation.589		/// - Storage: 1 read `O(R)`, 1 mutate `O(X + R)`.590		/// - One event.591		/// # </weight>592		#[pallet::call_index(4)]593		#[pallet::weight(T::WeightInfo::request_judgement(594			T::MaxRegistrars::get(), // R595			T::MaxAdditionalFields::get(), // X596		))]597		pub fn request_judgement(598			origin: OriginFor<T>,599			#[pallet::compact] reg_index: RegistrarIndex,600			#[pallet::compact] max_fee: BalanceOf<T>,601		) -> DispatchResultWithPostInfo {602			let sender = ensure_signed(origin)?;603			let registrars = <Registrars<T>>::get();604			let registrar = registrars605				.get(reg_index as usize)606				.and_then(Option::as_ref)607				.ok_or(Error::<T>::EmptyIndex)?;608			ensure!(max_fee >= registrar.fee, Error::<T>::FeeChanged);609			let mut id = <IdentityOf<T>>::get(&sender).ok_or(Error::<T>::NoIdentity)?;610611			let item = (reg_index, Judgement::FeePaid(registrar.fee));612			match id.judgements.binary_search_by_key(&reg_index, |x| x.0) {613				Ok(i) => {614					if id.judgements[i].1.is_sticky() {615						return Err(Error::<T>::StickyJudgement.into());616					} else {617						id.judgements[i] = item618					}619				}620				Err(i) => id621					.judgements622					.try_insert(i, item)623					.map_err(|_| Error::<T>::TooManyRegistrars)?,624			}625626			T::Currency::reserve(&sender, registrar.fee)?;627628			let judgements = id.judgements.len();629			let extra_fields = id.info.additional.len();630			<IdentityOf<T>>::insert(&sender, id);631632			Self::deposit_event(Event::JudgementRequested {633				who: sender,634				registrar_index: reg_index,635			});636637			Ok(Some(T::WeightInfo::request_judgement(638				judgements as u32,639				extra_fields as u32,640			))641			.into())642		}643644		/// Cancel a previous request.645		///646		/// Payment: A previously reserved deposit is returned on success.647		///648		/// The dispatch origin for this call must be _Signed_ and the sender must have a649		/// registered identity.650		///651		/// - `reg_index`: The index of the registrar whose judgement is no longer requested.652		///653		/// Emits `JudgementUnrequested` if successful.654		///655		/// # <weight>656		/// - `O(R + X)`.657		/// - One balance-reserve operation.658		/// - One storage mutation `O(R + X)`.659		/// - One event660		/// # </weight>661		#[pallet::call_index(5)]662		#[pallet::weight(T::WeightInfo::cancel_request(663			T::MaxRegistrars::get(), // R664			T::MaxAdditionalFields::get(), // X665		))]666		pub fn cancel_request(667			origin: OriginFor<T>,668			reg_index: RegistrarIndex,669		) -> DispatchResultWithPostInfo {670			let sender = ensure_signed(origin)?;671			let mut id = <IdentityOf<T>>::get(&sender).ok_or(Error::<T>::NoIdentity)?;672673			let pos = id674				.judgements675				.binary_search_by_key(&reg_index, |x| x.0)676				.map_err(|_| Error::<T>::NotFound)?;677			let fee = if let Judgement::FeePaid(fee) = id.judgements.remove(pos).1 {678				fee679			} else {680				return Err(Error::<T>::JudgementGiven.into());681			};682683			let err_amount = T::Currency::unreserve(&sender, fee);684			debug_assert!(err_amount.is_zero());685			let judgements = id.judgements.len();686			let extra_fields = id.info.additional.len();687			<IdentityOf<T>>::insert(&sender, id);688689			Self::deposit_event(Event::JudgementUnrequested {690				who: sender,691				registrar_index: reg_index,692			});693694			Ok(Some(T::WeightInfo::cancel_request(695				judgements as u32,696				extra_fields as u32,697			))698			.into())699		}700701		/// Set the fee required for a judgement to be requested from a registrar.702		///703		/// The dispatch origin for this call must be _Signed_ and the sender must be the account704		/// of the registrar whose index is `index`.705		///706		/// - `index`: the index of the registrar whose fee is to be set.707		/// - `fee`: the new fee.708		///709		/// # <weight>710		/// - `O(R)`.711		/// - One storage mutation `O(R)`.712		/// - Benchmark: 7.315 + R * 0.329 µs (min squares analysis)713		/// # </weight>714		#[pallet::call_index(6)]715		#[pallet::weight(T::WeightInfo::set_fee(T::MaxRegistrars::get()))] // R716		pub fn set_fee(717			origin: OriginFor<T>,718			#[pallet::compact] index: RegistrarIndex,719			#[pallet::compact] fee: BalanceOf<T>,720		) -> DispatchResultWithPostInfo {721			let who = ensure_signed(origin)?;722723			let registrars = <Registrars<T>>::mutate(|rs| -> Result<usize, DispatchError> {724				rs.get_mut(index as usize)725					.and_then(|x| x.as_mut())726					.and_then(|r| {727						if r.account == who {728							r.fee = fee;729							Some(())730						} else {731							None732						}733					})734					.ok_or_else(|| DispatchError::from(Error::<T>::InvalidIndex))?;735				Ok(rs.len())736			})?;737			Ok(Some(T::WeightInfo::set_fee(registrars as u32)).into()) // R738		}739740		/// Change the account associated with a registrar.741		///742		/// The dispatch origin for this call must be _Signed_ and the sender must be the account743		/// of the registrar whose index is `index`.744		///745		/// - `index`: the index of the registrar whose fee is to be set.746		/// - `new`: the new account ID.747		///748		/// # <weight>749		/// - `O(R)`.750		/// - One storage mutation `O(R)`.751		/// - Benchmark: 8.823 + R * 0.32 µs (min squares analysis)752		/// # </weight>753		#[pallet::call_index(7)]754		#[pallet::weight(T::WeightInfo::set_account_id(T::MaxRegistrars::get()))] // R755		pub fn set_account_id(756			origin: OriginFor<T>,757			#[pallet::compact] index: RegistrarIndex,758			new: AccountIdLookupOf<T>,759		) -> DispatchResultWithPostInfo {760			let who = ensure_signed(origin)?;761			let new = T::Lookup::lookup(new)?;762763			let registrars = <Registrars<T>>::mutate(|rs| -> Result<usize, DispatchError> {764				rs.get_mut(index as usize)765					.and_then(|x| x.as_mut())766					.and_then(|r| {767						if r.account == who {768							r.account = new;769							Some(())770						} else {771							None772						}773					})774					.ok_or_else(|| DispatchError::from(Error::<T>::InvalidIndex))?;775				Ok(rs.len())776			})?;777			Ok(Some(T::WeightInfo::set_account_id(registrars as u32)).into()) // R778		}779780		/// Set the field information for a registrar.781		///782		/// The dispatch origin for this call must be _Signed_ and the sender must be the account783		/// of the registrar whose index is `index`.784		///785		/// - `index`: the index of the registrar whose fee is to be set.786		/// - `fields`: the fields that the registrar concerns themselves with.787		///788		/// # <weight>789		/// - `O(R)`.790		/// - One storage mutation `O(R)`.791		/// - Benchmark: 7.464 + R * 0.325 µs (min squares analysis)792		/// # </weight>793		#[pallet::call_index(8)]794		#[pallet::weight(T::WeightInfo::set_fields(T::MaxRegistrars::get()))] // R795		pub fn set_fields(796			origin: OriginFor<T>,797			#[pallet::compact] index: RegistrarIndex,798			fields: IdentityFields,799		) -> DispatchResultWithPostInfo {800			let who = ensure_signed(origin)?;801802			let registrars = <Registrars<T>>::mutate(|rs| -> Result<usize, DispatchError> {803				rs.get_mut(index as usize)804					.and_then(|x| x.as_mut())805					.and_then(|r| {806						if r.account == who {807							r.fields = fields;808							Some(())809						} else {810							None811						}812					})813					.ok_or_else(|| DispatchError::from(Error::<T>::InvalidIndex))?;814				Ok(rs.len())815			})?;816			Ok(Some(T::WeightInfo::set_fields(817				registrars as u32, // R818			))819			.into())820		}821822		/// Provide a judgement for an account's identity.823		///824		/// The dispatch origin for this call must be _Signed_ and the sender must be the account825		/// of the registrar whose index is `reg_index`.826		///827		/// - `reg_index`: the index of the registrar whose judgement is being made.828		/// - `target`: the account whose identity the judgement is upon. This must be an account829		///   with a registered identity.830		/// - `judgement`: the judgement of the registrar of index `reg_index` about `target`.831		/// - `identity`: The hash of the [`IdentityInfo`] for that the judgement is provided.832		///833		/// Emits `JudgementGiven` if successful.834		///835		/// # <weight>836		/// - `O(R + X)`.837		/// - One balance-transfer operation.838		/// - Up to one account-lookup operation.839		/// - Storage: 1 read `O(R)`, 1 mutate `O(R + X)`.840		/// - One event.841		/// # </weight>842		#[pallet::call_index(9)]843		#[pallet::weight(T::WeightInfo::provide_judgement(844			T::MaxRegistrars::get(), // R845			T::MaxAdditionalFields::get(), // X846		))]847		pub fn provide_judgement(848			origin: OriginFor<T>,849			#[pallet::compact] reg_index: RegistrarIndex,850			target: AccountIdLookupOf<T>,851			judgement: Judgement<BalanceOf<T>>,852			identity: T::Hash,853		) -> DispatchResultWithPostInfo {854			let sender = ensure_signed(origin)?;855			let target = T::Lookup::lookup(target)?;856			ensure!(!judgement.has_deposit(), Error::<T>::InvalidJudgement);857			<Registrars<T>>::get()858				.get(reg_index as usize)859				.and_then(Option::as_ref)860				.filter(|r| r.account == sender)861				.ok_or(Error::<T>::InvalidIndex)?;862			let mut id = <IdentityOf<T>>::get(&target).ok_or(Error::<T>::InvalidTarget)?;863864			if T::Hashing::hash_of(&id.info) != identity {865				return Err(Error::<T>::JudgementForDifferentIdentity.into());866			}867868			let item = (reg_index, judgement);869			match id.judgements.binary_search_by_key(&reg_index, |x| x.0) {870				Ok(position) => {871					if let Judgement::FeePaid(fee) = id.judgements[position].1 {872						T::Currency::repatriate_reserved(873							&target,874							&sender,875							fee,876							BalanceStatus::Free,877						)878						.map_err(|_| Error::<T>::JudgementPaymentFailed)?;879					}880					id.judgements[position] = item881				}882				Err(position) => id883					.judgements884					.try_insert(position, item)885					.map_err(|_| Error::<T>::TooManyRegistrars)?,886			}887888			let judgements = id.judgements.len();889			let extra_fields = id.info.additional.len();890			<IdentityOf<T>>::insert(&target, id);891			Self::deposit_event(Event::JudgementGiven {892				target,893				registrar_index: reg_index,894			});895896			Ok(Some(T::WeightInfo::provide_judgement(897				judgements as u32,898				extra_fields as u32,899			))900			.into())901		}902903		/// Remove an account's identity and sub-account information and slash the deposits.904		///905		/// Payment: Reserved balances from `set_subs` and `set_identity` are slashed and handled by906		/// `Slash`. Verification request deposits are not returned; they should be cancelled907		/// manually using `cancel_request`.908		///909		/// The dispatch origin for this call must match `T::ForceOrigin`.910		///911		/// - `target`: the account whose identity the judgement is upon. This must be an account912		///   with a registered identity.913		///914		/// Emits `IdentityKilled` if successful.915		///916		/// # <weight>917		/// - `O(R + S + X)`.918		/// - One balance-reserve operation.919		/// - `S + 2` storage mutations.920		/// - One event.921		/// # </weight>922		#[pallet::call_index(10)]923		#[pallet::weight(T::WeightInfo::kill_identity(924			T::MaxRegistrars::get(), // R925			T::MaxSubAccounts::get(), // S926			T::MaxAdditionalFields::get(), // X927		))]928		pub fn kill_identity(929			origin: OriginFor<T>,930			target: AccountIdLookupOf<T>,931		) -> DispatchResultWithPostInfo {932			T::ForceOrigin::ensure_origin(origin)?;933934			// Figure out who we're meant to be clearing.935			let target = T::Lookup::lookup(target)?;936			// Grab their deposit (and check that they have one).937			let (subs_deposit, sub_ids) = <SubsOf<T>>::take(&target);938			let id = <IdentityOf<T>>::take(&target).ok_or(Error::<T>::NotNamed)?;939			let deposit = id.total_deposit() + subs_deposit;940			for sub in sub_ids.iter() {941				<SuperOf<T>>::remove(sub);942			}943			// Slash their deposit from them.944			T::Slashed::on_unbalanced(T::Currency::slash_reserved(&target, deposit).0);945946			Self::deposit_event(Event::IdentityKilled {947				who: target,948				deposit,949			});950951			Ok(Some(T::WeightInfo::kill_identity(952				id.judgements.len() as u32,      // R953				sub_ids.len() as u32,            // S954				id.info.additional.len() as u32, // X955			))956			.into())957		}958959		/// Add the given account to the sender's subs.960		///961		/// Payment: Balance reserved by a previous `set_subs` call for one sub will be repatriated962		/// to the sender.963		///964		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered965		/// sub identity of `sub`.966		#[pallet::call_index(11)]967		#[pallet::weight(T::WeightInfo::add_sub(T::MaxSubAccounts::get()))]968		pub fn add_sub(969			origin: OriginFor<T>,970			sub: AccountIdLookupOf<T>,971			data: Data,972		) -> DispatchResult {973			let sender = ensure_signed(origin)?;974			let sub = T::Lookup::lookup(sub)?;975			ensure!(976				IdentityOf::<T>::contains_key(&sender),977				Error::<T>::NoIdentity978			);979980			// Check if it's already claimed as sub-identity.981			ensure!(982				!SuperOf::<T>::contains_key(&sub),983				Error::<T>::AlreadyClaimed984			);985986			SubsOf::<T>::try_mutate(&sender, |(ref mut subs_deposit, ref mut sub_ids)| {987				// Ensure there is space and that the deposit is paid.988				ensure!(989					sub_ids.len() < T::MaxSubAccounts::get() as usize,990					Error::<T>::TooManySubAccounts991				);992				let deposit = T::SubAccountDeposit::get();993				T::Currency::reserve(&sender, deposit)?;994995				SuperOf::<T>::insert(&sub, (sender.clone(), data));996				sub_ids997					.try_push(sub.clone())998					.expect("sub ids length checked above; qed");999				*subs_deposit = subs_deposit.saturating_add(deposit);10001001				Self::deposit_event(Event::SubIdentityAdded {1002					sub,1003					main: sender.clone(),1004					deposit,1005				});1006				Ok(())1007			})1008		}10091010		/// Alter the associated name of the given sub-account.1011		///1012		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered1013		/// sub identity of `sub`.1014		#[pallet::call_index(12)]1015		#[pallet::weight(T::WeightInfo::rename_sub(T::MaxSubAccounts::get()))]1016		pub fn rename_sub(1017			origin: OriginFor<T>,1018			sub: AccountIdLookupOf<T>,1019			data: Data,1020		) -> DispatchResult {1021			let sender = ensure_signed(origin)?;1022			let sub = T::Lookup::lookup(sub)?;1023			ensure!(1024				IdentityOf::<T>::contains_key(&sender),1025				Error::<T>::NoIdentity1026			);1027			ensure!(1028				SuperOf::<T>::get(&sub).map_or(false, |x| x.0 == sender),1029				Error::<T>::NotOwned1030			);1031			SuperOf::<T>::insert(&sub, (sender, data));1032			Ok(())1033		}10341035		/// Remove the given account from the sender's subs.1036		///1037		/// Payment: Balance reserved by a previous `set_subs` call for one sub will be repatriated1038		/// to the sender.1039		///1040		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered1041		/// sub identity of `sub`.1042		#[pallet::call_index(13)]1043		#[pallet::weight(T::WeightInfo::remove_sub(T::MaxSubAccounts::get()))]1044		pub fn remove_sub(origin: OriginFor<T>, sub: AccountIdLookupOf<T>) -> DispatchResult {1045			let sender = ensure_signed(origin)?;1046			ensure!(1047				IdentityOf::<T>::contains_key(&sender),1048				Error::<T>::NoIdentity1049			);1050			let sub = T::Lookup::lookup(sub)?;1051			let (sup, _) = SuperOf::<T>::get(&sub).ok_or(Error::<T>::NotSub)?;1052			ensure!(sup == sender, Error::<T>::NotOwned);1053			SuperOf::<T>::remove(&sub);1054			SubsOf::<T>::mutate(&sup, |(ref mut subs_deposit, ref mut sub_ids)| {1055				sub_ids.retain(|x| x != &sub);1056				let deposit = T::SubAccountDeposit::get().min(*subs_deposit);1057				*subs_deposit -= deposit;1058				let err_amount = T::Currency::unreserve(&sender, deposit);1059				debug_assert!(err_amount.is_zero());1060				Self::deposit_event(Event::SubIdentityRemoved {1061					sub,1062					main: sender,1063					deposit,1064				});1065			});1066			Ok(())1067		}10681069		/// Remove the sender as a sub-account.1070		///1071		/// Payment: Balance reserved by a previous `set_subs` call for one sub will be repatriated1072		/// to the sender (*not* the original depositor).1073		///1074		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered1075		/// super-identity.1076		///1077		/// NOTE: This should not normally be used, but is provided in the case that the non-1078		/// controller of an account is maliciously registered as a sub-account.1079		#[pallet::call_index(14)]1080		#[pallet::weight(T::WeightInfo::quit_sub(T::MaxSubAccounts::get()))]1081		pub fn quit_sub(origin: OriginFor<T>) -> DispatchResult {1082			let sender = ensure_signed(origin)?;1083			let (sup, _) = SuperOf::<T>::take(&sender).ok_or(Error::<T>::NotSub)?;1084			SubsOf::<T>::mutate(&sup, |(ref mut subs_deposit, ref mut sub_ids)| {1085				sub_ids.retain(|x| x != &sender);1086				let deposit = T::SubAccountDeposit::get().min(*subs_deposit);1087				*subs_deposit -= deposit;1088				let _ =1089					T::Currency::repatriate_reserved(&sup, &sender, deposit, BalanceStatus::Free);1090				Self::deposit_event(Event::SubIdentityRevoked {1091					sub: sender,1092					main: sup.clone(),1093					deposit,1094				});1095			});1096			Ok(())1097		}10981099		/// Set identities to be associated with the provided accounts as force origin.1100		///1101		/// This is not meant to operate in tandem with the identity pallet as is,1102		/// and be instead used to keep identities made and verified externally,1103		/// forbidden from interacting with an ordinary user, since it ignores any safety mechanism.1104		#[pallet::call_index(15)]1105		#[pallet::weight(T::WeightInfo::force_insert_identities(1106			T::MaxAdditionalFields::get(), // X1107			identities.len() as u32, // N1108		))]1109		pub fn force_insert_identities(1110			origin: OriginFor<T>,1111			identities: Vec<(1112				T::AccountId,1113				Registration<BalanceOf<T>, T::MaxRegistrars, T::MaxAdditionalFields>,1114			)>,1115		) -> DispatchResult {1116			T::ForceOrigin::ensure_origin(origin)?;1117			for identity in identities.clone() {1118				IdentityOf::<T>::insert(identity.0, identity.1);1119			}1120			Self::deposit_event(Event::IdentitiesInserted {1121				amount: identities.len() as u32,1122			});1123			Ok(())1124		}11251126		/// Remove identities associated with the provided accounts as force origin.1127		///1128		/// This is not meant to operate in tandem with the identity pallet as is,1129		/// and be instead used to keep identities made and verified externally,1130		/// forbidden from interacting with an ordinary user, since it ignores any safety mechanism.1131		#[pallet::call_index(16)]1132		#[pallet::weight(T::WeightInfo::force_remove_identities(1133			T::MaxAdditionalFields::get(), // X1134			identities.len() as u32, // N1135		))]1136		pub fn force_remove_identities(1137			origin: OriginFor<T>,1138			identities: Vec<T::AccountId>,1139		) -> DispatchResult {1140			T::ForceOrigin::ensure_origin(origin)?;1141			for identity in identities.clone() {1142				let (_, sub_ids) = <SubsOf<T>>::take(&identity);1143				<IdentityOf<T>>::remove(&identity);1144				for sub in sub_ids.iter() {1145					<SuperOf<T>>::remove(sub);1146				}1147			}1148			Self::deposit_event(Event::IdentitiesRemoved {1149				amount: identities.len() as u32,1150			});1151			Ok(())1152		}11531154		/// Set sub-identities to be associated with the provided accounts as force origin.1155		///1156		/// This is not meant to operate in tandem with the identity pallet as is,1157		/// and be instead used to keep identities made and verified externally,1158		/// forbidden from interacting with an ordinary user, since it ignores any safety mechanism.1159		#[pallet::call_index(17)]1160		#[pallet::weight(T::WeightInfo::force_set_subs(1161			T::MaxSubAccounts::get(), // S1162			subs.len() as u32, // N1163		))]1164		pub fn force_set_subs(1165			origin: OriginFor<T>,1166			subs: Vec<(1167				T::AccountId,1168				(1169					BalanceOf<T>,1170					BoundedVec<(T::AccountId, Data), T::MaxSubAccounts>,1171				),1172			)>,1173		) -> DispatchResult {1174			T::ForceOrigin::ensure_origin(origin)?;1175			for identity in subs.clone() {1176				let account = identity.0;1177				let (_, old_subs) = <SubsOf<T>>::get(&account);1178				for old_sub in old_subs {1179					<SuperOf<T>>::remove(old_sub);1180				}11811182				let mut ids = BoundedVec::<T::AccountId, T::MaxSubAccounts>::default();1183				for (id, name) in identity.1 .1 {1184					<SuperOf<T>>::insert(&id, (account.clone(), name));1185					ids.try_push(id)1186						.expect("subs length is less than T::MaxSubAccounts; qed");1187				}11881189				if ids.is_empty() {1190					<SubsOf<T>>::remove(&account);1191				} else {1192					<SubsOf<T>>::insert(account, (identity.1 .0, ids));1193				}1194			}1195			Self::deposit_event(Event::SubIdentitiesInserted {1196				amount: subs.len() as u32,1197			});1198			Ok(())1199		}1200	}1201}12021203impl<T: Config> Pallet<T> {1204	/// Get the subs of an account.1205	pub fn subs(who: &T::AccountId) -> Vec<(T::AccountId, Data)> {1206		SubsOf::<T>::get(who)1207			.11208			.into_iter()1209			.filter_map(|a| SuperOf::<T>::get(&a).map(|x| (a, x.1)))1210			.collect()1211	}12121213	/// Check if the account has corresponding identity information by the identity field.1214	pub fn has_identity(who: &T::AccountId, fields: u64) -> bool {1215		IdentityOf::<T>::get(who).map_or(false, |registration| {1216			(registration.info.fields().0.bits() & fields) == fields1217		})1218	}1219}
modifiedpallets/identity/src/weights.rsdiffbeforeafterboth
--- a/pallets/identity/src/weights.rs
+++ b/pallets/identity/src/weights.rs
@@ -78,6 +78,7 @@
 	fn kill_identity(r: u32, s: u32, x: u32, ) -> Weight;
 	fn force_insert_identities(x: u32, n: u32, ) -> Weight;
 	fn force_remove_identities(x: u32, n: u32, ) -> Weight;
+	fn force_set_subs(s: u32, n: u32, ) -> Weight;
 	fn add_sub(s: u32, ) -> Weight;
 	fn rename_sub(s: u32, ) -> Weight;
 	fn remove_sub(s: u32, ) -> Weight;
@@ -273,6 +274,20 @@
 			.saturating_add(T::DbWeight::get().reads(1 as u64))
 			.saturating_add(T::DbWeight::get().writes(1 as u64).saturating_mul(n as u64))
 	}
+	// Storage: Identity IdentityOf (r:1 w:1)
+	// todo:collator
+	/// The range of component `s` is `[0, 100]`.
+	/// The range of component `n` is `[0, 600]`.
+	fn force_set_subs(s: u32, n: u32) -> Weight {
+		// Minimum execution time: 41_872 nanoseconds.
+		Weight::from_ref_time(40_230_216 as u64)
+			// Standard Error: 2_342
+			.saturating_add(Weight::from_ref_time(145_168 as u64))
+			// Standard Error: 457
+			.saturating_add(Weight::from_ref_time(291_732 as u64).saturating_mul(s as u64))
+			.saturating_add(T::DbWeight::get().reads(1 as u64))
+			.saturating_add(T::DbWeight::get().writes(1 as u64).saturating_mul(n as u64))
+	}
 	// Storage: Identity IdentityOf (r:1 w:0)
 	// Storage: Identity SuperOf (r:1 w:1)
 	// Storage: Identity SubsOf (r:1 w:1)
@@ -509,6 +524,20 @@
 			.saturating_add(RocksDbWeight::get().reads(1 as u64))
 			.saturating_add(RocksDbWeight::get().writes(1 as u64).saturating_mul(n as u64))
 	}
+	// Storage: Identity IdentityOf (r:1 w:1)
+	// todo:collator
+	/// The range of component `xs is `[0, 100]`.
+	/// The range of component `n` is `[0, 600]`.
+	fn force_set_subs(s: u32, n: u32) -> Weight {
+		// Minimum execution time: 41_872 nanoseconds.
+		Weight::from_ref_time(40_230_216 as u64)
+			// Standard Error: 2_342
+			.saturating_add(Weight::from_ref_time(145_168 as u64))
+			// Standard Error: 457
+			.saturating_add(Weight::from_ref_time(291_732 as u64).saturating_mul(s as u64))
+			.saturating_add(RocksDbWeight::get().reads(1 as u64))
+			.saturating_add(RocksDbWeight::get().writes(1 as u64).saturating_mul(n as u64))
+	}
 	// Storage: Identity IdentityOf (r:1 w:0)
 	// Storage: Identity SuperOf (r:1 w:1)
 	// Storage: Identity SubsOf (r:1 w:1)