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

difftreelog

source

pallets/identity/src/lib.rs35.5 KiBsourcehistory
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}