Skip to main content

pallet_identity/
lib.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! # Identity Pallet
19//!
20//! - [`Config`]
21//! - [`Call`]
22//!
23//! ## Overview
24//!
25//! A federated naming system, allowing for multiple registrars to be added from a specified origin.
26//! Registrars can set a fee to provide identity-verification service. Anyone can put forth a
27//! proposed identity for a fixed deposit and ask for review by any number of registrars (paying
28//! each of their fees). Registrar judgements are given as an `enum`, allowing for sophisticated,
29//! multi-tier opinions.
30//!
31//! Some judgements are identified as *sticky*, which means they cannot be removed except by
32//! complete removal of the identity, or by the registrar. Judgements are allowed to represent a
33//! portion of funds that have been reserved for the registrar.
34//!
35//! A super-user can remove accounts and in doing so, slash the deposit.
36//!
37//! All accounts may also have a limited number of sub-accounts which may be specified by the owner;
38//! by definition, these have equivalent ownership and each has an individual name.
39//!
40//! The number of registrars should be limited, and the deposit made sufficiently large, to ensure
41//! no state-bloat attack is viable.
42//!
43//! ### Usernames
44//!
45//! The pallet provides functionality for username authorities to issue usernames, which are
46//! independent of the identity information functionality; an account can set:
47//! - an identity without setting a username
48//! - a username without setting an identity
49//! - an identity and a username
50//!
51//! The username functionality implemented in this pallet is meant to be a user friendly lookup of
52//! accounts. There are mappings in both directions, "account -> username" and "username ->
53//! account".
54//!
55//! Usernames are granted by authorities and grouped by suffix, with each suffix being administered
56//! by one authority. To grant a username, a username authority can either:
57//! - be given an allocation by governance of a specific amount of usernames to issue for free,
58//!   without any deposit associated with storage costs;
59//! - put up a deposit for each username it issues (usually a subsidized, reduced deposit, relative
60//!   to other deposits in the system)
61//!
62//! Users can have multiple usernames that map to the same `AccountId`, however one `AccountId` can
63//! only map to a single username, known as the _primary_. This primary username will be the result
64//! of a lookup in the [UsernameOf] map for any given account.
65//!
66//! ## Interface
67//!
68//! ### Dispatchable Functions
69//!
70//! #### For General Users
71//! * `set_identity` - Set the associated identity of an account; a small deposit is reserved if not
72//!   already taken.
73//! * `clear_identity` - Remove an account's associated identity; the deposit is returned.
74//! * `request_judgement` - Request a judgement from a registrar, paying a fee.
75//! * `cancel_request` - Cancel the previous request for a judgement.
76//! * `accept_username` - Accept a username issued by a username authority.
77//! * `remove_expired_approval` - Remove a username that was issued but never accepted.
78//! * `set_primary_username` - Set a given username as an account's primary.
79//! * `remove_username` - Remove a username after its grace period has ended.
80//!
81//! #### For General Users with Sub-Identities
82//! * `set_subs` - Set the sub-accounts of an identity.
83//! * `add_sub` - Add a sub-identity to an identity.
84//! * `remove_sub` - Remove a sub-identity of an identity.
85//! * `rename_sub` - Rename a sub-identity of an identity.
86//! * `quit_sub` - Remove a sub-identity of an identity (called by the sub-identity).
87//!
88//! #### For Registrars
89//! * `set_fee` - Set the fee required to be paid for a judgement to be given by the registrar.
90//! * `set_fields` - Set the fields that a registrar cares about in their judgements.
91//! * `provide_judgement` - Provide a judgement to an identity.
92//!
93//! #### For Username Authorities
94//! * `set_username_for` - Set a username for a given account. The account must approve it.
95//! * `unbind_username` - Start the grace period for a username.
96//!
97//! #### For Superusers
98//! * `add_registrar` - Add a new registrar to the system.
99//! * `kill_identity` - Forcibly remove the associated identity; the deposit is lost.
100//! * `add_username_authority` - Add an account with the ability to issue usernames.
101//! * `remove_username_authority` - Remove an account with the ability to issue usernames.
102//! * `kill_username` - Forcibly remove a username.
103//!
104//! [`Call`]: ./enum.Call.html
105//! [`Config`]: ./trait.Config.html
106
107#![cfg_attr(not(feature = "std"), no_std)]
108
109mod benchmarking;
110pub mod legacy;
111pub mod migration;
112#[cfg(test)]
113mod tests;
114mod types;
115pub mod weights;
116
117extern crate alloc;
118
119use crate::types::{AuthorityProperties, Provider, Suffix, Username, UsernameInformation};
120use alloc::{boxed::Box, vec::Vec};
121use codec::Encode;
122use frame_support::{
123	ensure,
124	pallet_prelude::{DispatchError, DispatchResult},
125	traits::{
126		BalanceStatus, Currency, Defensive, Get, OnUnbalanced, ReservableCurrency, StorageVersion,
127	},
128	BoundedVec,
129};
130use frame_system::pallet_prelude::*;
131pub use pallet::*;
132use sp_runtime::traits::{
133	AppendZerosInput, Hash, IdentifyAccount, Saturating, StaticLookup, Verify, Zero,
134};
135pub use types::{
136	Data, IdentityInformationProvider, Judgement, RegistrarIndex, RegistrarInfo, Registration,
137};
138pub use weights::WeightInfo;
139
140type BalanceOf<T> =
141	<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
142type NegativeImbalanceOf<T> = <<T as Config>::Currency as Currency<
143	<T as frame_system::Config>::AccountId,
144>>::NegativeImbalance;
145type AccountIdLookupOf<T> = <<T as frame_system::Config>::Lookup as StaticLookup>::Source;
146type ProviderOf<T> = Provider<BalanceOf<T>>;
147
148#[frame_support::pallet]
149pub mod pallet {
150	use super::*;
151	use frame_support::pallet_prelude::*;
152
153	#[cfg(feature = "runtime-benchmarks")]
154	pub trait BenchmarkHelper<Public, Signature> {
155		fn sign_message(message: &[u8]) -> (Public, Signature);
156	}
157	#[cfg(feature = "runtime-benchmarks")]
158	impl BenchmarkHelper<sp_runtime::MultiSigner, sp_runtime::MultiSignature> for () {
159		fn sign_message(message: &[u8]) -> (sp_runtime::MultiSigner, sp_runtime::MultiSignature) {
160			let public = sp_io::crypto::sr25519_generate(0.into(), None);
161			let signature = sp_runtime::MultiSignature::Sr25519(
162				sp_io::crypto::sr25519_sign(
163					0.into(),
164					&public.into_account().try_into().unwrap(),
165					message,
166				)
167				.unwrap(),
168			);
169			(public.into(), signature)
170		}
171	}
172
173	#[pallet::config]
174	pub trait Config: frame_system::Config {
175		/// The overarching event type.
176		#[allow(deprecated)]
177		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
178
179		/// The currency trait.
180		type Currency: ReservableCurrency<Self::AccountId>;
181
182		/// The amount held on deposit for a registered identity.
183		#[pallet::constant]
184		type BasicDeposit: Get<BalanceOf<Self>>;
185
186		/// The amount held on deposit per encoded byte for a registered identity.
187		#[pallet::constant]
188		type ByteDeposit: Get<BalanceOf<Self>>;
189
190		/// The amount held on deposit per registered username. This value should change only in
191		/// runtime upgrades with proper migration of existing deposits.
192		#[pallet::constant]
193		type UsernameDeposit: Get<BalanceOf<Self>>;
194
195		/// The amount held on deposit for a registered subaccount. This should account for the fact
196		/// that one storage item's value will increase by the size of an account ID, and there will
197		/// be another trie item whose value is the size of an account ID plus 32 bytes.
198		#[pallet::constant]
199		type SubAccountDeposit: Get<BalanceOf<Self>>;
200
201		/// The maximum number of sub-accounts allowed per identified account.
202		#[pallet::constant]
203		type MaxSubAccounts: Get<u32>;
204
205		/// Structure holding information about an identity.
206		type IdentityInformation: IdentityInformationProvider;
207
208		/// Maximum number of registrars allowed in the system. Needed to bound the complexity
209		/// of, e.g., updating judgements.
210		#[pallet::constant]
211		type MaxRegistrars: Get<u32>;
212
213		/// What to do with slashed funds.
214		type Slashed: OnUnbalanced<NegativeImbalanceOf<Self>>;
215
216		/// The origin which may forcibly set or remove a name. Root can always do this.
217		type ForceOrigin: EnsureOrigin<Self::RuntimeOrigin>;
218
219		/// The origin which may add or remove registrars. Root can always do this.
220		type RegistrarOrigin: EnsureOrigin<Self::RuntimeOrigin>;
221
222		/// Signature type for pre-authorizing usernames off-chain.
223		///
224		/// Can verify whether an `Self::SigningPublicKey` created a signature.
225		type OffchainSignature: Verify<Signer = Self::SigningPublicKey> + Parameter;
226
227		/// Public key that corresponds to an on-chain `Self::AccountId`.
228		type SigningPublicKey: IdentifyAccount<AccountId = Self::AccountId>;
229
230		/// The origin which may add or remove username authorities. Root can always do this.
231		type UsernameAuthorityOrigin: EnsureOrigin<Self::RuntimeOrigin>;
232
233		/// The number of blocks within which a username grant must be accepted.
234		#[pallet::constant]
235		type PendingUsernameExpiration: Get<BlockNumberFor<Self>>;
236
237		/// The number of blocks that must pass to enable the permanent deletion of a username by
238		/// its respective authority.
239		#[pallet::constant]
240		type UsernameGracePeriod: Get<BlockNumberFor<Self>>;
241
242		/// The maximum length of a suffix.
243		#[pallet::constant]
244		type MaxSuffixLength: Get<u32>;
245
246		/// The maximum length of a username, including its suffix and any system-added delimiters.
247		#[pallet::constant]
248		type MaxUsernameLength: Get<u32>;
249
250		/// A set of helper functions for benchmarking.
251		/// The default configuration `()` uses the `SR25519` signature schema.
252		#[cfg(feature = "runtime-benchmarks")]
253		type BenchmarkHelper: BenchmarkHelper<Self::SigningPublicKey, Self::OffchainSignature>;
254
255		/// Weight information for extrinsics in this pallet.
256		type WeightInfo: WeightInfo;
257	}
258
259	const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);
260
261	#[pallet::pallet]
262	#[pallet::storage_version(STORAGE_VERSION)]
263	pub struct Pallet<T>(_);
264
265	/// Information that is pertinent to identify the entity behind an account. First item is the
266	/// registration, second is the account's primary username.
267	///
268	/// TWOX-NOTE: OK ― `AccountId` is a secure hash.
269	#[pallet::storage]
270	pub type IdentityOf<T: Config> = StorageMap<
271		_,
272		Twox64Concat,
273		T::AccountId,
274		Registration<BalanceOf<T>, T::MaxRegistrars, T::IdentityInformation>,
275		OptionQuery,
276	>;
277
278	/// Identifies the primary username of an account.
279	#[pallet::storage]
280	pub type UsernameOf<T: Config> =
281		StorageMap<_, Twox64Concat, T::AccountId, Username<T>, OptionQuery>;
282
283	/// The super-identity of an alternative "sub" identity together with its name, within that
284	/// context. If the account is not some other account's sub-identity, then just `None`.
285	#[pallet::storage]
286	pub type SuperOf<T: Config> =
287		StorageMap<_, Blake2_128Concat, T::AccountId, (T::AccountId, Data), OptionQuery>;
288
289	/// Alternative "sub" identities of this account.
290	///
291	/// The first item is the deposit, the second is a vector of the accounts.
292	///
293	/// TWOX-NOTE: OK ― `AccountId` is a secure hash.
294	#[pallet::storage]
295	pub type SubsOf<T: Config> = StorageMap<
296		_,
297		Twox64Concat,
298		T::AccountId,
299		(BalanceOf<T>, BoundedVec<T::AccountId, T::MaxSubAccounts>),
300		ValueQuery,
301	>;
302
303	/// The set of registrars. Not expected to get very big as can only be added through a
304	/// special origin (likely a council motion).
305	///
306	/// The index into this can be cast to `RegistrarIndex` to get a valid value.
307	#[pallet::storage]
308	pub type Registrars<T: Config> = StorageValue<
309		_,
310		BoundedVec<
311			Option<
312				RegistrarInfo<
313					BalanceOf<T>,
314					T::AccountId,
315					<T::IdentityInformation as IdentityInformationProvider>::FieldsIdentifier,
316				>,
317			>,
318			T::MaxRegistrars,
319		>,
320		ValueQuery,
321	>;
322
323	/// A map of the accounts who are authorized to grant usernames.
324	#[pallet::storage]
325	pub type AuthorityOf<T: Config> =
326		StorageMap<_, Twox64Concat, Suffix<T>, AuthorityProperties<T::AccountId>, OptionQuery>;
327
328	/// Reverse lookup from `username` to the `AccountId` that has registered it and the provider of
329	/// the username. The `owner` value should be a key in the `UsernameOf` map, but it may not if
330	/// the user has cleared their username or it has been removed.
331	///
332	/// Multiple usernames may map to the same `AccountId`, but `UsernameOf` will only map to one
333	/// primary username.
334	#[pallet::storage]
335	pub type UsernameInfoOf<T: Config> = StorageMap<
336		_,
337		Blake2_128Concat,
338		Username<T>,
339		UsernameInformation<T::AccountId, BalanceOf<T>>,
340		OptionQuery,
341	>;
342
343	/// Usernames that an authority has granted, but that the account controller has not confirmed
344	/// that they want it. Used primarily in cases where the `AccountId` cannot provide a signature
345	/// because they are a pure proxy, multisig, etc. In order to confirm it, they should call
346	/// [accept_username](`Call::accept_username`).
347	///
348	/// First tuple item is the account and second is the acceptance deadline.
349	#[pallet::storage]
350	pub type PendingUsernames<T: Config> = StorageMap<
351		_,
352		Blake2_128Concat,
353		Username<T>,
354		(T::AccountId, BlockNumberFor<T>, ProviderOf<T>),
355		OptionQuery,
356	>;
357
358	/// Usernames for which the authority that granted them has started the removal process by
359	/// unbinding them. Each unbinding username maps to its grace period expiry, which is the first
360	/// block in which the username could be deleted through a
361	/// [remove_username](`Call::remove_username`) call.
362	#[pallet::storage]
363	pub type UnbindingUsernames<T: Config> =
364		StorageMap<_, Blake2_128Concat, Username<T>, BlockNumberFor<T>, OptionQuery>;
365
366	#[pallet::error]
367	pub enum Error<T> {
368		/// Too many subs-accounts.
369		TooManySubAccounts,
370		/// Account isn't found.
371		NotFound,
372		/// Account isn't named.
373		NotNamed,
374		/// Empty index.
375		EmptyIndex,
376		/// Fee is changed.
377		FeeChanged,
378		/// No identity found.
379		NoIdentity,
380		/// Sticky judgement.
381		StickyJudgement,
382		/// Judgement given.
383		JudgementGiven,
384		/// Invalid judgement.
385		InvalidJudgement,
386		/// The index is invalid.
387		InvalidIndex,
388		/// The target is invalid.
389		InvalidTarget,
390		/// Maximum amount of registrars reached. Cannot add any more.
391		TooManyRegistrars,
392		/// Account ID is already named.
393		AlreadyClaimed,
394		/// Sender is not a sub-account.
395		NotSub,
396		/// Sub-account isn't owned by sender.
397		NotOwned,
398		/// The provided judgement was for a different identity.
399		JudgementForDifferentIdentity,
400		/// Error that occurs when there is an issue paying for judgement.
401		JudgementPaymentFailed,
402		/// The provided suffix is too long.
403		InvalidSuffix,
404		/// The sender does not have permission to issue a username.
405		NotUsernameAuthority,
406		/// The authority cannot allocate any more usernames.
407		NoAllocation,
408		/// The signature on a username was not valid.
409		InvalidSignature,
410		/// Setting this username requires a signature, but none was provided.
411		RequiresSignature,
412		/// The username does not meet the requirements.
413		InvalidUsername,
414		/// The username is already taken.
415		UsernameTaken,
416		/// The requested username does not exist.
417		NoUsername,
418		/// The username cannot be forcefully removed because it can still be accepted.
419		NotExpired,
420		/// The username cannot be removed because it's still in the grace period.
421		TooEarly,
422		/// The username cannot be removed because it is not unbinding.
423		NotUnbinding,
424		/// The username cannot be unbound because it is already unbinding.
425		AlreadyUnbinding,
426		/// The action cannot be performed because of insufficient privileges (e.g. authority
427		/// trying to unbind a username provided by the system).
428		InsufficientPrivileges,
429	}
430
431	#[pallet::event]
432	#[pallet::generate_deposit(pub(super) fn deposit_event)]
433	pub enum Event<T: Config> {
434		/// A name was set or reset (which will remove all judgements).
435		IdentitySet { who: T::AccountId },
436		/// A name was cleared, and the given balance returned.
437		IdentityCleared { who: T::AccountId, deposit: BalanceOf<T> },
438		/// A name was removed and the given balance slashed.
439		IdentityKilled { who: T::AccountId, deposit: BalanceOf<T> },
440		/// A judgement was asked from a registrar.
441		JudgementRequested { who: T::AccountId, registrar_index: RegistrarIndex },
442		/// A judgement request was retracted.
443		JudgementUnrequested { who: T::AccountId, registrar_index: RegistrarIndex },
444		/// A judgement was given by a registrar.
445		JudgementGiven { target: T::AccountId, registrar_index: RegistrarIndex },
446		/// A registrar was added.
447		RegistrarAdded { registrar_index: RegistrarIndex },
448		/// A sub-identity was added to an identity and the deposit paid.
449		SubIdentityAdded { sub: T::AccountId, main: T::AccountId, deposit: BalanceOf<T> },
450		/// An account's sub-identities were set (in bulk).
451		SubIdentitiesSet { main: T::AccountId, number_of_subs: u32, new_deposit: BalanceOf<T> },
452		/// A given sub-account's associated name was changed by its super-identity.
453		SubIdentityRenamed { sub: T::AccountId, main: T::AccountId },
454		/// A sub-identity was removed from an identity and the deposit freed.
455		SubIdentityRemoved { sub: T::AccountId, main: T::AccountId, deposit: BalanceOf<T> },
456		/// A sub-identity was cleared, and the given deposit repatriated from the
457		/// main identity account to the sub-identity account.
458		SubIdentityRevoked { sub: T::AccountId, main: T::AccountId, deposit: BalanceOf<T> },
459		/// A username authority was added.
460		AuthorityAdded { authority: T::AccountId },
461		/// A username authority was removed.
462		AuthorityRemoved { authority: T::AccountId },
463		/// A username was set for `who`.
464		UsernameSet { who: T::AccountId, username: Username<T> },
465		/// A username was queued, but `who` must accept it prior to `expiration`.
466		UsernameQueued { who: T::AccountId, username: Username<T>, expiration: BlockNumberFor<T> },
467		/// A queued username passed its expiration without being claimed and was removed.
468		PreapprovalExpired { whose: T::AccountId },
469		/// A username was set as a primary and can be looked up from `who`.
470		PrimaryUsernameSet { who: T::AccountId, username: Username<T> },
471		/// A dangling username (as in, a username corresponding to an account that has removed its
472		/// identity) has been removed.
473		DanglingUsernameRemoved { who: T::AccountId, username: Username<T> },
474		/// A username has been unbound.
475		UsernameUnbound { username: Username<T> },
476		/// A username has been removed.
477		UsernameRemoved { username: Username<T> },
478		/// A username has been killed.
479		UsernameKilled { username: Username<T> },
480	}
481
482	#[pallet::call]
483	/// Identity pallet declaration.
484	impl<T: Config> Pallet<T> {
485		/// Add a registrar to the system.
486		///
487		/// The dispatch origin for this call must be `T::RegistrarOrigin`.
488		///
489		/// - `account`: the account of the registrar.
490		///
491		/// Emits `RegistrarAdded` if successful.
492		#[pallet::call_index(0)]
493		#[pallet::weight(T::WeightInfo::add_registrar(T::MaxRegistrars::get()))]
494		pub fn add_registrar(
495			origin: OriginFor<T>,
496			account: AccountIdLookupOf<T>,
497		) -> DispatchResultWithPostInfo {
498			T::RegistrarOrigin::ensure_origin(origin)?;
499			let account = T::Lookup::lookup(account)?;
500
501			let (i, registrar_count) = Registrars::<T>::try_mutate(
502				|registrars| -> Result<(RegistrarIndex, usize), DispatchError> {
503					registrars
504						.try_push(Some(RegistrarInfo {
505							account,
506							fee: Zero::zero(),
507							fields: Default::default(),
508						}))
509						.map_err(|_| Error::<T>::TooManyRegistrars)?;
510					Ok(((registrars.len() - 1) as RegistrarIndex, registrars.len()))
511				},
512			)?;
513
514			Self::deposit_event(Event::RegistrarAdded { registrar_index: i });
515
516			Ok(Some(T::WeightInfo::add_registrar(registrar_count as u32)).into())
517		}
518
519		/// Set an account's identity information and reserve the appropriate deposit.
520		///
521		/// If the account already has identity information, the deposit is taken as part payment
522		/// for the new deposit.
523		///
524		/// The dispatch origin for this call must be _Signed_.
525		///
526		/// - `info`: The identity information.
527		///
528		/// Emits `IdentitySet` if successful.
529		#[pallet::call_index(1)]
530		#[pallet::weight(T::WeightInfo::set_identity(T::MaxRegistrars::get()))]
531		pub fn set_identity(
532			origin: OriginFor<T>,
533			info: Box<T::IdentityInformation>,
534		) -> DispatchResultWithPostInfo {
535			let sender = ensure_signed(origin)?;
536
537			let mut id = match IdentityOf::<T>::get(&sender) {
538				Some(mut id) => {
539					// Only keep non-positive judgements.
540					id.judgements.retain(|j| j.1.is_sticky());
541					id.info = *info;
542					id
543				},
544				None => Registration {
545					info: *info,
546					judgements: BoundedVec::default(),
547					deposit: Zero::zero(),
548				},
549			};
550
551			let new_deposit = Self::calculate_identity_deposit(&id.info);
552			let old_deposit = id.deposit;
553			Self::rejig_deposit(&sender, old_deposit, new_deposit)?;
554
555			id.deposit = new_deposit;
556			let judgements = id.judgements.len();
557			IdentityOf::<T>::insert(&sender, id);
558			Self::deposit_event(Event::IdentitySet { who: sender });
559
560			Ok(Some(T::WeightInfo::set_identity(judgements as u32)).into())
561		}
562
563		/// Set the sub-accounts of the sender.
564		///
565		/// Payment: Any aggregate balance reserved by previous `set_subs` calls will be returned
566		/// and an amount `SubAccountDeposit` will be reserved for each item in `subs`.
567		///
568		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered
569		/// identity.
570		///
571		/// - `subs`: The identity's (new) sub-accounts.
572		// TODO: This whole extrinsic screams "not optimized". For example we could
573		// filter any overlap between new and old subs, and avoid reading/writing
574		// to those values... We could also ideally avoid needing to write to
575		// N storage items for N sub accounts. Right now the weight on this function
576		// is a large overestimate due to the fact that it could potentially write
577		// to 2 x T::MaxSubAccounts::get().
578		#[pallet::call_index(2)]
579		#[pallet::weight(T::WeightInfo::set_subs_old(T::MaxSubAccounts::get())
580			.saturating_add(T::WeightInfo::set_subs_new(subs.len() as u32))
581		)]
582		pub fn set_subs(
583			origin: OriginFor<T>,
584			subs: Vec<(T::AccountId, Data)>,
585		) -> DispatchResultWithPostInfo {
586			let sender = ensure_signed(origin)?;
587			ensure!(IdentityOf::<T>::contains_key(&sender), Error::<T>::NotFound);
588			ensure!(
589				subs.len() <= T::MaxSubAccounts::get() as usize,
590				Error::<T>::TooManySubAccounts
591			);
592
593			let (old_deposit, old_ids) = SubsOf::<T>::get(&sender);
594			let new_deposit = Self::subs_deposit(subs.len() as u32);
595
596			let not_other_sub =
597				subs.iter().filter_map(|i| SuperOf::<T>::get(&i.0)).all(|i| i.0 == sender);
598			ensure!(not_other_sub, Error::<T>::AlreadyClaimed);
599
600			if old_deposit < new_deposit {
601				T::Currency::reserve(&sender, new_deposit - old_deposit)?;
602			} else if old_deposit > new_deposit {
603				let err_amount = T::Currency::unreserve(&sender, old_deposit - new_deposit);
604				debug_assert!(err_amount.is_zero());
605			}
606			// do nothing if they're equal.
607
608			for s in old_ids.iter() {
609				SuperOf::<T>::remove(s);
610			}
611			let mut ids = BoundedVec::<T::AccountId, T::MaxSubAccounts>::default();
612			for (id, name) in subs {
613				SuperOf::<T>::insert(&id, (sender.clone(), name));
614				ids.try_push(id).expect("subs length is less than T::MaxSubAccounts; qed");
615			}
616			let new_subs = ids.len();
617
618			if ids.is_empty() {
619				SubsOf::<T>::remove(&sender);
620			} else {
621				SubsOf::<T>::insert(&sender, (new_deposit, ids));
622			}
623
624			Self::deposit_event(Event::SubIdentitiesSet {
625				main: sender,
626				number_of_subs: new_subs as u32,
627				new_deposit,
628			});
629
630			Ok(Some(
631				T::WeightInfo::set_subs_old(old_ids.len() as u32) // P: Real number of old accounts removed.
632					// S: New subs added
633					.saturating_add(T::WeightInfo::set_subs_new(new_subs as u32)),
634			)
635			.into())
636		}
637
638		/// Clear an account's identity info and all sub-accounts and return all deposits.
639		///
640		/// Payment: All reserved balances on the account are returned.
641		///
642		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered
643		/// identity.
644		///
645		/// Emits `IdentityCleared` if successful.
646		#[pallet::call_index(3)]
647		#[pallet::weight(T::WeightInfo::clear_identity(
648			T::MaxRegistrars::get(),
649			T::MaxSubAccounts::get(),
650		))]
651		pub fn clear_identity(origin: OriginFor<T>) -> DispatchResultWithPostInfo {
652			let sender = ensure_signed(origin)?;
653
654			let (subs_deposit, sub_ids) = SubsOf::<T>::take(&sender);
655			let id = IdentityOf::<T>::take(&sender).ok_or(Error::<T>::NoIdentity)?;
656			let deposit = id.total_deposit().saturating_add(subs_deposit);
657			for sub in sub_ids.iter() {
658				SuperOf::<T>::remove(sub);
659			}
660
661			let err_amount = T::Currency::unreserve(&sender, deposit);
662			debug_assert!(err_amount.is_zero());
663
664			Self::deposit_event(Event::IdentityCleared { who: sender, deposit });
665
666			#[allow(deprecated)]
667			Ok(Some(T::WeightInfo::clear_identity(
668				id.judgements.len() as u32,
669				sub_ids.len() as u32,
670			))
671			.into())
672		}
673
674		/// Request a judgement from a registrar.
675		///
676		/// Payment: At most `max_fee` will be reserved for payment to the registrar if judgement
677		/// given.
678		///
679		/// The dispatch origin for this call must be _Signed_ and the sender must have a
680		/// registered identity.
681		///
682		/// - `reg_index`: The index of the registrar whose judgement is requested.
683		/// - `max_fee`: The maximum fee that may be paid. This should just be auto-populated as:
684		///
685		/// ```nocompile
686		/// Registrars::<T>::get().get(reg_index).unwrap().fee
687		/// ```
688		///
689		/// Emits `JudgementRequested` if successful.
690		#[pallet::call_index(4)]
691		#[pallet::weight(T::WeightInfo::request_judgement(T::MaxRegistrars::get(),))]
692		pub fn request_judgement(
693			origin: OriginFor<T>,
694			#[pallet::compact] reg_index: RegistrarIndex,
695			#[pallet::compact] max_fee: BalanceOf<T>,
696		) -> DispatchResultWithPostInfo {
697			let sender = ensure_signed(origin)?;
698			let registrars = Registrars::<T>::get();
699			let registrar = registrars
700				.get(reg_index as usize)
701				.and_then(Option::as_ref)
702				.ok_or(Error::<T>::EmptyIndex)?;
703			ensure!(max_fee >= registrar.fee, Error::<T>::FeeChanged);
704			let mut id = IdentityOf::<T>::get(&sender).ok_or(Error::<T>::NoIdentity)?;
705
706			let item = (reg_index, Judgement::FeePaid(registrar.fee));
707			match id.judgements.binary_search_by_key(&reg_index, |x| x.0) {
708				Ok(i) => {
709					if id.judgements[i].1.is_sticky() {
710						return Err(Error::<T>::StickyJudgement.into());
711					} else {
712						id.judgements[i] = item
713					}
714				},
715				Err(i) => {
716					id.judgements.try_insert(i, item).map_err(|_| Error::<T>::TooManyRegistrars)?
717				},
718			}
719
720			T::Currency::reserve(&sender, registrar.fee)?;
721
722			let judgements = id.judgements.len();
723			IdentityOf::<T>::insert(&sender, id);
724
725			Self::deposit_event(Event::JudgementRequested {
726				who: sender,
727				registrar_index: reg_index,
728			});
729
730			Ok(Some(T::WeightInfo::request_judgement(judgements as u32)).into())
731		}
732
733		/// Cancel a previous request.
734		///
735		/// Payment: A previously reserved deposit is returned on success.
736		///
737		/// The dispatch origin for this call must be _Signed_ and the sender must have a
738		/// registered identity.
739		///
740		/// - `reg_index`: The index of the registrar whose judgement is no longer requested.
741		///
742		/// Emits `JudgementUnrequested` if successful.
743		#[pallet::call_index(5)]
744		#[pallet::weight(T::WeightInfo::cancel_request(T::MaxRegistrars::get()))]
745		pub fn cancel_request(
746			origin: OriginFor<T>,
747			reg_index: RegistrarIndex,
748		) -> DispatchResultWithPostInfo {
749			let sender = ensure_signed(origin)?;
750			let mut id = IdentityOf::<T>::get(&sender).ok_or(Error::<T>::NoIdentity)?;
751
752			let pos = id
753				.judgements
754				.binary_search_by_key(&reg_index, |x| x.0)
755				.map_err(|_| Error::<T>::NotFound)?;
756			let fee = if let Judgement::FeePaid(fee) = id.judgements.remove(pos).1 {
757				fee
758			} else {
759				return Err(Error::<T>::JudgementGiven.into());
760			};
761
762			let err_amount = T::Currency::unreserve(&sender, fee);
763			debug_assert!(err_amount.is_zero());
764			let judgements = id.judgements.len();
765			IdentityOf::<T>::insert(&sender, id);
766
767			Self::deposit_event(Event::JudgementUnrequested {
768				who: sender,
769				registrar_index: reg_index,
770			});
771
772			Ok(Some(T::WeightInfo::cancel_request(judgements as u32)).into())
773		}
774
775		/// Set the fee required for a judgement to be requested from a registrar.
776		///
777		/// The dispatch origin for this call must be _Signed_ and the sender must be the account
778		/// of the registrar whose index is `index`.
779		///
780		/// - `index`: the index of the registrar whose fee is to be set.
781		/// - `fee`: the new fee.
782		#[pallet::call_index(6)]
783		#[pallet::weight(T::WeightInfo::set_fee(T::MaxRegistrars::get()))]
784		pub fn set_fee(
785			origin: OriginFor<T>,
786			#[pallet::compact] index: RegistrarIndex,
787			#[pallet::compact] fee: BalanceOf<T>,
788		) -> DispatchResultWithPostInfo {
789			let who = ensure_signed(origin)?;
790
791			let registrars = Registrars::<T>::mutate(|rs| -> Result<usize, DispatchError> {
792				rs.get_mut(index as usize)
793					.and_then(|x| x.as_mut())
794					.and_then(|r| {
795						if r.account == who {
796							r.fee = fee;
797							Some(())
798						} else {
799							None
800						}
801					})
802					.ok_or_else(|| DispatchError::from(Error::<T>::InvalidIndex))?;
803				Ok(rs.len())
804			})?;
805			Ok(Some(T::WeightInfo::set_fee(registrars as u32)).into())
806		}
807
808		/// Change the account associated with a registrar.
809		///
810		/// The dispatch origin for this call must be _Signed_ and the sender must be the account
811		/// of the registrar whose index is `index`.
812		///
813		/// - `index`: the index of the registrar whose fee is to be set.
814		/// - `new`: the new account ID.
815		#[pallet::call_index(7)]
816		#[pallet::weight(T::WeightInfo::set_account_id(T::MaxRegistrars::get()))]
817		pub fn set_account_id(
818			origin: OriginFor<T>,
819			#[pallet::compact] index: RegistrarIndex,
820			new: AccountIdLookupOf<T>,
821		) -> DispatchResultWithPostInfo {
822			let who = ensure_signed(origin)?;
823			let new = T::Lookup::lookup(new)?;
824
825			let registrars = Registrars::<T>::mutate(|rs| -> Result<usize, DispatchError> {
826				rs.get_mut(index as usize)
827					.and_then(|x| x.as_mut())
828					.and_then(|r| {
829						if r.account == who {
830							r.account = new;
831							Some(())
832						} else {
833							None
834						}
835					})
836					.ok_or_else(|| DispatchError::from(Error::<T>::InvalidIndex))?;
837				Ok(rs.len())
838			})?;
839			Ok(Some(T::WeightInfo::set_account_id(registrars as u32)).into())
840		}
841
842		/// Set the field information for a registrar.
843		///
844		/// The dispatch origin for this call must be _Signed_ and the sender must be the account
845		/// of the registrar whose index is `index`.
846		///
847		/// - `index`: the index of the registrar whose fee is to be set.
848		/// - `fields`: the fields that the registrar concerns themselves with.
849		#[pallet::call_index(8)]
850		#[pallet::weight(T::WeightInfo::set_fields(T::MaxRegistrars::get()))]
851		pub fn set_fields(
852			origin: OriginFor<T>,
853			#[pallet::compact] index: RegistrarIndex,
854			fields: <T::IdentityInformation as IdentityInformationProvider>::FieldsIdentifier,
855		) -> DispatchResultWithPostInfo {
856			let who = ensure_signed(origin)?;
857
858			let registrars =
859				Registrars::<T>::mutate(|registrars| -> Result<usize, DispatchError> {
860					let registrar = registrars
861						.get_mut(index as usize)
862						.and_then(|r| r.as_mut())
863						.filter(|r| r.account == who)
864						.ok_or_else(|| DispatchError::from(Error::<T>::InvalidIndex))?;
865					registrar.fields = fields;
866
867					Ok(registrars.len())
868				})?;
869			Ok(Some(T::WeightInfo::set_fields(registrars as u32)).into())
870		}
871
872		/// Provide a judgement for an account's identity.
873		///
874		/// The dispatch origin for this call must be _Signed_ and the sender must be the account
875		/// of the registrar whose index is `reg_index`.
876		///
877		/// - `reg_index`: the index of the registrar whose judgement is being made.
878		/// - `target`: the account whose identity the judgement is upon. This must be an account
879		///   with a registered identity.
880		/// - `judgement`: the judgement of the registrar of index `reg_index` about `target`.
881		/// - `identity`: The hash of the [`IdentityInformationProvider`] for that the judgement is
882		///   provided.
883		///
884		/// Note: Judgements do not apply to a username.
885		///
886		/// Emits `JudgementGiven` if successful.
887		#[pallet::call_index(9)]
888		#[pallet::weight(T::WeightInfo::provide_judgement(T::MaxRegistrars::get()))]
889		pub fn provide_judgement(
890			origin: OriginFor<T>,
891			#[pallet::compact] reg_index: RegistrarIndex,
892			target: AccountIdLookupOf<T>,
893			judgement: Judgement<BalanceOf<T>>,
894			identity: T::Hash,
895		) -> DispatchResultWithPostInfo {
896			let sender = ensure_signed(origin)?;
897			let target = T::Lookup::lookup(target)?;
898			ensure!(!judgement.has_deposit(), Error::<T>::InvalidJudgement);
899			Registrars::<T>::get()
900				.get(reg_index as usize)
901				.and_then(Option::as_ref)
902				.filter(|r| r.account == sender)
903				.ok_or(Error::<T>::InvalidIndex)?;
904			let mut id = IdentityOf::<T>::get(&target).ok_or(Error::<T>::InvalidTarget)?;
905
906			if T::Hashing::hash_of(&id.info) != identity {
907				return Err(Error::<T>::JudgementForDifferentIdentity.into());
908			}
909
910			let item = (reg_index, judgement);
911			match id.judgements.binary_search_by_key(&reg_index, |x| x.0) {
912				Ok(position) => {
913					if let Judgement::FeePaid(fee) = id.judgements[position].1 {
914						T::Currency::repatriate_reserved(
915							&target,
916							&sender,
917							fee,
918							BalanceStatus::Free,
919						)
920						.map_err(|_| Error::<T>::JudgementPaymentFailed)?;
921					}
922					id.judgements[position] = item
923				},
924				Err(position) => id
925					.judgements
926					.try_insert(position, item)
927					.map_err(|_| Error::<T>::TooManyRegistrars)?,
928			}
929
930			let judgements = id.judgements.len();
931			IdentityOf::<T>::insert(&target, id);
932			Self::deposit_event(Event::JudgementGiven { target, registrar_index: reg_index });
933
934			Ok(Some(T::WeightInfo::provide_judgement(judgements as u32)).into())
935		}
936
937		/// Remove an account's identity and sub-account information and slash the deposits.
938		///
939		/// Payment: Reserved balances from `set_subs` and `set_identity` are slashed and handled by
940		/// `Slash`. Verification request deposits are not returned; they should be cancelled
941		/// manually using `cancel_request`.
942		///
943		/// The dispatch origin for this call must match `T::ForceOrigin`.
944		///
945		/// - `target`: the account whose identity the judgement is upon. This must be an account
946		///   with a registered identity.
947		///
948		/// Emits `IdentityKilled` if successful.
949		#[pallet::call_index(10)]
950		#[pallet::weight(T::WeightInfo::kill_identity(
951			T::MaxRegistrars::get(),
952			T::MaxSubAccounts::get(),
953		))]
954		pub fn kill_identity(
955			origin: OriginFor<T>,
956			target: AccountIdLookupOf<T>,
957		) -> DispatchResultWithPostInfo {
958			T::ForceOrigin::ensure_origin(origin)?;
959
960			// Figure out who we're meant to be clearing.
961			let target = T::Lookup::lookup(target)?;
962			// Grab their deposit (and check that they have one).
963			let (subs_deposit, sub_ids) = SubsOf::<T>::take(&target);
964			let id = IdentityOf::<T>::take(&target).ok_or(Error::<T>::NoIdentity)?;
965			let deposit = id.total_deposit().saturating_add(subs_deposit);
966			for sub in sub_ids.iter() {
967				SuperOf::<T>::remove(sub);
968			}
969			// Slash their deposit from them.
970			T::Slashed::on_unbalanced(T::Currency::slash_reserved(&target, deposit).0);
971
972			Self::deposit_event(Event::IdentityKilled { who: target, deposit });
973
974			#[allow(deprecated)]
975			Ok(Some(T::WeightInfo::kill_identity(id.judgements.len() as u32, sub_ids.len() as u32))
976				.into())
977		}
978
979		/// Add the given account to the sender's subs.
980		///
981		/// Payment: Balance reserved by a previous `set_subs` call for one sub will be repatriated
982		/// to the sender.
983		///
984		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered
985		/// sub identity of `sub`.
986		#[pallet::call_index(11)]
987		#[pallet::weight(T::WeightInfo::add_sub(T::MaxSubAccounts::get()))]
988		pub fn add_sub(
989			origin: OriginFor<T>,
990			sub: AccountIdLookupOf<T>,
991			data: Data,
992		) -> DispatchResult {
993			let sender = ensure_signed(origin)?;
994			let sub = T::Lookup::lookup(sub)?;
995			ensure!(IdentityOf::<T>::contains_key(&sender), Error::<T>::NoIdentity);
996
997			// Check if it's already claimed as sub-identity.
998			ensure!(!SuperOf::<T>::contains_key(&sub), Error::<T>::AlreadyClaimed);
999
1000			SubsOf::<T>::try_mutate(&sender, |(ref mut subs_deposit, ref mut sub_ids)| {
1001				// Ensure there is space and that the deposit is paid.
1002				ensure!(
1003					sub_ids.len() < T::MaxSubAccounts::get() as usize,
1004					Error::<T>::TooManySubAccounts
1005				);
1006				let deposit = T::SubAccountDeposit::get();
1007				T::Currency::reserve(&sender, deposit)?;
1008
1009				SuperOf::<T>::insert(&sub, (sender.clone(), data));
1010				sub_ids.try_push(sub.clone()).expect("sub ids length checked above; qed");
1011				*subs_deposit = subs_deposit.saturating_add(deposit);
1012
1013				Self::deposit_event(Event::SubIdentityAdded { sub, main: sender.clone(), deposit });
1014				Ok(())
1015			})
1016		}
1017
1018		/// Alter the associated name of the given sub-account.
1019		///
1020		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered
1021		/// sub identity of `sub`.
1022		#[pallet::call_index(12)]
1023		#[pallet::weight(T::WeightInfo::rename_sub(T::MaxSubAccounts::get()))]
1024		pub fn rename_sub(
1025			origin: OriginFor<T>,
1026			sub: AccountIdLookupOf<T>,
1027			data: Data,
1028		) -> DispatchResult {
1029			let sender = ensure_signed(origin)?;
1030			let sub = T::Lookup::lookup(sub)?;
1031			ensure!(IdentityOf::<T>::contains_key(&sender), Error::<T>::NoIdentity);
1032			ensure!(SuperOf::<T>::get(&sub).map_or(false, |x| x.0 == sender), Error::<T>::NotOwned);
1033			SuperOf::<T>::insert(&sub, (&sender, data));
1034
1035			Self::deposit_event(Event::SubIdentityRenamed { main: sender, sub });
1036			Ok(())
1037		}
1038
1039		/// Remove the given account from the sender's subs.
1040		///
1041		/// Payment: Balance reserved by a previous `set_subs` call for one sub will be repatriated
1042		/// to the sender.
1043		///
1044		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered
1045		/// sub identity of `sub`.
1046		#[pallet::call_index(13)]
1047		#[pallet::weight(T::WeightInfo::remove_sub(T::MaxSubAccounts::get()))]
1048		pub fn remove_sub(origin: OriginFor<T>, sub: AccountIdLookupOf<T>) -> DispatchResult {
1049			let sender = ensure_signed(origin)?;
1050			ensure!(IdentityOf::<T>::contains_key(&sender), Error::<T>::NoIdentity);
1051			let sub = T::Lookup::lookup(sub)?;
1052			let (sup, _) = SuperOf::<T>::get(&sub).ok_or(Error::<T>::NotSub)?;
1053			ensure!(sup == sender, Error::<T>::NotOwned);
1054			SuperOf::<T>::remove(&sub);
1055			SubsOf::<T>::mutate(&sup, |(ref mut subs_deposit, ref mut sub_ids)| {
1056				sub_ids.retain(|x| x != &sub);
1057				let deposit = T::SubAccountDeposit::get().min(*subs_deposit);
1058				*subs_deposit -= deposit;
1059				let err_amount = T::Currency::unreserve(&sender, deposit);
1060				debug_assert!(err_amount.is_zero());
1061				Self::deposit_event(Event::SubIdentityRemoved { sub, main: sender, deposit });
1062			});
1063			Ok(())
1064		}
1065
1066		/// Remove the sender as a sub-account.
1067		///
1068		/// Payment: Balance reserved by a previous `set_subs` call for one sub will be repatriated
1069		/// to the sender (*not* the original depositor).
1070		///
1071		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered
1072		/// super-identity.
1073		///
1074		/// NOTE: This should not normally be used, but is provided in the case that the non-
1075		/// controller of an account is maliciously registered as a sub-account.
1076		#[pallet::call_index(14)]
1077		#[pallet::weight(T::WeightInfo::quit_sub(T::MaxSubAccounts::get()))]
1078		pub fn quit_sub(origin: OriginFor<T>) -> DispatchResult {
1079			let sender = ensure_signed(origin)?;
1080			let (sup, _) = SuperOf::<T>::take(&sender).ok_or(Error::<T>::NotSub)?;
1081			SubsOf::<T>::mutate(&sup, |(ref mut subs_deposit, ref mut sub_ids)| {
1082				sub_ids.retain(|x| x != &sender);
1083				let deposit = T::SubAccountDeposit::get().min(*subs_deposit);
1084				*subs_deposit -= deposit;
1085				let _ =
1086					T::Currency::repatriate_reserved(&sup, &sender, deposit, BalanceStatus::Free);
1087				Self::deposit_event(Event::SubIdentityRevoked {
1088					sub: sender,
1089					main: sup.clone(),
1090					deposit,
1091				});
1092			});
1093			Ok(())
1094		}
1095
1096		/// Add an `AccountId` with permission to grant usernames with a given `suffix` appended.
1097		///
1098		/// The authority can grant up to `allocation` usernames. To top up the allocation or
1099		/// change the account used to grant usernames, this call can be used with the updated
1100		/// parameters to overwrite the existing configuration.
1101		#[pallet::call_index(15)]
1102		#[pallet::weight(T::WeightInfo::add_username_authority())]
1103		pub fn add_username_authority(
1104			origin: OriginFor<T>,
1105			authority: AccountIdLookupOf<T>,
1106			suffix: Vec<u8>,
1107			allocation: u32,
1108		) -> DispatchResult {
1109			T::UsernameAuthorityOrigin::ensure_origin(origin)?;
1110			let authority = T::Lookup::lookup(authority)?;
1111			// We don't need to check the length because it gets checked when casting into a
1112			// `BoundedVec`.
1113			Self::validate_suffix(&suffix)?;
1114			let suffix = Suffix::<T>::try_from(suffix).map_err(|_| Error::<T>::InvalidSuffix)?;
1115			// The call is `UsernameAuthorityOrigin` guarded, overwrite the old entry if it exists.
1116			AuthorityOf::<T>::insert(
1117				&suffix,
1118				AuthorityProperties::<T::AccountId> { account_id: authority.clone(), allocation },
1119			);
1120			Self::deposit_event(Event::AuthorityAdded { authority });
1121			Ok(())
1122		}
1123
1124		/// Remove `authority` from the username authorities.
1125		#[pallet::call_index(16)]
1126		#[pallet::weight(T::WeightInfo::remove_username_authority())]
1127		pub fn remove_username_authority(
1128			origin: OriginFor<T>,
1129			suffix: Vec<u8>,
1130			authority: AccountIdLookupOf<T>,
1131		) -> DispatchResult {
1132			T::UsernameAuthorityOrigin::ensure_origin(origin)?;
1133			let suffix = Suffix::<T>::try_from(suffix).map_err(|_| Error::<T>::InvalidSuffix)?;
1134			let authority = T::Lookup::lookup(authority)?;
1135			let properties =
1136				AuthorityOf::<T>::take(&suffix).ok_or(Error::<T>::NotUsernameAuthority)?;
1137			ensure!(properties.account_id == authority, Error::<T>::InvalidSuffix);
1138			Self::deposit_event(Event::AuthorityRemoved { authority });
1139			Ok(())
1140		}
1141
1142		/// Set the username for `who`. Must be called by a username authority.
1143		///
1144		/// If `use_allocation` is set, the authority must have a username allocation available to
1145		/// spend. Otherwise, the authority will need to put up a deposit for registering the
1146		/// username.
1147		///
1148		/// Users can either pre-sign their usernames or
1149		/// accept them later.
1150		///
1151		/// Usernames must:
1152		///   - Only contain lowercase ASCII characters or digits.
1153		///   - When combined with the suffix of the issuing authority be _less than_ the
1154		///     `MaxUsernameLength`.
1155		#[pallet::call_index(17)]
1156		#[pallet::weight(T::WeightInfo::set_username_for(if *use_allocation { 1 } else { 0 }))]
1157		pub fn set_username_for(
1158			origin: OriginFor<T>,
1159			who: AccountIdLookupOf<T>,
1160			username: Vec<u8>,
1161			signature: Option<T::OffchainSignature>,
1162			use_allocation: bool,
1163		) -> DispatchResult {
1164			// Ensure origin is a Username Authority and has an allocation. Decrement their
1165			// allocation by one.
1166			let sender = ensure_signed(origin)?;
1167			let suffix = Self::validate_username(&username)?;
1168			let provider = AuthorityOf::<T>::try_mutate(
1169				&suffix,
1170				|maybe_authority| -> Result<ProviderOf<T>, DispatchError> {
1171					let properties =
1172						maybe_authority.as_mut().ok_or(Error::<T>::NotUsernameAuthority)?;
1173					ensure!(properties.account_id == sender, Error::<T>::NotUsernameAuthority);
1174					if use_allocation {
1175						ensure!(properties.allocation > 0, Error::<T>::NoAllocation);
1176						properties.allocation.saturating_dec();
1177						Ok(Provider::new_with_allocation())
1178					} else {
1179						let deposit = T::UsernameDeposit::get();
1180						T::Currency::reserve(&sender, deposit)?;
1181						Ok(Provider::new_with_deposit(deposit))
1182					}
1183				},
1184			)?;
1185
1186			let bounded_username =
1187				Username::<T>::try_from(username).map_err(|_| Error::<T>::InvalidUsername)?;
1188
1189			// Usernames must be unique. Ensure it's not taken.
1190			ensure!(
1191				!UsernameInfoOf::<T>::contains_key(&bounded_username),
1192				Error::<T>::UsernameTaken
1193			);
1194			ensure!(
1195				!PendingUsernames::<T>::contains_key(&bounded_username),
1196				Error::<T>::UsernameTaken
1197			);
1198
1199			// Insert or queue.
1200			let who = T::Lookup::lookup(who)?;
1201			if let Some(s) = signature {
1202				// Account has pre-signed an authorization. Verify the signature provided and grant
1203				// the username directly.
1204				Self::validate_signature(&bounded_username[..], &s, &who)?;
1205				Self::insert_username(&who, bounded_username, provider);
1206			} else {
1207				// The user must accept the username, therefore, queue it.
1208				Self::queue_acceptance(&who, bounded_username, provider);
1209			}
1210			Ok(())
1211		}
1212
1213		/// Accept a given username that an `authority` granted. The call must include the full
1214		/// username, as in `username.suffix`.
1215		#[pallet::call_index(18)]
1216		#[pallet::weight(T::WeightInfo::accept_username())]
1217		pub fn accept_username(
1218			origin: OriginFor<T>,
1219			username: Username<T>,
1220		) -> DispatchResultWithPostInfo {
1221			let who = ensure_signed(origin)?;
1222			let (approved_for, _, provider) =
1223				PendingUsernames::<T>::take(&username).ok_or(Error::<T>::NoUsername)?;
1224			ensure!(approved_for == who.clone(), Error::<T>::InvalidUsername);
1225			Self::insert_username(&who, username.clone(), provider);
1226			Self::deposit_event(Event::UsernameSet { who: who.clone(), username });
1227			Ok(Pays::No.into())
1228		}
1229
1230		/// Remove an expired username approval. The username was approved by an authority but never
1231		/// accepted by the user and must now be beyond its expiration. The call must include the
1232		/// full username, as in `username.suffix`.
1233		#[pallet::call_index(19)]
1234		#[pallet::weight(T::WeightInfo::remove_expired_approval(0))]
1235		pub fn remove_expired_approval(
1236			origin: OriginFor<T>,
1237			username: Username<T>,
1238		) -> DispatchResultWithPostInfo {
1239			ensure_signed(origin)?;
1240			if let Some((who, expiration, provider)) = PendingUsernames::<T>::take(&username) {
1241				let now = frame_system::Pallet::<T>::block_number();
1242				ensure!(now > expiration, Error::<T>::NotExpired);
1243				let actual_weight = match provider {
1244					Provider::AuthorityDeposit(deposit) => {
1245						let suffix = Self::suffix_of_username(&username)
1246							.ok_or(Error::<T>::InvalidUsername)?;
1247						let authority_account = AuthorityOf::<T>::get(&suffix)
1248							.map(|auth_info| auth_info.account_id)
1249							.ok_or(Error::<T>::NotUsernameAuthority)?;
1250						let err_amount = T::Currency::unreserve(&authority_account, deposit);
1251						debug_assert!(err_amount.is_zero());
1252						T::WeightInfo::remove_expired_approval(0)
1253					},
1254					Provider::Allocation => {
1255						// We don't refund the allocation, it is lost, but we refund some weight.
1256						T::WeightInfo::remove_expired_approval(1)
1257					},
1258					Provider::System => {
1259						// Usernames added by the system shouldn't ever be expired.
1260						return Err(Error::<T>::InvalidTarget.into());
1261					},
1262				};
1263				Self::deposit_event(Event::PreapprovalExpired { whose: who.clone() });
1264				Ok((Some(actual_weight), Pays::No).into())
1265			} else {
1266				Err(Error::<T>::NoUsername.into())
1267			}
1268		}
1269
1270		/// Set a given username as the primary. The username should include the suffix.
1271		#[pallet::call_index(20)]
1272		#[pallet::weight(T::WeightInfo::set_primary_username())]
1273		pub fn set_primary_username(origin: OriginFor<T>, username: Username<T>) -> DispatchResult {
1274			// ensure `username` maps to `origin` (i.e. has already been set by an authority).
1275			let who = ensure_signed(origin)?;
1276			let account_of_username =
1277				UsernameInfoOf::<T>::get(&username).ok_or(Error::<T>::NoUsername)?.owner;
1278			ensure!(who == account_of_username, Error::<T>::InvalidUsername);
1279			UsernameOf::<T>::insert(&who, username.clone());
1280			Self::deposit_event(Event::PrimaryUsernameSet { who: who.clone(), username });
1281			Ok(())
1282		}
1283
1284		/// Start the process of removing a username by placing it in the unbinding usernames map.
1285		/// Once the grace period has passed, the username can be deleted by calling
1286		/// [remove_username](crate::Call::remove_username).
1287		#[pallet::call_index(21)]
1288		#[pallet::weight(T::WeightInfo::unbind_username())]
1289		pub fn unbind_username(origin: OriginFor<T>, username: Username<T>) -> DispatchResult {
1290			let who = ensure_signed(origin)?;
1291			let username_info =
1292				UsernameInfoOf::<T>::get(&username).ok_or(Error::<T>::NoUsername)?;
1293			let suffix = Self::suffix_of_username(&username).ok_or(Error::<T>::InvalidUsername)?;
1294			let authority_account = AuthorityOf::<T>::get(&suffix)
1295				.map(|auth_info| auth_info.account_id)
1296				.ok_or(Error::<T>::NotUsernameAuthority)?;
1297			ensure!(who == authority_account, Error::<T>::NotUsernameAuthority);
1298			match username_info.provider {
1299				Provider::AuthorityDeposit(_) | Provider::Allocation => {
1300					let now = frame_system::Pallet::<T>::block_number();
1301					let grace_period_expiry = now.saturating_add(T::UsernameGracePeriod::get());
1302					UnbindingUsernames::<T>::try_mutate(&username, |maybe_init| {
1303						if maybe_init.is_some() {
1304							return Err(Error::<T>::AlreadyUnbinding);
1305						}
1306						*maybe_init = Some(grace_period_expiry);
1307						Ok(())
1308					})?;
1309				},
1310				Provider::System => return Err(Error::<T>::InsufficientPrivileges.into()),
1311			}
1312			Self::deposit_event(Event::UsernameUnbound { username });
1313			Ok(())
1314		}
1315
1316		/// Permanently delete a username which has been unbinding for longer than the grace period.
1317		/// Caller is refunded the fee if the username expired and the removal was successful.
1318		#[pallet::call_index(22)]
1319		#[pallet::weight(T::WeightInfo::remove_username())]
1320		pub fn remove_username(
1321			origin: OriginFor<T>,
1322			username: Username<T>,
1323		) -> DispatchResultWithPostInfo {
1324			ensure_signed(origin)?;
1325			let grace_period_expiry =
1326				UnbindingUsernames::<T>::take(&username).ok_or(Error::<T>::NotUnbinding)?;
1327			let now = frame_system::Pallet::<T>::block_number();
1328			ensure!(now >= grace_period_expiry, Error::<T>::TooEarly);
1329			let username_info = UsernameInfoOf::<T>::take(&username)
1330				.defensive_proof("an unbinding username must exist")
1331				.ok_or(Error::<T>::NoUsername)?;
1332			// If this is the primary username, remove the entry from the account -> username map.
1333			UsernameOf::<T>::mutate(&username_info.owner, |maybe_primary| {
1334				if maybe_primary.as_ref().map_or(false, |primary| *primary == username) {
1335					*maybe_primary = None;
1336				}
1337			});
1338			match username_info.provider {
1339				Provider::AuthorityDeposit(username_deposit) => {
1340					let suffix = Self::suffix_of_username(&username)
1341						.defensive_proof("registered username must be valid")
1342						.ok_or(Error::<T>::InvalidUsername)?;
1343					if let Some(authority_account) =
1344						AuthorityOf::<T>::get(&suffix).map(|auth_info| auth_info.account_id)
1345					{
1346						let err_amount =
1347							T::Currency::unreserve(&authority_account, username_deposit);
1348						debug_assert!(err_amount.is_zero());
1349					}
1350				},
1351				Provider::Allocation => {
1352					// We don't refund the allocation, it is lost.
1353				},
1354				Provider::System => return Err(Error::<T>::InsufficientPrivileges.into()),
1355			}
1356			Self::deposit_event(Event::UsernameRemoved { username });
1357			Ok(Pays::No.into())
1358		}
1359
1360		/// Call with [ForceOrigin](crate::Config::ForceOrigin) privileges which deletes a username
1361		/// and slashes any deposit associated with it.
1362		#[pallet::call_index(23)]
1363		#[pallet::weight(T::WeightInfo::kill_username(0))]
1364		pub fn kill_username(
1365			origin: OriginFor<T>,
1366			username: Username<T>,
1367		) -> DispatchResultWithPostInfo {
1368			T::ForceOrigin::ensure_origin(origin)?;
1369			let username_info =
1370				UsernameInfoOf::<T>::take(&username).ok_or(Error::<T>::NoUsername)?;
1371			// If this is the primary username, remove the entry from the account -> username map.
1372			UsernameOf::<T>::mutate(&username_info.owner, |maybe_primary| {
1373				if match maybe_primary {
1374					Some(primary) if *primary == username => true,
1375					_ => false,
1376				} {
1377					*maybe_primary = None;
1378				}
1379			});
1380			let _ = UnbindingUsernames::<T>::take(&username);
1381			let actual_weight = match username_info.provider {
1382				Provider::AuthorityDeposit(username_deposit) => {
1383					let suffix =
1384						Self::suffix_of_username(&username).ok_or(Error::<T>::InvalidUsername)?;
1385					if let Some(authority_account) =
1386						AuthorityOf::<T>::get(&suffix).map(|auth_info| auth_info.account_id)
1387					{
1388						T::Slashed::on_unbalanced(
1389							T::Currency::slash_reserved(&authority_account, username_deposit).0,
1390						);
1391					}
1392					T::WeightInfo::kill_username(0)
1393				},
1394				Provider::Allocation => {
1395					// We don't refund the allocation, it is lost, but we do refund some weight.
1396					T::WeightInfo::kill_username(1)
1397				},
1398				Provider::System => {
1399					// Force origin can remove system usernames.
1400					T::WeightInfo::kill_username(1)
1401				},
1402			};
1403			Self::deposit_event(Event::UsernameKilled { username });
1404			Ok((Some(actual_weight), Pays::No).into())
1405		}
1406	}
1407}
1408
1409impl<T: Config> Pallet<T> {
1410	/// Get the subs of an account.
1411	pub fn subs(who: &T::AccountId) -> Vec<(T::AccountId, Data)> {
1412		SubsOf::<T>::get(who)
1413			.1
1414			.into_iter()
1415			.filter_map(|a| SuperOf::<T>::get(&a).map(|x| (a, x.1)))
1416			.collect()
1417	}
1418
1419	/// Calculate the deposit required for a number of `sub` accounts.
1420	fn subs_deposit(subs: u32) -> BalanceOf<T> {
1421		T::SubAccountDeposit::get().saturating_mul(BalanceOf::<T>::from(subs))
1422	}
1423
1424	/// Take the `current` deposit that `who` is holding, and update it to a `new` one.
1425	fn rejig_deposit(
1426		who: &T::AccountId,
1427		current: BalanceOf<T>,
1428		new: BalanceOf<T>,
1429	) -> DispatchResult {
1430		if new > current {
1431			T::Currency::reserve(who, new - current)?;
1432		} else if new < current {
1433			let err_amount = T::Currency::unreserve(who, current - new);
1434			debug_assert!(err_amount.is_zero());
1435		}
1436		Ok(())
1437	}
1438
1439	/// Check if the account has corresponding identity information by the identity field.
1440	pub fn has_identity(
1441		who: &T::AccountId,
1442		fields: <T::IdentityInformation as IdentityInformationProvider>::FieldsIdentifier,
1443	) -> bool {
1444		IdentityOf::<T>::get(who)
1445			.map_or(false, |registration| registration.info.has_identity(fields))
1446	}
1447
1448	/// Calculate the deposit required for an identity.
1449	fn calculate_identity_deposit(info: &T::IdentityInformation) -> BalanceOf<T> {
1450		let bytes = info.encoded_size() as u32;
1451		let byte_deposit = T::ByteDeposit::get().saturating_mul(BalanceOf::<T>::from(bytes));
1452		T::BasicDeposit::get().saturating_add(byte_deposit)
1453	}
1454
1455	/// Validate that a username conforms to allowed characters/format.
1456	///
1457	/// The function will validate the characters in `username`. It is expected to pass a fully
1458	/// formatted username here (i.e. "username.suffix"). The suffix is also separately validated
1459	/// and returned by this function.
1460	fn validate_username(username: &Vec<u8>) -> Result<Suffix<T>, DispatchError> {
1461		// Verify input length before allocating a Vec with the user's input.
1462		ensure!(
1463			username.len() <= T::MaxUsernameLength::get() as usize,
1464			Error::<T>::InvalidUsername
1465		);
1466
1467		// Usernames cannot be empty.
1468		ensure!(!username.is_empty(), Error::<T>::InvalidUsername);
1469		let separator_idx =
1470			username.iter().rposition(|c| *c == b'.').ok_or(Error::<T>::InvalidUsername)?;
1471		ensure!(separator_idx > 0, Error::<T>::InvalidUsername);
1472		let suffix_start = separator_idx.checked_add(1).ok_or(Error::<T>::InvalidUsername)?;
1473		ensure!(suffix_start < username.len(), Error::<T>::InvalidUsername);
1474		// Username must be lowercase and alphanumeric.
1475		ensure!(
1476			username
1477				.iter()
1478				.take(separator_idx)
1479				.all(|byte| byte.is_ascii_digit() || byte.is_ascii_lowercase()),
1480			Error::<T>::InvalidUsername
1481		);
1482		let suffix: Suffix<T> = (&username[suffix_start..])
1483			.to_vec()
1484			.try_into()
1485			.map_err(|_| Error::<T>::InvalidUsername)?;
1486		Ok(suffix)
1487	}
1488
1489	/// Return the suffix of a username, if it is valid.
1490	fn suffix_of_username(username: &Username<T>) -> Option<Suffix<T>> {
1491		let separator_idx = username.iter().rposition(|c| *c == b'.')?;
1492		let suffix_start = separator_idx.checked_add(1)?;
1493		if suffix_start >= username.len() {
1494			return None;
1495		}
1496		(&username[suffix_start..]).to_vec().try_into().ok()
1497	}
1498
1499	/// Validate that a suffix conforms to allowed characters/format.
1500	fn validate_suffix(suffix: &Vec<u8>) -> Result<(), DispatchError> {
1501		ensure!(suffix.len() <= T::MaxSuffixLength::get() as usize, Error::<T>::InvalidSuffix);
1502		ensure!(!suffix.is_empty(), Error::<T>::InvalidSuffix);
1503		ensure!(
1504			suffix.iter().all(|byte| byte.is_ascii_digit() || byte.is_ascii_lowercase()),
1505			Error::<T>::InvalidSuffix
1506		);
1507		Ok(())
1508	}
1509
1510	/// Validate a signature. Supports signatures on raw `data` or `data` wrapped in HTML `<Bytes>`.
1511	pub fn validate_signature(
1512		data: &[u8],
1513		signature: &T::OffchainSignature,
1514		signer: &T::AccountId,
1515	) -> DispatchResult {
1516		// Happy path, user has signed the raw data.
1517		if signature.verify(data, &signer) {
1518			return Ok(());
1519		}
1520		// NOTE: for security reasons modern UIs implicitly wrap the data requested to sign into
1521		// `<Bytes> + data + </Bytes>`, so why we support both wrapped and raw versions.
1522		let prefix = b"<Bytes>";
1523		let suffix = b"</Bytes>";
1524		let mut wrapped: Vec<u8> = Vec::with_capacity(data.len() + prefix.len() + suffix.len());
1525		wrapped.extend(prefix);
1526		wrapped.extend(data);
1527		wrapped.extend(suffix);
1528
1529		ensure!(signature.verify(&wrapped[..], &signer), Error::<T>::InvalidSignature);
1530
1531		Ok(())
1532	}
1533
1534	/// A username has met all conditions. Insert the relevant storage items.
1535	pub fn insert_username(who: &T::AccountId, username: Username<T>, provider: ProviderOf<T>) {
1536		// Check if they already have a primary. If so, leave it. If not, set it.
1537		// Likewise, check if they have an identity. If not, give them a minimal one.
1538		let (primary_username, new_is_primary) = match UsernameOf::<T>::get(&who) {
1539			// User has an existing Identity and a primary username. Leave it.
1540			Some(primary) => (primary, false),
1541			// User has an Identity but no primary. Set the new one as primary.
1542			None => (username.clone(), true),
1543		};
1544
1545		if new_is_primary {
1546			UsernameOf::<T>::insert(&who, primary_username);
1547		}
1548		let username_info = UsernameInformation { owner: who.clone(), provider };
1549		// Enter in username map.
1550		UsernameInfoOf::<T>::insert(username.clone(), username_info);
1551		Self::deposit_event(Event::UsernameSet { who: who.clone(), username: username.clone() });
1552		if new_is_primary {
1553			Self::deposit_event(Event::PrimaryUsernameSet { who: who.clone(), username });
1554		}
1555	}
1556
1557	/// A username was granted by an authority, but must be accepted by `who`. Put the username
1558	/// into a queue for acceptance.
1559	pub fn queue_acceptance(who: &T::AccountId, username: Username<T>, provider: ProviderOf<T>) {
1560		let now = frame_system::Pallet::<T>::block_number();
1561		let expiration = now.saturating_add(T::PendingUsernameExpiration::get());
1562		PendingUsernames::<T>::insert(&username, (who.clone(), expiration, provider));
1563		Self::deposit_event(Event::UsernameQueued { who: who.clone(), username, expiration });
1564	}
1565
1566	/// Reap an identity, clearing associated storage items and refunding any deposits. This
1567	/// function is very similar to (a) `clear_identity`, but called on a `target` account instead
1568	/// of self; and (b) `kill_identity`, but without imposing a slash.
1569	///
1570	/// Parameters:
1571	/// - `target`: The account for which to reap identity state.
1572	///
1573	/// Return type is a tuple of the number of registrars, `IdentityInfo` bytes, and sub accounts,
1574	/// respectively.
1575	///
1576	/// NOTE: This function is here temporarily for migration of Identity info from the Polkadot
1577	/// Relay Chain into a system parachain. It will be removed after the migration.
1578	pub fn reap_identity(who: &T::AccountId) -> Result<(u32, u32, u32), DispatchError> {
1579		// `take` any storage items keyed by `target`
1580		// identity
1581		let id = IdentityOf::<T>::take(&who).ok_or(Error::<T>::NoIdentity)?;
1582		let registrars = id.judgements.len() as u32;
1583		let encoded_byte_size = id.info.encoded_size() as u32;
1584
1585		// subs
1586		let (subs_deposit, sub_ids) = SubsOf::<T>::take(&who);
1587		let actual_subs = sub_ids.len() as u32;
1588		for sub in sub_ids.iter() {
1589			SuperOf::<T>::remove(sub);
1590		}
1591
1592		// unreserve any deposits
1593		let deposit = id.total_deposit().saturating_add(subs_deposit);
1594		let err_amount = T::Currency::unreserve(&who, deposit);
1595		debug_assert!(err_amount.is_zero());
1596		Ok((registrars, encoded_byte_size, actual_subs))
1597	}
1598
1599	/// Update the deposits held by `target` for its identity info.
1600	///
1601	/// Parameters:
1602	/// - `target`: The account for which to update deposits.
1603	///
1604	/// Return type is a tuple of the new Identity and Subs deposits, respectively.
1605	///
1606	/// NOTE: This function is here temporarily for migration of Identity info from the Polkadot
1607	/// Relay Chain into a system parachain. It will be removed after the migration.
1608	pub fn poke_deposit(
1609		target: &T::AccountId,
1610	) -> Result<(BalanceOf<T>, BalanceOf<T>), DispatchError> {
1611		// Identity Deposit
1612		let new_id_deposit = IdentityOf::<T>::try_mutate(
1613			&target,
1614			|identity_of| -> Result<BalanceOf<T>, DispatchError> {
1615				let reg = identity_of.as_mut().ok_or(Error::<T>::NoIdentity)?;
1616				// Calculate what deposit should be
1617				let encoded_byte_size = reg.info.encoded_size() as u32;
1618				let byte_deposit =
1619					T::ByteDeposit::get().saturating_mul(BalanceOf::<T>::from(encoded_byte_size));
1620				let new_id_deposit = T::BasicDeposit::get().saturating_add(byte_deposit);
1621
1622				// Update account
1623				Self::rejig_deposit(&target, reg.deposit, new_id_deposit)?;
1624
1625				reg.deposit = new_id_deposit;
1626				Ok(new_id_deposit)
1627			},
1628		)?;
1629
1630		let new_subs_deposit = if SubsOf::<T>::contains_key(&target) {
1631			SubsOf::<T>::try_mutate(
1632				&target,
1633				|(current_subs_deposit, subs_of)| -> Result<BalanceOf<T>, DispatchError> {
1634					let new_subs_deposit = Self::subs_deposit(subs_of.len() as u32);
1635					Self::rejig_deposit(&target, *current_subs_deposit, new_subs_deposit)?;
1636					*current_subs_deposit = new_subs_deposit;
1637					Ok(new_subs_deposit)
1638				},
1639			)?
1640		} else {
1641			// If the item doesn't exist, there is no "old" deposit, and the new one is zero, so no
1642			// need to call rejig, it'd just be zero -> zero.
1643			Zero::zero()
1644		};
1645		Ok((new_id_deposit, new_subs_deposit))
1646	}
1647
1648	/// Set an identity with zero deposit. Used for benchmarking and XCM emulator tests that involve
1649	/// `rejig_deposit`.
1650	#[cfg(any(feature = "runtime-benchmarks", feature = "std"))]
1651	pub fn set_identity_no_deposit(
1652		who: &T::AccountId,
1653		info: T::IdentityInformation,
1654	) -> DispatchResult {
1655		IdentityOf::<T>::insert(
1656			&who,
1657			Registration {
1658				judgements: Default::default(),
1659				deposit: Zero::zero(),
1660				info: info.clone(),
1661			},
1662		);
1663		Ok(())
1664	}
1665
1666	/// Set subs with zero deposit and default name. Only used for benchmarks that involve
1667	/// `rejig_deposit`.
1668	#[cfg(any(feature = "runtime-benchmarks", feature = "std"))]
1669	pub fn set_subs_no_deposit(
1670		who: &T::AccountId,
1671		subs: Vec<(T::AccountId, Data)>,
1672	) -> DispatchResult {
1673		let mut sub_accounts = BoundedVec::<T::AccountId, T::MaxSubAccounts>::default();
1674		for (sub, name) in subs {
1675			SuperOf::<T>::insert(&sub, (who.clone(), name));
1676			sub_accounts
1677				.try_push(sub)
1678				.expect("benchmark should not pass more than T::MaxSubAccounts");
1679		}
1680		SubsOf::<T>::insert::<
1681			&T::AccountId,
1682			(BalanceOf<T>, BoundedVec<T::AccountId, T::MaxSubAccounts>),
1683		>(&who, (Zero::zero(), sub_accounts));
1684		Ok(())
1685	}
1686}