referrerpolicy=no-referrer-when-downgrade

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				Err(i) =>
715					id.judgements.try_insert(i, item).map_err(|_| Error::<T>::TooManyRegistrars)?,
716			}
717
718			T::Currency::reserve(&sender, registrar.fee)?;
719
720			let judgements = id.judgements.len();
721			IdentityOf::<T>::insert(&sender, id);
722
723			Self::deposit_event(Event::JudgementRequested {
724				who: sender,
725				registrar_index: reg_index,
726			});
727
728			Ok(Some(T::WeightInfo::request_judgement(judgements as u32)).into())
729		}
730
731		/// Cancel a previous request.
732		///
733		/// Payment: A previously reserved deposit is returned on success.
734		///
735		/// The dispatch origin for this call must be _Signed_ and the sender must have a
736		/// registered identity.
737		///
738		/// - `reg_index`: The index of the registrar whose judgement is no longer requested.
739		///
740		/// Emits `JudgementUnrequested` if successful.
741		#[pallet::call_index(5)]
742		#[pallet::weight(T::WeightInfo::cancel_request(T::MaxRegistrars::get()))]
743		pub fn cancel_request(
744			origin: OriginFor<T>,
745			reg_index: RegistrarIndex,
746		) -> DispatchResultWithPostInfo {
747			let sender = ensure_signed(origin)?;
748			let mut id = IdentityOf::<T>::get(&sender).ok_or(Error::<T>::NoIdentity)?;
749
750			let pos = id
751				.judgements
752				.binary_search_by_key(&reg_index, |x| x.0)
753				.map_err(|_| Error::<T>::NotFound)?;
754			let fee = if let Judgement::FeePaid(fee) = id.judgements.remove(pos).1 {
755				fee
756			} else {
757				return Err(Error::<T>::JudgementGiven.into())
758			};
759
760			let err_amount = T::Currency::unreserve(&sender, fee);
761			debug_assert!(err_amount.is_zero());
762			let judgements = id.judgements.len();
763			IdentityOf::<T>::insert(&sender, id);
764
765			Self::deposit_event(Event::JudgementUnrequested {
766				who: sender,
767				registrar_index: reg_index,
768			});
769
770			Ok(Some(T::WeightInfo::cancel_request(judgements as u32)).into())
771		}
772
773		/// Set the fee required for a judgement to be requested from a registrar.
774		///
775		/// The dispatch origin for this call must be _Signed_ and the sender must be the account
776		/// of the registrar whose index is `index`.
777		///
778		/// - `index`: the index of the registrar whose fee is to be set.
779		/// - `fee`: the new fee.
780		#[pallet::call_index(6)]
781		#[pallet::weight(T::WeightInfo::set_fee(T::MaxRegistrars::get()))]
782		pub fn set_fee(
783			origin: OriginFor<T>,
784			#[pallet::compact] index: RegistrarIndex,
785			#[pallet::compact] fee: BalanceOf<T>,
786		) -> DispatchResultWithPostInfo {
787			let who = ensure_signed(origin)?;
788
789			let registrars = Registrars::<T>::mutate(|rs| -> Result<usize, DispatchError> {
790				rs.get_mut(index as usize)
791					.and_then(|x| x.as_mut())
792					.and_then(|r| {
793						if r.account == who {
794							r.fee = fee;
795							Some(())
796						} else {
797							None
798						}
799					})
800					.ok_or_else(|| DispatchError::from(Error::<T>::InvalidIndex))?;
801				Ok(rs.len())
802			})?;
803			Ok(Some(T::WeightInfo::set_fee(registrars as u32)).into())
804		}
805
806		/// Change the account associated with a registrar.
807		///
808		/// The dispatch origin for this call must be _Signed_ and the sender must be the account
809		/// of the registrar whose index is `index`.
810		///
811		/// - `index`: the index of the registrar whose fee is to be set.
812		/// - `new`: the new account ID.
813		#[pallet::call_index(7)]
814		#[pallet::weight(T::WeightInfo::set_account_id(T::MaxRegistrars::get()))]
815		pub fn set_account_id(
816			origin: OriginFor<T>,
817			#[pallet::compact] index: RegistrarIndex,
818			new: AccountIdLookupOf<T>,
819		) -> DispatchResultWithPostInfo {
820			let who = ensure_signed(origin)?;
821			let new = T::Lookup::lookup(new)?;
822
823			let registrars = Registrars::<T>::mutate(|rs| -> Result<usize, DispatchError> {
824				rs.get_mut(index as usize)
825					.and_then(|x| x.as_mut())
826					.and_then(|r| {
827						if r.account == who {
828							r.account = new;
829							Some(())
830						} else {
831							None
832						}
833					})
834					.ok_or_else(|| DispatchError::from(Error::<T>::InvalidIndex))?;
835				Ok(rs.len())
836			})?;
837			Ok(Some(T::WeightInfo::set_account_id(registrars as u32)).into())
838		}
839
840		/// Set the field information for a registrar.
841		///
842		/// The dispatch origin for this call must be _Signed_ and the sender must be the account
843		/// of the registrar whose index is `index`.
844		///
845		/// - `index`: the index of the registrar whose fee is to be set.
846		/// - `fields`: the fields that the registrar concerns themselves with.
847		#[pallet::call_index(8)]
848		#[pallet::weight(T::WeightInfo::set_fields(T::MaxRegistrars::get()))]
849		pub fn set_fields(
850			origin: OriginFor<T>,
851			#[pallet::compact] index: RegistrarIndex,
852			fields: <T::IdentityInformation as IdentityInformationProvider>::FieldsIdentifier,
853		) -> DispatchResultWithPostInfo {
854			let who = ensure_signed(origin)?;
855
856			let registrars =
857				Registrars::<T>::mutate(|registrars| -> Result<usize, DispatchError> {
858					let registrar = registrars
859						.get_mut(index as usize)
860						.and_then(|r| r.as_mut())
861						.filter(|r| r.account == who)
862						.ok_or_else(|| DispatchError::from(Error::<T>::InvalidIndex))?;
863					registrar.fields = fields;
864
865					Ok(registrars.len())
866				})?;
867			Ok(Some(T::WeightInfo::set_fields(registrars as u32)).into())
868		}
869
870		/// Provide a judgement for an account's identity.
871		///
872		/// The dispatch origin for this call must be _Signed_ and the sender must be the account
873		/// of the registrar whose index is `reg_index`.
874		///
875		/// - `reg_index`: the index of the registrar whose judgement is being made.
876		/// - `target`: the account whose identity the judgement is upon. This must be an account
877		///   with a registered identity.
878		/// - `judgement`: the judgement of the registrar of index `reg_index` about `target`.
879		/// - `identity`: The hash of the [`IdentityInformationProvider`] for that the judgement is
880		///   provided.
881		///
882		/// Note: Judgements do not apply to a username.
883		///
884		/// Emits `JudgementGiven` if successful.
885		#[pallet::call_index(9)]
886		#[pallet::weight(T::WeightInfo::provide_judgement(T::MaxRegistrars::get()))]
887		pub fn provide_judgement(
888			origin: OriginFor<T>,
889			#[pallet::compact] reg_index: RegistrarIndex,
890			target: AccountIdLookupOf<T>,
891			judgement: Judgement<BalanceOf<T>>,
892			identity: T::Hash,
893		) -> DispatchResultWithPostInfo {
894			let sender = ensure_signed(origin)?;
895			let target = T::Lookup::lookup(target)?;
896			ensure!(!judgement.has_deposit(), Error::<T>::InvalidJudgement);
897			Registrars::<T>::get()
898				.get(reg_index as usize)
899				.and_then(Option::as_ref)
900				.filter(|r| r.account == sender)
901				.ok_or(Error::<T>::InvalidIndex)?;
902			let mut id = IdentityOf::<T>::get(&target).ok_or(Error::<T>::InvalidTarget)?;
903
904			if T::Hashing::hash_of(&id.info) != identity {
905				return Err(Error::<T>::JudgementForDifferentIdentity.into())
906			}
907
908			let item = (reg_index, judgement);
909			match id.judgements.binary_search_by_key(&reg_index, |x| x.0) {
910				Ok(position) => {
911					if let Judgement::FeePaid(fee) = id.judgements[position].1 {
912						T::Currency::repatriate_reserved(
913							&target,
914							&sender,
915							fee,
916							BalanceStatus::Free,
917						)
918						.map_err(|_| Error::<T>::JudgementPaymentFailed)?;
919					}
920					id.judgements[position] = item
921				},
922				Err(position) => id
923					.judgements
924					.try_insert(position, item)
925					.map_err(|_| Error::<T>::TooManyRegistrars)?,
926			}
927
928			let judgements = id.judgements.len();
929			IdentityOf::<T>::insert(&target, id);
930			Self::deposit_event(Event::JudgementGiven { target, registrar_index: reg_index });
931
932			Ok(Some(T::WeightInfo::provide_judgement(judgements as u32)).into())
933		}
934
935		/// Remove an account's identity and sub-account information and slash the deposits.
936		///
937		/// Payment: Reserved balances from `set_subs` and `set_identity` are slashed and handled by
938		/// `Slash`. Verification request deposits are not returned; they should be cancelled
939		/// manually using `cancel_request`.
940		///
941		/// The dispatch origin for this call must match `T::ForceOrigin`.
942		///
943		/// - `target`: the account whose identity the judgement is upon. This must be an account
944		///   with a registered identity.
945		///
946		/// Emits `IdentityKilled` if successful.
947		#[pallet::call_index(10)]
948		#[pallet::weight(T::WeightInfo::kill_identity(
949			T::MaxRegistrars::get(),
950			T::MaxSubAccounts::get(),
951		))]
952		pub fn kill_identity(
953			origin: OriginFor<T>,
954			target: AccountIdLookupOf<T>,
955		) -> DispatchResultWithPostInfo {
956			T::ForceOrigin::ensure_origin(origin)?;
957
958			// Figure out who we're meant to be clearing.
959			let target = T::Lookup::lookup(target)?;
960			// Grab their deposit (and check that they have one).
961			let (subs_deposit, sub_ids) = SubsOf::<T>::take(&target);
962			let id = IdentityOf::<T>::take(&target).ok_or(Error::<T>::NoIdentity)?;
963			let deposit = id.total_deposit().saturating_add(subs_deposit);
964			for sub in sub_ids.iter() {
965				SuperOf::<T>::remove(sub);
966			}
967			// Slash their deposit from them.
968			T::Slashed::on_unbalanced(T::Currency::slash_reserved(&target, deposit).0);
969
970			Self::deposit_event(Event::IdentityKilled { who: target, deposit });
971
972			#[allow(deprecated)]
973			Ok(Some(T::WeightInfo::kill_identity(id.judgements.len() as u32, sub_ids.len() as u32))
974				.into())
975		}
976
977		/// Add the given account to the sender's subs.
978		///
979		/// Payment: Balance reserved by a previous `set_subs` call for one sub will be repatriated
980		/// to the sender.
981		///
982		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered
983		/// sub identity of `sub`.
984		#[pallet::call_index(11)]
985		#[pallet::weight(T::WeightInfo::add_sub(T::MaxSubAccounts::get()))]
986		pub fn add_sub(
987			origin: OriginFor<T>,
988			sub: AccountIdLookupOf<T>,
989			data: Data,
990		) -> DispatchResult {
991			let sender = ensure_signed(origin)?;
992			let sub = T::Lookup::lookup(sub)?;
993			ensure!(IdentityOf::<T>::contains_key(&sender), Error::<T>::NoIdentity);
994
995			// Check if it's already claimed as sub-identity.
996			ensure!(!SuperOf::<T>::contains_key(&sub), Error::<T>::AlreadyClaimed);
997
998			SubsOf::<T>::try_mutate(&sender, |(ref mut subs_deposit, ref mut sub_ids)| {
999				// Ensure there is space and that the deposit is paid.
1000				ensure!(
1001					sub_ids.len() < T::MaxSubAccounts::get() as usize,
1002					Error::<T>::TooManySubAccounts
1003				);
1004				let deposit = T::SubAccountDeposit::get();
1005				T::Currency::reserve(&sender, deposit)?;
1006
1007				SuperOf::<T>::insert(&sub, (sender.clone(), data));
1008				sub_ids.try_push(sub.clone()).expect("sub ids length checked above; qed");
1009				*subs_deposit = subs_deposit.saturating_add(deposit);
1010
1011				Self::deposit_event(Event::SubIdentityAdded { sub, main: sender.clone(), deposit });
1012				Ok(())
1013			})
1014		}
1015
1016		/// Alter the associated name of the given sub-account.
1017		///
1018		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered
1019		/// sub identity of `sub`.
1020		#[pallet::call_index(12)]
1021		#[pallet::weight(T::WeightInfo::rename_sub(T::MaxSubAccounts::get()))]
1022		pub fn rename_sub(
1023			origin: OriginFor<T>,
1024			sub: AccountIdLookupOf<T>,
1025			data: Data,
1026		) -> DispatchResult {
1027			let sender = ensure_signed(origin)?;
1028			let sub = T::Lookup::lookup(sub)?;
1029			ensure!(IdentityOf::<T>::contains_key(&sender), Error::<T>::NoIdentity);
1030			ensure!(SuperOf::<T>::get(&sub).map_or(false, |x| x.0 == sender), Error::<T>::NotOwned);
1031			SuperOf::<T>::insert(&sub, (&sender, data));
1032
1033			Self::deposit_event(Event::SubIdentityRenamed { main: sender, sub });
1034			Ok(())
1035		}
1036
1037		/// Remove the given account from the sender's subs.
1038		///
1039		/// Payment: Balance reserved by a previous `set_subs` call for one sub will be repatriated
1040		/// to the sender.
1041		///
1042		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered
1043		/// sub identity of `sub`.
1044		#[pallet::call_index(13)]
1045		#[pallet::weight(T::WeightInfo::remove_sub(T::MaxSubAccounts::get()))]
1046		pub fn remove_sub(origin: OriginFor<T>, sub: AccountIdLookupOf<T>) -> DispatchResult {
1047			let sender = ensure_signed(origin)?;
1048			ensure!(IdentityOf::<T>::contains_key(&sender), Error::<T>::NoIdentity);
1049			let sub = T::Lookup::lookup(sub)?;
1050			let (sup, _) = SuperOf::<T>::get(&sub).ok_or(Error::<T>::NotSub)?;
1051			ensure!(sup == sender, Error::<T>::NotOwned);
1052			SuperOf::<T>::remove(&sub);
1053			SubsOf::<T>::mutate(&sup, |(ref mut subs_deposit, ref mut sub_ids)| {
1054				sub_ids.retain(|x| x != &sub);
1055				let deposit = T::SubAccountDeposit::get().min(*subs_deposit);
1056				*subs_deposit -= deposit;
1057				let err_amount = T::Currency::unreserve(&sender, deposit);
1058				debug_assert!(err_amount.is_zero());
1059				Self::deposit_event(Event::SubIdentityRemoved { sub, main: sender, deposit });
1060			});
1061			Ok(())
1062		}
1063
1064		/// Remove the sender as a sub-account.
1065		///
1066		/// Payment: Balance reserved by a previous `set_subs` call for one sub will be repatriated
1067		/// to the sender (*not* the original depositor).
1068		///
1069		/// The dispatch origin for this call must be _Signed_ and the sender must have a registered
1070		/// super-identity.
1071		///
1072		/// NOTE: This should not normally be used, but is provided in the case that the non-
1073		/// controller of an account is maliciously registered as a sub-account.
1074		#[pallet::call_index(14)]
1075		#[pallet::weight(T::WeightInfo::quit_sub(T::MaxSubAccounts::get()))]
1076		pub fn quit_sub(origin: OriginFor<T>) -> DispatchResult {
1077			let sender = ensure_signed(origin)?;
1078			let (sup, _) = SuperOf::<T>::take(&sender).ok_or(Error::<T>::NotSub)?;
1079			SubsOf::<T>::mutate(&sup, |(ref mut subs_deposit, ref mut sub_ids)| {
1080				sub_ids.retain(|x| x != &sender);
1081				let deposit = T::SubAccountDeposit::get().min(*subs_deposit);
1082				*subs_deposit -= deposit;
1083				let _ =
1084					T::Currency::repatriate_reserved(&sup, &sender, deposit, BalanceStatus::Free);
1085				Self::deposit_event(Event::SubIdentityRevoked {
1086					sub: sender,
1087					main: sup.clone(),
1088					deposit,
1089				});
1090			});
1091			Ok(())
1092		}
1093
1094		/// Add an `AccountId` with permission to grant usernames with a given `suffix` appended.
1095		///
1096		/// The authority can grant up to `allocation` usernames. To top up the allocation or
1097		/// change the account used to grant usernames, this call can be used with the updated
1098		/// parameters to overwrite the existing configuration.
1099		#[pallet::call_index(15)]
1100		#[pallet::weight(T::WeightInfo::add_username_authority())]
1101		pub fn add_username_authority(
1102			origin: OriginFor<T>,
1103			authority: AccountIdLookupOf<T>,
1104			suffix: Vec<u8>,
1105			allocation: u32,
1106		) -> DispatchResult {
1107			T::UsernameAuthorityOrigin::ensure_origin(origin)?;
1108			let authority = T::Lookup::lookup(authority)?;
1109			// We don't need to check the length because it gets checked when casting into a
1110			// `BoundedVec`.
1111			Self::validate_suffix(&suffix)?;
1112			let suffix = Suffix::<T>::try_from(suffix).map_err(|_| Error::<T>::InvalidSuffix)?;
1113			// The call is `UsernameAuthorityOrigin` guarded, overwrite the old entry if it exists.
1114			AuthorityOf::<T>::insert(
1115				&suffix,
1116				AuthorityProperties::<T::AccountId> { account_id: authority.clone(), allocation },
1117			);
1118			Self::deposit_event(Event::AuthorityAdded { authority });
1119			Ok(())
1120		}
1121
1122		/// Remove `authority` from the username authorities.
1123		#[pallet::call_index(16)]
1124		#[pallet::weight(T::WeightInfo::remove_username_authority())]
1125		pub fn remove_username_authority(
1126			origin: OriginFor<T>,
1127			suffix: Vec<u8>,
1128			authority: AccountIdLookupOf<T>,
1129		) -> DispatchResult {
1130			T::UsernameAuthorityOrigin::ensure_origin(origin)?;
1131			let suffix = Suffix::<T>::try_from(suffix).map_err(|_| Error::<T>::InvalidSuffix)?;
1132			let authority = T::Lookup::lookup(authority)?;
1133			let properties =
1134				AuthorityOf::<T>::take(&suffix).ok_or(Error::<T>::NotUsernameAuthority)?;
1135			ensure!(properties.account_id == authority, Error::<T>::InvalidSuffix);
1136			Self::deposit_event(Event::AuthorityRemoved { authority });
1137			Ok(())
1138		}
1139
1140		/// Set the username for `who`. Must be called by a username authority.
1141		///
1142		/// If `use_allocation` is set, the authority must have a username allocation available to
1143		/// spend. Otherwise, the authority will need to put up a deposit for registering the
1144		/// username.
1145		///
1146		/// Users can either pre-sign their usernames or
1147		/// accept them later.
1148		///
1149		/// Usernames must:
1150		///   - Only contain lowercase ASCII characters or digits.
1151		///   - When combined with the suffix of the issuing authority be _less than_ the
1152		///     `MaxUsernameLength`.
1153		#[pallet::call_index(17)]
1154		#[pallet::weight(T::WeightInfo::set_username_for(if *use_allocation { 1 } else { 0 }))]
1155		pub fn set_username_for(
1156			origin: OriginFor<T>,
1157			who: AccountIdLookupOf<T>,
1158			username: Vec<u8>,
1159			signature: Option<T::OffchainSignature>,
1160			use_allocation: bool,
1161		) -> DispatchResult {
1162			// Ensure origin is a Username Authority and has an allocation. Decrement their
1163			// allocation by one.
1164			let sender = ensure_signed(origin)?;
1165			let suffix = Self::validate_username(&username)?;
1166			let provider = AuthorityOf::<T>::try_mutate(
1167				&suffix,
1168				|maybe_authority| -> Result<ProviderOf<T>, DispatchError> {
1169					let properties =
1170						maybe_authority.as_mut().ok_or(Error::<T>::NotUsernameAuthority)?;
1171					ensure!(properties.account_id == sender, Error::<T>::NotUsernameAuthority);
1172					if use_allocation {
1173						ensure!(properties.allocation > 0, Error::<T>::NoAllocation);
1174						properties.allocation.saturating_dec();
1175						Ok(Provider::new_with_allocation())
1176					} else {
1177						let deposit = T::UsernameDeposit::get();
1178						T::Currency::reserve(&sender, deposit)?;
1179						Ok(Provider::new_with_deposit(deposit))
1180					}
1181				},
1182			)?;
1183
1184			let bounded_username =
1185				Username::<T>::try_from(username).map_err(|_| Error::<T>::InvalidUsername)?;
1186
1187			// Usernames must be unique. Ensure it's not taken.
1188			ensure!(
1189				!UsernameInfoOf::<T>::contains_key(&bounded_username),
1190				Error::<T>::UsernameTaken
1191			);
1192			ensure!(
1193				!PendingUsernames::<T>::contains_key(&bounded_username),
1194				Error::<T>::UsernameTaken
1195			);
1196
1197			// Insert or queue.
1198			let who = T::Lookup::lookup(who)?;
1199			if let Some(s) = signature {
1200				// Account has pre-signed an authorization. Verify the signature provided and grant
1201				// the username directly.
1202				Self::validate_signature(&bounded_username[..], &s, &who)?;
1203				Self::insert_username(&who, bounded_username, provider);
1204			} else {
1205				// The user must accept the username, therefore, queue it.
1206				Self::queue_acceptance(&who, bounded_username, provider);
1207			}
1208			Ok(())
1209		}
1210
1211		/// Accept a given username that an `authority` granted. The call must include the full
1212		/// username, as in `username.suffix`.
1213		#[pallet::call_index(18)]
1214		#[pallet::weight(T::WeightInfo::accept_username())]
1215		pub fn accept_username(
1216			origin: OriginFor<T>,
1217			username: Username<T>,
1218		) -> DispatchResultWithPostInfo {
1219			let who = ensure_signed(origin)?;
1220			let (approved_for, _, provider) =
1221				PendingUsernames::<T>::take(&username).ok_or(Error::<T>::NoUsername)?;
1222			ensure!(approved_for == who.clone(), Error::<T>::InvalidUsername);
1223			Self::insert_username(&who, username.clone(), provider);
1224			Self::deposit_event(Event::UsernameSet { who: who.clone(), username });
1225			Ok(Pays::No.into())
1226		}
1227
1228		/// Remove an expired username approval. The username was approved by an authority but never
1229		/// accepted by the user and must now be beyond its expiration. The call must include the
1230		/// full username, as in `username.suffix`.
1231		#[pallet::call_index(19)]
1232		#[pallet::weight(T::WeightInfo::remove_expired_approval(0))]
1233		pub fn remove_expired_approval(
1234			origin: OriginFor<T>,
1235			username: Username<T>,
1236		) -> DispatchResultWithPostInfo {
1237			ensure_signed(origin)?;
1238			if let Some((who, expiration, provider)) = PendingUsernames::<T>::take(&username) {
1239				let now = frame_system::Pallet::<T>::block_number();
1240				ensure!(now > expiration, Error::<T>::NotExpired);
1241				let actual_weight = match provider {
1242					Provider::AuthorityDeposit(deposit) => {
1243						let suffix = Self::suffix_of_username(&username)
1244							.ok_or(Error::<T>::InvalidUsername)?;
1245						let authority_account = AuthorityOf::<T>::get(&suffix)
1246							.map(|auth_info| auth_info.account_id)
1247							.ok_or(Error::<T>::NotUsernameAuthority)?;
1248						let err_amount = T::Currency::unreserve(&authority_account, deposit);
1249						debug_assert!(err_amount.is_zero());
1250						T::WeightInfo::remove_expired_approval(0)
1251					},
1252					Provider::Allocation => {
1253						// We don't refund the allocation, it is lost, but we refund some weight.
1254						T::WeightInfo::remove_expired_approval(1)
1255					},
1256					Provider::System => {
1257						// Usernames added by the system shouldn't ever be expired.
1258						return Err(Error::<T>::InvalidTarget.into());
1259					},
1260				};
1261				Self::deposit_event(Event::PreapprovalExpired { whose: who.clone() });
1262				Ok((Some(actual_weight), Pays::No).into())
1263			} else {
1264				Err(Error::<T>::NoUsername.into())
1265			}
1266		}
1267
1268		/// Set a given username as the primary. The username should include the suffix.
1269		#[pallet::call_index(20)]
1270		#[pallet::weight(T::WeightInfo::set_primary_username())]
1271		pub fn set_primary_username(origin: OriginFor<T>, username: Username<T>) -> DispatchResult {
1272			// ensure `username` maps to `origin` (i.e. has already been set by an authority).
1273			let who = ensure_signed(origin)?;
1274			let account_of_username =
1275				UsernameInfoOf::<T>::get(&username).ok_or(Error::<T>::NoUsername)?.owner;
1276			ensure!(who == account_of_username, Error::<T>::InvalidUsername);
1277			UsernameOf::<T>::insert(&who, username.clone());
1278			Self::deposit_event(Event::PrimaryUsernameSet { who: who.clone(), username });
1279			Ok(())
1280		}
1281
1282		/// Start the process of removing a username by placing it in the unbinding usernames map.
1283		/// Once the grace period has passed, the username can be deleted by calling
1284		/// [remove_username](crate::Call::remove_username).
1285		#[pallet::call_index(21)]
1286		#[pallet::weight(T::WeightInfo::unbind_username())]
1287		pub fn unbind_username(origin: OriginFor<T>, username: Username<T>) -> DispatchResult {
1288			let who = ensure_signed(origin)?;
1289			let username_info =
1290				UsernameInfoOf::<T>::get(&username).ok_or(Error::<T>::NoUsername)?;
1291			let suffix = Self::suffix_of_username(&username).ok_or(Error::<T>::InvalidUsername)?;
1292			let authority_account = AuthorityOf::<T>::get(&suffix)
1293				.map(|auth_info| auth_info.account_id)
1294				.ok_or(Error::<T>::NotUsernameAuthority)?;
1295			ensure!(who == authority_account, Error::<T>::NotUsernameAuthority);
1296			match username_info.provider {
1297				Provider::AuthorityDeposit(_) | Provider::Allocation => {
1298					let now = frame_system::Pallet::<T>::block_number();
1299					let grace_period_expiry = now.saturating_add(T::UsernameGracePeriod::get());
1300					UnbindingUsernames::<T>::try_mutate(&username, |maybe_init| {
1301						if maybe_init.is_some() {
1302							return Err(Error::<T>::AlreadyUnbinding);
1303						}
1304						*maybe_init = Some(grace_period_expiry);
1305						Ok(())
1306					})?;
1307				},
1308				Provider::System => return Err(Error::<T>::InsufficientPrivileges.into()),
1309			}
1310			Self::deposit_event(Event::UsernameUnbound { username });
1311			Ok(())
1312		}
1313
1314		/// Permanently delete a username which has been unbinding for longer than the grace period.
1315		/// Caller is refunded the fee if the username expired and the removal was successful.
1316		#[pallet::call_index(22)]
1317		#[pallet::weight(T::WeightInfo::remove_username())]
1318		pub fn remove_username(
1319			origin: OriginFor<T>,
1320			username: Username<T>,
1321		) -> DispatchResultWithPostInfo {
1322			ensure_signed(origin)?;
1323			let grace_period_expiry =
1324				UnbindingUsernames::<T>::take(&username).ok_or(Error::<T>::NotUnbinding)?;
1325			let now = frame_system::Pallet::<T>::block_number();
1326			ensure!(now >= grace_period_expiry, Error::<T>::TooEarly);
1327			let username_info = UsernameInfoOf::<T>::take(&username)
1328				.defensive_proof("an unbinding username must exist")
1329				.ok_or(Error::<T>::NoUsername)?;
1330			// If this is the primary username, remove the entry from the account -> username map.
1331			UsernameOf::<T>::mutate(&username_info.owner, |maybe_primary| {
1332				if maybe_primary.as_ref().map_or(false, |primary| *primary == username) {
1333					*maybe_primary = None;
1334				}
1335			});
1336			match username_info.provider {
1337				Provider::AuthorityDeposit(username_deposit) => {
1338					let suffix = Self::suffix_of_username(&username)
1339						.defensive_proof("registered username must be valid")
1340						.ok_or(Error::<T>::InvalidUsername)?;
1341					if let Some(authority_account) =
1342						AuthorityOf::<T>::get(&suffix).map(|auth_info| auth_info.account_id)
1343					{
1344						let err_amount =
1345							T::Currency::unreserve(&authority_account, username_deposit);
1346						debug_assert!(err_amount.is_zero());
1347					}
1348				},
1349				Provider::Allocation => {
1350					// We don't refund the allocation, it is lost.
1351				},
1352				Provider::System => return Err(Error::<T>::InsufficientPrivileges.into()),
1353			}
1354			Self::deposit_event(Event::UsernameRemoved { username });
1355			Ok(Pays::No.into())
1356		}
1357
1358		/// Call with [ForceOrigin](crate::Config::ForceOrigin) privileges which deletes a username
1359		/// and slashes any deposit associated with it.
1360		#[pallet::call_index(23)]
1361		#[pallet::weight(T::WeightInfo::kill_username(0))]
1362		pub fn kill_username(
1363			origin: OriginFor<T>,
1364			username: Username<T>,
1365		) -> DispatchResultWithPostInfo {
1366			T::ForceOrigin::ensure_origin(origin)?;
1367			let username_info =
1368				UsernameInfoOf::<T>::take(&username).ok_or(Error::<T>::NoUsername)?;
1369			// If this is the primary username, remove the entry from the account -> username map.
1370			UsernameOf::<T>::mutate(&username_info.owner, |maybe_primary| {
1371				if match maybe_primary {
1372					Some(primary) if *primary == username => true,
1373					_ => false,
1374				} {
1375					*maybe_primary = None;
1376				}
1377			});
1378			let _ = UnbindingUsernames::<T>::take(&username);
1379			let actual_weight = match username_info.provider {
1380				Provider::AuthorityDeposit(username_deposit) => {
1381					let suffix =
1382						Self::suffix_of_username(&username).ok_or(Error::<T>::InvalidUsername)?;
1383					if let Some(authority_account) =
1384						AuthorityOf::<T>::get(&suffix).map(|auth_info| auth_info.account_id)
1385					{
1386						T::Slashed::on_unbalanced(
1387							T::Currency::slash_reserved(&authority_account, username_deposit).0,
1388						);
1389					}
1390					T::WeightInfo::kill_username(0)
1391				},
1392				Provider::Allocation => {
1393					// We don't refund the allocation, it is lost, but we do refund some weight.
1394					T::WeightInfo::kill_username(1)
1395				},
1396				Provider::System => {
1397					// Force origin can remove system usernames.
1398					T::WeightInfo::kill_username(1)
1399				},
1400			};
1401			Self::deposit_event(Event::UsernameKilled { username });
1402			Ok((Some(actual_weight), Pays::No).into())
1403		}
1404	}
1405}
1406
1407impl<T: Config> Pallet<T> {
1408	/// Get the subs of an account.
1409	pub fn subs(who: &T::AccountId) -> Vec<(T::AccountId, Data)> {
1410		SubsOf::<T>::get(who)
1411			.1
1412			.into_iter()
1413			.filter_map(|a| SuperOf::<T>::get(&a).map(|x| (a, x.1)))
1414			.collect()
1415	}
1416
1417	/// Calculate the deposit required for a number of `sub` accounts.
1418	fn subs_deposit(subs: u32) -> BalanceOf<T> {
1419		T::SubAccountDeposit::get().saturating_mul(BalanceOf::<T>::from(subs))
1420	}
1421
1422	/// Take the `current` deposit that `who` is holding, and update it to a `new` one.
1423	fn rejig_deposit(
1424		who: &T::AccountId,
1425		current: BalanceOf<T>,
1426		new: BalanceOf<T>,
1427	) -> DispatchResult {
1428		if new > current {
1429			T::Currency::reserve(who, new - current)?;
1430		} else if new < current {
1431			let err_amount = T::Currency::unreserve(who, current - new);
1432			debug_assert!(err_amount.is_zero());
1433		}
1434		Ok(())
1435	}
1436
1437	/// Check if the account has corresponding identity information by the identity field.
1438	pub fn has_identity(
1439		who: &T::AccountId,
1440		fields: <T::IdentityInformation as IdentityInformationProvider>::FieldsIdentifier,
1441	) -> bool {
1442		IdentityOf::<T>::get(who)
1443			.map_or(false, |registration| (registration.info.has_identity(fields)))
1444	}
1445
1446	/// Calculate the deposit required for an identity.
1447	fn calculate_identity_deposit(info: &T::IdentityInformation) -> BalanceOf<T> {
1448		let bytes = info.encoded_size() as u32;
1449		let byte_deposit = T::ByteDeposit::get().saturating_mul(BalanceOf::<T>::from(bytes));
1450		T::BasicDeposit::get().saturating_add(byte_deposit)
1451	}
1452
1453	/// Validate that a username conforms to allowed characters/format.
1454	///
1455	/// The function will validate the characters in `username`. It is expected to pass a fully
1456	/// formatted username here (i.e. "username.suffix"). The suffix is also separately validated
1457	/// and returned by this function.
1458	fn validate_username(username: &Vec<u8>) -> Result<Suffix<T>, DispatchError> {
1459		// Verify input length before allocating a Vec with the user's input.
1460		ensure!(
1461			username.len() <= T::MaxUsernameLength::get() as usize,
1462			Error::<T>::InvalidUsername
1463		);
1464
1465		// Usernames cannot be empty.
1466		ensure!(!username.is_empty(), Error::<T>::InvalidUsername);
1467		let separator_idx =
1468			username.iter().rposition(|c| *c == b'.').ok_or(Error::<T>::InvalidUsername)?;
1469		ensure!(separator_idx > 0, Error::<T>::InvalidUsername);
1470		let suffix_start = separator_idx.checked_add(1).ok_or(Error::<T>::InvalidUsername)?;
1471		ensure!(suffix_start < username.len(), Error::<T>::InvalidUsername);
1472		// Username must be lowercase and alphanumeric.
1473		ensure!(
1474			username
1475				.iter()
1476				.take(separator_idx)
1477				.all(|byte| byte.is_ascii_digit() || byte.is_ascii_lowercase()),
1478			Error::<T>::InvalidUsername
1479		);
1480		let suffix: Suffix<T> = (&username[suffix_start..])
1481			.to_vec()
1482			.try_into()
1483			.map_err(|_| Error::<T>::InvalidUsername)?;
1484		Ok(suffix)
1485	}
1486
1487	/// Return the suffix of a username, if it is valid.
1488	fn suffix_of_username(username: &Username<T>) -> Option<Suffix<T>> {
1489		let separator_idx = username.iter().rposition(|c| *c == b'.')?;
1490		let suffix_start = separator_idx.checked_add(1)?;
1491		if suffix_start >= username.len() {
1492			return None;
1493		}
1494		(&username[suffix_start..]).to_vec().try_into().ok()
1495	}
1496
1497	/// Validate that a suffix conforms to allowed characters/format.
1498	fn validate_suffix(suffix: &Vec<u8>) -> Result<(), DispatchError> {
1499		ensure!(suffix.len() <= T::MaxSuffixLength::get() as usize, Error::<T>::InvalidSuffix);
1500		ensure!(!suffix.is_empty(), Error::<T>::InvalidSuffix);
1501		ensure!(
1502			suffix.iter().all(|byte| byte.is_ascii_digit() || byte.is_ascii_lowercase()),
1503			Error::<T>::InvalidSuffix
1504		);
1505		Ok(())
1506	}
1507
1508	/// Validate a signature. Supports signatures on raw `data` or `data` wrapped in HTML `<Bytes>`.
1509	pub fn validate_signature(
1510		data: &[u8],
1511		signature: &T::OffchainSignature,
1512		signer: &T::AccountId,
1513	) -> DispatchResult {
1514		// Happy path, user has signed the raw data.
1515		if signature.verify(data, &signer) {
1516			return Ok(())
1517		}
1518		// NOTE: for security reasons modern UIs implicitly wrap the data requested to sign into
1519		// `<Bytes> + data + </Bytes>`, so why we support both wrapped and raw versions.
1520		let prefix = b"<Bytes>";
1521		let suffix = b"</Bytes>";
1522		let mut wrapped: Vec<u8> = Vec::with_capacity(data.len() + prefix.len() + suffix.len());
1523		wrapped.extend(prefix);
1524		wrapped.extend(data);
1525		wrapped.extend(suffix);
1526
1527		ensure!(signature.verify(&wrapped[..], &signer), Error::<T>::InvalidSignature);
1528
1529		Ok(())
1530	}
1531
1532	/// A username has met all conditions. Insert the relevant storage items.
1533	pub fn insert_username(who: &T::AccountId, username: Username<T>, provider: ProviderOf<T>) {
1534		// Check if they already have a primary. If so, leave it. If not, set it.
1535		// Likewise, check if they have an identity. If not, give them a minimal one.
1536		let (primary_username, new_is_primary) = match UsernameOf::<T>::get(&who) {
1537			// User has an existing Identity and a primary username. Leave it.
1538			Some(primary) => (primary, false),
1539			// User has an Identity but no primary. Set the new one as primary.
1540			None => (username.clone(), true),
1541		};
1542
1543		if new_is_primary {
1544			UsernameOf::<T>::insert(&who, primary_username);
1545		}
1546		let username_info = UsernameInformation { owner: who.clone(), provider };
1547		// Enter in username map.
1548		UsernameInfoOf::<T>::insert(username.clone(), username_info);
1549		Self::deposit_event(Event::UsernameSet { who: who.clone(), username: username.clone() });
1550		if new_is_primary {
1551			Self::deposit_event(Event::PrimaryUsernameSet { who: who.clone(), username });
1552		}
1553	}
1554
1555	/// A username was granted by an authority, but must be accepted by `who`. Put the username
1556	/// into a queue for acceptance.
1557	pub fn queue_acceptance(who: &T::AccountId, username: Username<T>, provider: ProviderOf<T>) {
1558		let now = frame_system::Pallet::<T>::block_number();
1559		let expiration = now.saturating_add(T::PendingUsernameExpiration::get());
1560		PendingUsernames::<T>::insert(&username, (who.clone(), expiration, provider));
1561		Self::deposit_event(Event::UsernameQueued { who: who.clone(), username, expiration });
1562	}
1563
1564	/// Reap an identity, clearing associated storage items and refunding any deposits. This
1565	/// function is very similar to (a) `clear_identity`, but called on a `target` account instead
1566	/// of self; and (b) `kill_identity`, but without imposing a slash.
1567	///
1568	/// Parameters:
1569	/// - `target`: The account for which to reap identity state.
1570	///
1571	/// Return type is a tuple of the number of registrars, `IdentityInfo` bytes, and sub accounts,
1572	/// respectively.
1573	///
1574	/// NOTE: This function is here temporarily for migration of Identity info from the Polkadot
1575	/// Relay Chain into a system parachain. It will be removed after the migration.
1576	pub fn reap_identity(who: &T::AccountId) -> Result<(u32, u32, u32), DispatchError> {
1577		// `take` any storage items keyed by `target`
1578		// identity
1579		let id = IdentityOf::<T>::take(&who).ok_or(Error::<T>::NoIdentity)?;
1580		let registrars = id.judgements.len() as u32;
1581		let encoded_byte_size = id.info.encoded_size() as u32;
1582
1583		// subs
1584		let (subs_deposit, sub_ids) = SubsOf::<T>::take(&who);
1585		let actual_subs = sub_ids.len() as u32;
1586		for sub in sub_ids.iter() {
1587			SuperOf::<T>::remove(sub);
1588		}
1589
1590		// unreserve any deposits
1591		let deposit = id.total_deposit().saturating_add(subs_deposit);
1592		let err_amount = T::Currency::unreserve(&who, deposit);
1593		debug_assert!(err_amount.is_zero());
1594		Ok((registrars, encoded_byte_size, actual_subs))
1595	}
1596
1597	/// Update the deposits held by `target` for its identity info.
1598	///
1599	/// Parameters:
1600	/// - `target`: The account for which to update deposits.
1601	///
1602	/// Return type is a tuple of the new Identity and Subs deposits, respectively.
1603	///
1604	/// NOTE: This function is here temporarily for migration of Identity info from the Polkadot
1605	/// Relay Chain into a system parachain. It will be removed after the migration.
1606	pub fn poke_deposit(
1607		target: &T::AccountId,
1608	) -> Result<(BalanceOf<T>, BalanceOf<T>), DispatchError> {
1609		// Identity Deposit
1610		let new_id_deposit = IdentityOf::<T>::try_mutate(
1611			&target,
1612			|identity_of| -> Result<BalanceOf<T>, DispatchError> {
1613				let reg = identity_of.as_mut().ok_or(Error::<T>::NoIdentity)?;
1614				// Calculate what deposit should be
1615				let encoded_byte_size = reg.info.encoded_size() as u32;
1616				let byte_deposit =
1617					T::ByteDeposit::get().saturating_mul(BalanceOf::<T>::from(encoded_byte_size));
1618				let new_id_deposit = T::BasicDeposit::get().saturating_add(byte_deposit);
1619
1620				// Update account
1621				Self::rejig_deposit(&target, reg.deposit, new_id_deposit)?;
1622
1623				reg.deposit = new_id_deposit;
1624				Ok(new_id_deposit)
1625			},
1626		)?;
1627
1628		let new_subs_deposit = if SubsOf::<T>::contains_key(&target) {
1629			SubsOf::<T>::try_mutate(
1630				&target,
1631				|(current_subs_deposit, subs_of)| -> Result<BalanceOf<T>, DispatchError> {
1632					let new_subs_deposit = Self::subs_deposit(subs_of.len() as u32);
1633					Self::rejig_deposit(&target, *current_subs_deposit, new_subs_deposit)?;
1634					*current_subs_deposit = new_subs_deposit;
1635					Ok(new_subs_deposit)
1636				},
1637			)?
1638		} else {
1639			// If the item doesn't exist, there is no "old" deposit, and the new one is zero, so no
1640			// need to call rejig, it'd just be zero -> zero.
1641			Zero::zero()
1642		};
1643		Ok((new_id_deposit, new_subs_deposit))
1644	}
1645
1646	/// Set an identity with zero deposit. Used for benchmarking and XCM emulator tests that involve
1647	/// `rejig_deposit`.
1648	#[cfg(any(feature = "runtime-benchmarks", feature = "std"))]
1649	pub fn set_identity_no_deposit(
1650		who: &T::AccountId,
1651		info: T::IdentityInformation,
1652	) -> DispatchResult {
1653		IdentityOf::<T>::insert(
1654			&who,
1655			Registration {
1656				judgements: Default::default(),
1657				deposit: Zero::zero(),
1658				info: info.clone(),
1659			},
1660		);
1661		Ok(())
1662	}
1663
1664	/// Set subs with zero deposit and default name. Only used for benchmarks that involve
1665	/// `rejig_deposit`.
1666	#[cfg(any(feature = "runtime-benchmarks", feature = "std"))]
1667	pub fn set_subs_no_deposit(
1668		who: &T::AccountId,
1669		subs: Vec<(T::AccountId, Data)>,
1670	) -> DispatchResult {
1671		let mut sub_accounts = BoundedVec::<T::AccountId, T::MaxSubAccounts>::default();
1672		for (sub, name) in subs {
1673			SuperOf::<T>::insert(&sub, (who.clone(), name));
1674			sub_accounts
1675				.try_push(sub)
1676				.expect("benchmark should not pass more than T::MaxSubAccounts");
1677		}
1678		SubsOf::<T>::insert::<
1679			&T::AccountId,
1680			(BalanceOf<T>, BoundedVec<T::AccountId, T::MaxSubAccounts>),
1681		>(&who, (Zero::zero(), sub_accounts));
1682		Ok(())
1683	}
1684}