diff --git a/substrate/bin/node/runtime/src/lib.rs b/substrate/bin/node/runtime/src/lib.rs index 36ad4d985cfd5..f4c8a5940a3ca 100644 --- a/substrate/bin/node/runtime/src/lib.rs +++ b/substrate/bin/node/runtime/src/lib.rs @@ -60,6 +60,7 @@ use node_primitives::{AccountIndex, Balance, BlockNumber, Hash, Moment, Nonce}; use pallet_asset_conversion::{NativeOrAssetId, NativeOrAssetIdConverter}; use pallet_broker::{CoreAssignment, CoreIndex, CoretimeInterface, PartsOf57600}; use pallet_election_provider_multi_phase::{GeometricDepositBase, SolutionAccuracyOf}; +use pallet_identity::simple::IdentityInfo; use pallet_im_online::sr25519::AuthorityId as ImOnlineId; use pallet_nfts::PalletFeatures; use pallet_nis::WithMaximumOf; @@ -1474,6 +1475,7 @@ impl pallet_identity::Config for Runtime { type SubAccountDeposit = SubAccountDeposit; type MaxSubAccounts = MaxSubAccounts; type MaxAdditionalFields = MaxAdditionalFields; + type IdentityInformation = IdentityInfo; type MaxRegistrars = MaxRegistrars; type Slashed = Treasury; type ForceOrigin = EnsureRootOrHalfCouncil; diff --git a/substrate/frame/alliance/src/lib.rs b/substrate/frame/alliance/src/lib.rs index 627399f805b31..f3ff03780f59a 100644 --- a/substrate/frame/alliance/src/lib.rs +++ b/substrate/frame/alliance/src/lib.rs @@ -112,7 +112,7 @@ use frame_support::{ }, weights::Weight, }; -use pallet_identity::IdentityField; +use pallet_identity::simple::IdentityField; use scale_info::TypeInfo; pub use pallet::*; diff --git a/substrate/frame/alliance/src/mock.rs b/substrate/frame/alliance/src/mock.rs index eac8411699e89..a5970bc7af675 100644 --- a/substrate/frame/alliance/src/mock.rs +++ b/substrate/frame/alliance/src/mock.rs @@ -31,7 +31,7 @@ pub use frame_support::{ BoundedVec, }; use frame_system::{EnsureRoot, EnsureSignedBy}; -use pallet_identity::{Data, IdentityInfo, Judgement}; +use pallet_identity::{simple::IdentityInfo, Data, Judgement}; pub use crate as pallet_alliance; @@ -121,6 +121,7 @@ impl pallet_identity::Config for Test { type SubAccountDeposit = SubAccountDeposit; type MaxSubAccounts = MaxSubAccounts; type MaxAdditionalFields = MaxAdditionalFields; + type IdentityInformation = IdentityInfo; type MaxRegistrars = MaxRegistrars; type Slashed = (); type RegistrarOrigin = EnsureOneOrRoot; diff --git a/substrate/frame/identity/src/benchmarking.rs b/substrate/frame/identity/src/benchmarking.rs index 059de204bbf77..16ce4d8246e61 100644 --- a/substrate/frame/identity/src/benchmarking.rs +++ b/substrate/frame/identity/src/benchmarking.rs @@ -22,6 +22,7 @@ use super::*; use crate::Pallet as Identity; +use enumflags2::BitFlag; use frame_benchmarking::{ account, impl_benchmark_test_suite, v2::*, whitelisted_caller, BenchmarkError, }; @@ -48,14 +49,9 @@ fn add_registrars(r: u32) -> Result<(), &'static str> { .expect("RegistrarOrigin has no successful origin required for the benchmark"); Identity::::add_registrar(registrar_origin, registrar_lookup)?; Identity::::set_fee(RawOrigin::Signed(registrar.clone()).into(), i, 10u32.into())?; - let fields = - IdentityFields( - IdentityField::Display | - IdentityField::Legal | IdentityField::Web | - IdentityField::Riot | IdentityField::Email | - IdentityField::PgpFingerprint | - IdentityField::Image | IdentityField::Twitter, - ); + let fields = IdentityFields( + ::IdentityField::all(), + ); Identity::::set_fields(RawOrigin::Signed(registrar.clone()).into(), i, fields)?; } @@ -81,7 +77,7 @@ fn create_sub_accounts( // Set identity so `set_subs` does not fail. if IdentityOf::::get(who).is_none() { let _ = T::Currency::make_free_balance_be(who, BalanceOf::::max_value() / 2u32.into()); - let info = create_identity_info::(1); + let info = T::IdentityInformation::create_identity_info(1); Identity::::set_identity(who_origin.into(), Box::new(info))?; } @@ -102,24 +98,6 @@ fn add_sub_accounts( Ok(subs) } -// This creates an `IdentityInfo` object with `num_fields` extra fields. -// All data is pre-populated with some arbitrary bytes. -fn create_identity_info(num_fields: u32) -> IdentityInfo { - let data = Data::Raw(vec![0; 32].try_into().unwrap()); - - IdentityInfo { - additional: vec![(data.clone(), data.clone()); num_fields as usize].try_into().unwrap(), - display: data.clone(), - legal: data.clone(), - web: data.clone(), - riot: data.clone(), - email: data.clone(), - pgp_fingerprint: Some([0; 20]), - image: data.clone(), - twitter: data, - } -} - #[benchmarks] mod benchmarks { use super::*; @@ -153,7 +131,7 @@ mod benchmarks { let _ = T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); // Add an initial identity - let initial_info = create_identity_info::(1); + let initial_info = T::IdentityInformation::create_identity_info(1); Identity::::set_identity(caller_origin.clone(), Box::new(initial_info.clone()))?; // User requests judgement from all the registrars, and they approve @@ -174,7 +152,10 @@ mod benchmarks { } #[extrinsic_call] - _(RawOrigin::Signed(caller.clone()), Box::new(create_identity_info::(x))); + _( + RawOrigin::Signed(caller.clone()), + Box::new(T::IdentityInformation::create_identity_info(x)), + ); assert_last_event::(Event::::IdentitySet { who: caller }.into()); Ok(()) @@ -235,7 +216,7 @@ mod benchmarks { let _ = add_sub_accounts::(&caller, s)?; // Create their main identity with x additional fields - let info = create_identity_info::(x); + let info = T::IdentityInformation::create_identity_info(x); Identity::::set_identity(caller_origin.clone(), Box::new(info.clone()))?; // User requests judgement from all the registrars, and they approve @@ -275,7 +256,7 @@ mod benchmarks { add_registrars::(r)?; // Create their main identity with x additional fields - let info = create_identity_info::(x); + let info = T::IdentityInformation::create_identity_info(x); let caller_origin = ::RuntimeOrigin::from(RawOrigin::Signed(caller.clone())); Identity::::set_identity(caller_origin.clone(), Box::new(info))?; @@ -302,7 +283,7 @@ mod benchmarks { add_registrars::(r)?; // Create their main identity with x additional fields - let info = create_identity_info::(x); + let info = T::IdentityInformation::create_identity_info(x); let caller_origin = ::RuntimeOrigin::from(RawOrigin::Signed(caller.clone())); Identity::::set_identity(caller_origin.clone(), Box::new(info))?; @@ -386,14 +367,9 @@ mod benchmarks { .expect("RegistrarOrigin has no successful origin required for the benchmark"); Identity::::add_registrar(registrar_origin, caller_lookup)?; - let fields = - IdentityFields( - IdentityField::Display | - IdentityField::Legal | IdentityField::Web | - IdentityField::Riot | IdentityField::Email | - IdentityField::PgpFingerprint | - IdentityField::Image | IdentityField::Twitter, - ); + let fields = IdentityFields( + ::IdentityField::all(), + ); let registrars = Registrars::::get(); ensure!( @@ -431,7 +407,7 @@ mod benchmarks { add_registrars::(r)?; - let info = create_identity_info::(x); + let info = T::IdentityInformation::create_identity_info(x); let info_hash = T::Hashing::hash_of(&info); Identity::::set_identity(user_origin.clone(), Box::new(info))?; @@ -464,7 +440,7 @@ mod benchmarks { let target_lookup = T::Lookup::unlookup(target.clone()); let _ = T::Currency::make_free_balance_be(&target, BalanceOf::::max_value()); - let info = create_identity_info::(x); + let info = T::IdentityInformation::create_identity_info(x); Identity::::set_identity(target_origin.clone(), Box::new(info.clone()))?; let _ = add_sub_accounts::(&target, s)?; diff --git a/substrate/frame/identity/src/lib.rs b/substrate/frame/identity/src/lib.rs index f192ee2b461b3..a341cc6bb9bda 100644 --- a/substrate/frame/identity/src/lib.rs +++ b/substrate/frame/identity/src/lib.rs @@ -73,6 +73,7 @@ #![cfg_attr(not(feature = "std"), no_std)] mod benchmarking; +pub mod simple; #[cfg(test)] mod tests; mod types; @@ -85,7 +86,7 @@ pub use weights::WeightInfo; pub use pallet::*; pub use types::{ - Data, IdentityField, IdentityFields, IdentityInfo, Judgement, RegistrarIndex, RegistrarInfo, + Data, IdentityFields, IdentityInformationProvider, Judgement, RegistrarIndex, RegistrarInfo, Registration, }; @@ -133,6 +134,9 @@ pub mod pallet { #[pallet::constant] type MaxAdditionalFields: Get; + /// Structure holding information about an identity. + type IdentityInformation: IdentityInformationProvider; + /// Maxmimum number of registrars allowed in the system. Needed to bound the complexity /// of, e.g., updating judgements. #[pallet::constant] @@ -163,7 +167,7 @@ pub mod pallet { _, Twox64Concat, T::AccountId, - Registration, T::MaxRegistrars, T::MaxAdditionalFields>, + Registration, T::MaxRegistrars, T::IdentityInformation>, OptionQuery, >; @@ -197,7 +201,16 @@ pub mod pallet { #[pallet::getter(fn registrars)] pub(super) type Registrars = StorageValue< _, - BoundedVec, T::AccountId>>, T::MaxRegistrars>, + BoundedVec< + Option< + RegistrarInfo< + BalanceOf, + T::AccountId, + ::IdentityField, + >, + >, + T::MaxRegistrars, + >, ValueQuery, >; @@ -277,9 +290,6 @@ pub mod pallet { /// - `account`: the account of the registrar. /// /// Emits `RegistrarAdded` if successful. - /// - /// ## Complexity - /// - `O(R)` where `R` registrar-count (governance-bounded and code-bounded). #[pallet::call_index(0)] #[pallet::weight(T::WeightInfo::add_registrar(T::MaxRegistrars::get()))] pub fn add_registrar( @@ -317,22 +327,18 @@ pub mod pallet { /// - `info`: The identity information. /// /// Emits `IdentitySet` if successful. - /// - /// ## Complexity - /// - `O(X + X' + R)` - /// - where `X` additional-field-count (deposit-bounded and code-bounded) - /// - where `R` judgements-count (registrar-count-bounded) #[pallet::call_index(1)] - #[pallet::weight( T::WeightInfo::set_identity( - T::MaxRegistrars::get(), // R - T::MaxAdditionalFields::get(), // X + #[pallet::weight(T::WeightInfo::set_identity( + T::MaxRegistrars::get(), + T::MaxAdditionalFields::get(), ))] pub fn set_identity( origin: OriginFor, - info: Box>, + info: Box, ) -> DispatchResultWithPostInfo { let sender = ensure_signed(origin)?; - let extra_fields = info.additional.len() as u32; + #[allow(deprecated)] + let extra_fields = info.additional() as u32; ensure!(extra_fields <= T::MaxAdditionalFields::get(), Error::::TooManyFields); let fd = >::from(extra_fields) * T::FieldDeposit::get(); @@ -364,11 +370,7 @@ pub mod pallet { >::insert(&sender, id); Self::deposit_event(Event::IdentitySet { who: sender }); - Ok(Some(T::WeightInfo::set_identity( - judgements as u32, // R - extra_fields, // X - )) - .into()) + Ok(Some(T::WeightInfo::set_identity(judgements as u32, extra_fields)).into()) } /// Set the sub-accounts of the sender. @@ -380,11 +382,6 @@ pub mod pallet { /// identity. /// /// - `subs`: The identity's (new) sub-accounts. - /// - /// ## Complexity - /// - `O(P + S)` - /// - where `P` old-subs-count (hard- and deposit-bounded). - /// - where `S` subs-count (hard- and deposit-bounded). // TODO: This whole extrinsic screams "not optimized". For example we could // filter any overlap between new and old subs, and avoid reading/writing // to those values... We could also ideally avoid needing to write to @@ -392,8 +389,8 @@ pub mod pallet { // is a large overestimate due to the fact that it could potentially write // to 2 x T::MaxSubAccounts::get(). #[pallet::call_index(2)] - #[pallet::weight(T::WeightInfo::set_subs_old(T::MaxSubAccounts::get()) // P: Assume max sub accounts removed. - .saturating_add(T::WeightInfo::set_subs_new(subs.len() as u32)) // S: Assume all subs are new. + #[pallet::weight(T::WeightInfo::set_subs_old(T::MaxSubAccounts::get()) + .saturating_add(T::WeightInfo::set_subs_new(subs.len() as u32)) )] pub fn set_subs( origin: OriginFor, @@ -453,17 +450,11 @@ pub mod pallet { /// identity. /// /// Emits `IdentityCleared` if successful. - /// - /// ## Complexity - /// - `O(R + S + X)` - /// - where `R` registrar-count (governance-bounded). - /// - where `S` subs-count (hard- and deposit-bounded). - /// - where `X` additional-field-count (deposit-bounded and code-bounded). #[pallet::call_index(3)] #[pallet::weight(T::WeightInfo::clear_identity( - T::MaxRegistrars::get(), // R - T::MaxSubAccounts::get(), // S - T::MaxAdditionalFields::get(), // X + T::MaxRegistrars::get(), + T::MaxSubAccounts::get(), + T::MaxAdditionalFields::get(), ))] pub fn clear_identity(origin: OriginFor) -> DispatchResultWithPostInfo { let sender = ensure_signed(origin)?; @@ -480,10 +471,11 @@ pub mod pallet { Self::deposit_event(Event::IdentityCleared { who: sender, deposit }); + #[allow(deprecated)] Ok(Some(T::WeightInfo::clear_identity( - id.judgements.len() as u32, // R - sub_ids.len() as u32, // S - id.info.additional.len() as u32, // X + id.judgements.len() as u32, + sub_ids.len() as u32, + id.info.additional() as u32, )) .into()) } @@ -504,15 +496,10 @@ pub mod pallet { /// ``` /// /// Emits `JudgementRequested` if successful. - /// - /// ## Complexity - /// - `O(R + X)`. - /// - where `R` registrar-count (governance-bounded). - /// - where `X` additional-field-count (deposit-bounded and code-bounded). #[pallet::call_index(4)] #[pallet::weight(T::WeightInfo::request_judgement( - T::MaxRegistrars::get(), // R - T::MaxAdditionalFields::get(), // X + T::MaxRegistrars::get(), + T::MaxAdditionalFields::get(), ))] pub fn request_judgement( origin: OriginFor, @@ -543,7 +530,8 @@ pub mod pallet { T::Currency::reserve(&sender, registrar.fee)?; let judgements = id.judgements.len(); - let extra_fields = id.info.additional.len(); + #[allow(deprecated)] + let extra_fields = id.info.additional(); >::insert(&sender, id); Self::deposit_event(Event::JudgementRequested { @@ -565,15 +553,10 @@ pub mod pallet { /// - `reg_index`: The index of the registrar whose judgement is no longer requested. /// /// Emits `JudgementUnrequested` if successful. - /// - /// ## Complexity - /// - `O(R + X)`. - /// - where `R` registrar-count (governance-bounded). - /// - where `X` additional-field-count (deposit-bounded and code-bounded). #[pallet::call_index(5)] #[pallet::weight(T::WeightInfo::cancel_request( - T::MaxRegistrars::get(), // R - T::MaxAdditionalFields::get(), // X + T::MaxRegistrars::get(), + T::MaxAdditionalFields::get(), ))] pub fn cancel_request( origin: OriginFor, @@ -595,7 +578,8 @@ pub mod pallet { let err_amount = T::Currency::unreserve(&sender, fee); debug_assert!(err_amount.is_zero()); let judgements = id.judgements.len(); - let extra_fields = id.info.additional.len(); + #[allow(deprecated)] + let extra_fields = id.info.additional(); >::insert(&sender, id); Self::deposit_event(Event::JudgementUnrequested { @@ -613,12 +597,8 @@ pub mod pallet { /// /// - `index`: the index of the registrar whose fee is to be set. /// - `fee`: the new fee. - /// - /// ## Complexity - /// - `O(R)`. - /// - where `R` registrar-count (governance-bounded). #[pallet::call_index(6)] - #[pallet::weight(T::WeightInfo::set_fee(T::MaxRegistrars::get()))] // R + #[pallet::weight(T::WeightInfo::set_fee(T::MaxRegistrars::get()))] pub fn set_fee( origin: OriginFor, #[pallet::compact] index: RegistrarIndex, @@ -640,7 +620,7 @@ pub mod pallet { .ok_or_else(|| DispatchError::from(Error::::InvalidIndex))?; Ok(rs.len()) })?; - Ok(Some(T::WeightInfo::set_fee(registrars as u32)).into()) // R + Ok(Some(T::WeightInfo::set_fee(registrars as u32)).into()) } /// Change the account associated with a registrar. @@ -650,12 +630,8 @@ pub mod pallet { /// /// - `index`: the index of the registrar whose fee is to be set. /// - `new`: the new account ID. - /// - /// ## Complexity - /// - `O(R)`. - /// - where `R` registrar-count (governance-bounded). #[pallet::call_index(7)] - #[pallet::weight(T::WeightInfo::set_account_id(T::MaxRegistrars::get()))] // R + #[pallet::weight(T::WeightInfo::set_account_id(T::MaxRegistrars::get()))] pub fn set_account_id( origin: OriginFor, #[pallet::compact] index: RegistrarIndex, @@ -678,7 +654,7 @@ pub mod pallet { .ok_or_else(|| DispatchError::from(Error::::InvalidIndex))?; Ok(rs.len()) })?; - Ok(Some(T::WeightInfo::set_account_id(registrars as u32)).into()) // R + Ok(Some(T::WeightInfo::set_account_id(registrars as u32)).into()) } /// Set the field information for a registrar. @@ -688,16 +664,14 @@ pub mod pallet { /// /// - `index`: the index of the registrar whose fee is to be set. /// - `fields`: the fields that the registrar concerns themselves with. - /// - /// ## Complexity - /// - `O(R)`. - /// - where `R` registrar-count (governance-bounded). #[pallet::call_index(8)] - #[pallet::weight(T::WeightInfo::set_fields(T::MaxRegistrars::get()))] // R + #[pallet::weight(T::WeightInfo::set_fields(T::MaxRegistrars::get()))] pub fn set_fields( origin: OriginFor, #[pallet::compact] index: RegistrarIndex, - fields: IdentityFields, + fields: IdentityFields< + ::IdentityField, + >, ) -> DispatchResultWithPostInfo { let who = ensure_signed(origin)?; @@ -715,10 +689,7 @@ pub mod pallet { .ok_or_else(|| DispatchError::from(Error::::InvalidIndex))?; Ok(rs.len()) })?; - Ok(Some(T::WeightInfo::set_fields( - registrars as u32, // R - )) - .into()) + Ok(Some(T::WeightInfo::set_fields(registrars as u32)).into()) } /// Provide a judgement for an account's identity. @@ -730,18 +701,14 @@ pub mod pallet { /// - `target`: the account whose identity the judgement is upon. This must be an account /// with a registered identity. /// - `judgement`: the judgement of the registrar of index `reg_index` about `target`. - /// - `identity`: The hash of the [`IdentityInfo`] for that the judgement is provided. + /// - `identity`: The hash of the [`IdentityInformationProvider`] for that the judgement is + /// provided. /// /// Emits `JudgementGiven` if successful. - /// - /// ## Complexity - /// - `O(R + X)`. - /// - where `R` registrar-count (governance-bounded). - /// - where `X` additional-field-count (deposit-bounded and code-bounded). #[pallet::call_index(9)] #[pallet::weight(T::WeightInfo::provide_judgement( - T::MaxRegistrars::get(), // R - T::MaxAdditionalFields::get(), // X + T::MaxRegistrars::get(), + T::MaxAdditionalFields::get(), ))] pub fn provide_judgement( origin: OriginFor, @@ -785,7 +752,8 @@ pub mod pallet { } let judgements = id.judgements.len(); - let extra_fields = id.info.additional.len(); + #[allow(deprecated)] + let extra_fields = id.info.additional(); >::insert(&target, id); Self::deposit_event(Event::JudgementGiven { target, registrar_index: reg_index }); @@ -805,17 +773,11 @@ pub mod pallet { /// with a registered identity. /// /// Emits `IdentityKilled` if successful. - /// - /// ## Complexity - /// - `O(R + S + X)` - /// - where `R` registrar-count (governance-bounded). - /// - where `S` subs-count (hard- and deposit-bounded). - /// - where `X` additional-field-count (deposit-bounded and code-bounded). #[pallet::call_index(10)] #[pallet::weight(T::WeightInfo::kill_identity( - T::MaxRegistrars::get(), // R - T::MaxSubAccounts::get(), // S - T::MaxAdditionalFields::get(), // X + T::MaxRegistrars::get(), + T::MaxSubAccounts::get(), + T::MaxAdditionalFields::get(), ))] pub fn kill_identity( origin: OriginFor, @@ -837,10 +799,11 @@ pub mod pallet { Self::deposit_event(Event::IdentityKilled { who: target, deposit }); + #[allow(deprecated)] Ok(Some(T::WeightInfo::kill_identity( - id.judgements.len() as u32, // R - sub_ids.len() as u32, // S - id.info.additional.len() as u32, // X + id.judgements.len() as u32, + sub_ids.len() as u32, + id.info.additional() as u32, )) .into()) } @@ -975,6 +938,6 @@ impl Pallet { /// Check if the account has corresponding identity information by the identity field. pub fn has_identity(who: &T::AccountId, fields: u64) -> bool { IdentityOf::::get(who) - .map_or(false, |registration| (registration.info.fields().0.bits() & fields) == fields) + .map_or(false, |registration| (registration.info.has_identity(fields))) } } diff --git a/substrate/frame/identity/src/simple.rs b/substrate/frame/identity/src/simple.rs new file mode 100644 index 0000000000000..db5ecf3b1c97e --- /dev/null +++ b/substrate/frame/identity/src/simple.rs @@ -0,0 +1,185 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use codec::{Decode, Encode, MaxEncodedLen}; +use enumflags2::{bitflags, BitFlags}; +use frame_support::{traits::Get, CloneNoBound, EqNoBound, PartialEqNoBound, RuntimeDebugNoBound}; +use scale_info::{build::Variants, Path, Type, TypeInfo}; +use sp_runtime::{BoundedVec, RuntimeDebug}; +use sp_std::prelude::*; + +use crate::types::{Data, IdentityFields, IdentityInformationProvider, U64BitFlag}; + +/// The fields that we use to identify the owner of an account with. Each corresponds to a field +/// in the `IdentityInfo` struct. +#[bitflags] +#[repr(u64)] +#[derive(Clone, Copy, PartialEq, Eq, RuntimeDebug)] +pub enum IdentityField { + Display, + Legal, + Web, + Riot, + Email, + PgpFingerprint, + Image, + Twitter, +} + +impl TypeInfo for IdentityField { + type Identity = Self; + + fn type_info() -> scale_info::Type { + Type::builder().path(Path::new("IdentityField", module_path!())).variant( + Variants::new() + .variant("Display", |v| v.index(0)) + .variant("Legal", |v| v.index(1)) + .variant("Web", |v| v.index(2)) + .variant("Riot", |v| v.index(3)) + .variant("Email", |v| v.index(4)) + .variant("PgpFingerprint", |v| v.index(5)) + .variant("Image", |v| v.index(6)) + .variant("Twitter", |v| v.index(7)), + ) + } +} + +impl U64BitFlag for IdentityField {} + +/// Information concerning the identity of the controller of an account. +/// +/// NOTE: This should be stored at the end of the storage item to facilitate the addition of extra +/// fields in a backwards compatible way through a specialized `Decode` impl. +#[derive( + CloneNoBound, + Encode, + Decode, + EqNoBound, + MaxEncodedLen, + PartialEqNoBound, + RuntimeDebugNoBound, + TypeInfo, +)] +#[codec(mel_bound())] +#[cfg_attr(test, derive(frame_support::DefaultNoBound))] +#[scale_info(skip_type_params(FieldLimit))] +pub struct IdentityInfo> { + /// Additional fields of the identity that are not catered for with the struct's explicit + /// fields. + pub additional: BoundedVec<(Data, Data), FieldLimit>, + + /// A reasonable display name for the controller of the account. This should be whatever it is + /// that it is typically known as and should not be confusable with other entities, given + /// reasonable context. + /// + /// Stored as UTF-8. + pub display: Data, + + /// The full legal name in the local jurisdiction of the entity. This might be a bit + /// long-winded. + /// + /// Stored as UTF-8. + pub legal: Data, + + /// A representative website held by the controller of the account. + /// + /// NOTE: `https://` is automatically prepended. + /// + /// Stored as UTF-8. + pub web: Data, + + /// The Riot/Matrix handle held by the controller of the account. + /// + /// Stored as UTF-8. + pub riot: Data, + + /// The email address of the controller of the account. + /// + /// Stored as UTF-8. + pub email: Data, + + /// The PGP/GPG public key of the controller of the account. + pub pgp_fingerprint: Option<[u8; 20]>, + + /// A graphic image representing the controller of the account. Should be a company, + /// organization or project logo or a headshot in the case of a human. + pub image: Data, + + /// The Twitter identity. The leading `@` character may be elided. + pub twitter: Data, +} + +impl + 'static> IdentityInformationProvider for IdentityInfo { + type IdentityField = IdentityField; + + fn has_identity(&self, fields: u64) -> bool { + self.fields().0.bits() & fields == fields + } + + fn additional(&self) -> usize { + self.additional.len() + } + + #[cfg(feature = "runtime-benchmarks")] + fn create_identity_info(num_fields: u32) -> Self { + let data = Data::Raw(vec![0; 32].try_into().unwrap()); + + IdentityInfo { + additional: vec![(data.clone(), data.clone()); num_fields as usize].try_into().unwrap(), + display: data.clone(), + legal: data.clone(), + web: data.clone(), + riot: data.clone(), + email: data.clone(), + pgp_fingerprint: Some([0; 20]), + image: data.clone(), + twitter: data, + } + } +} + +impl> IdentityInfo { + #[allow(unused)] + pub(crate) fn fields(&self) -> IdentityFields { + let mut res = >::empty(); + if !self.display.is_none() { + res.insert(IdentityField::Display); + } + if !self.legal.is_none() { + res.insert(IdentityField::Legal); + } + if !self.web.is_none() { + res.insert(IdentityField::Web); + } + if !self.riot.is_none() { + res.insert(IdentityField::Riot); + } + if !self.email.is_none() { + res.insert(IdentityField::Email); + } + if self.pgp_fingerprint.is_some() { + res.insert(IdentityField::PgpFingerprint); + } + if !self.image.is_none() { + res.insert(IdentityField::Image); + } + if !self.twitter.is_none() { + res.insert(IdentityField::Twitter); + } + IdentityFields(res) + } +} diff --git a/substrate/frame/identity/src/tests.rs b/substrate/frame/identity/src/tests.rs index 6bfd15b4aaeef..f0980e9c7cc89 100644 --- a/substrate/frame/identity/src/tests.rs +++ b/substrate/frame/identity/src/tests.rs @@ -18,7 +18,10 @@ // Tests for Identity Pallet use super::*; -use crate as pallet_identity; +use crate::{ + self as pallet_identity, + simple::{IdentityField as SimpleIdentityField, IdentityInfo}, +}; use codec::{Decode, Encode}; use frame_support::{ @@ -107,6 +110,7 @@ impl pallet_identity::Config for Test { type SubAccountDeposit = ConstU64<10>; type MaxSubAccounts = ConstU32<2>; type MaxAdditionalFields = MaxAdditionalFields; + type IdentityInformation = IdentityInfo; type MaxRegistrars = MaxRegistrars; type RegistrarOrigin = EnsureOneOrRoot; type ForceOrigin = EnsureTwoOrRoot; @@ -139,6 +143,43 @@ fn twenty() -> IdentityInfo { } } +#[test] +fn identity_fields_repr_works() { + // `SimpleIdentityField` sanity checks. + assert_eq!(SimpleIdentityField::Display as u64, 1 << 0); + assert_eq!(SimpleIdentityField::Legal as u64, 1 << 1); + assert_eq!(SimpleIdentityField::Web as u64, 1 << 2); + assert_eq!(SimpleIdentityField::Riot as u64, 1 << 3); + assert_eq!(SimpleIdentityField::Email as u64, 1 << 4); + assert_eq!(SimpleIdentityField::PgpFingerprint as u64, 1 << 5); + assert_eq!(SimpleIdentityField::Image as u64, 1 << 6); + assert_eq!(SimpleIdentityField::Twitter as u64, 1 << 7); + + let fields = IdentityFields( + SimpleIdentityField::Legal | + SimpleIdentityField::Web | + SimpleIdentityField::Riot | + SimpleIdentityField::PgpFingerprint | + SimpleIdentityField::Twitter, + ); + + assert!(!fields.0.contains(SimpleIdentityField::Display)); + assert!(fields.0.contains(SimpleIdentityField::Legal)); + assert!(fields.0.contains(SimpleIdentityField::Web)); + assert!(fields.0.contains(SimpleIdentityField::Riot)); + assert!(!fields.0.contains(SimpleIdentityField::Email)); + assert!(fields.0.contains(SimpleIdentityField::PgpFingerprint)); + assert!(!fields.0.contains(SimpleIdentityField::Image)); + assert!(fields.0.contains(SimpleIdentityField::Twitter)); + + // The `IdentityFields` inner `BitFlags::bits` is used for `Encode`/`Decode`, so we ensure that + // the `u64` representation matches what we expect during encode/decode operations. + assert_eq!( + fields.0.bits(), + 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_10101110 + ); +} + #[test] fn editing_subaccounts_should_work() { new_test_ext().execute_with(|| { @@ -233,7 +274,7 @@ fn adding_registrar_should_work() { new_test_ext().execute_with(|| { assert_ok!(Identity::add_registrar(RuntimeOrigin::signed(1), 3)); assert_ok!(Identity::set_fee(RuntimeOrigin::signed(3), 0, 10)); - let fields = IdentityFields(IdentityField::Display | IdentityField::Legal); + let fields = IdentityFields(SimpleIdentityField::Display | SimpleIdentityField::Legal); assert_ok!(Identity::set_fields(RuntimeOrigin::signed(3), 0, fields)); assert_eq!( Identity::registrars(), @@ -608,15 +649,17 @@ fn setting_account_id_should_work() { fn test_has_identity() { new_test_ext().execute_with(|| { assert_ok!(Identity::set_identity(RuntimeOrigin::signed(10), Box::new(ten()))); - assert!(Identity::has_identity(&10, IdentityField::Display as u64)); - assert!(Identity::has_identity(&10, IdentityField::Legal as u64)); + assert!(Identity::has_identity(&10, SimpleIdentityField::Display as u64)); + assert!(Identity::has_identity(&10, SimpleIdentityField::Legal as u64)); assert!(Identity::has_identity( &10, - IdentityField::Display as u64 | IdentityField::Legal as u64 + SimpleIdentityField::Display as u64 | SimpleIdentityField::Legal as u64 )); assert!(!Identity::has_identity( &10, - IdentityField::Display as u64 | IdentityField::Legal as u64 | IdentityField::Web as u64 + SimpleIdentityField::Display as u64 | + SimpleIdentityField::Legal as u64 | + SimpleIdentityField::Web as u64 )); }); } diff --git a/substrate/frame/identity/src/types.rs b/substrate/frame/identity/src/types.rs index 1837b30b027f9..7055f6d80cfb5 100644 --- a/substrate/frame/identity/src/types.rs +++ b/substrate/frame/identity/src/types.rs @@ -17,7 +17,7 @@ use super::*; use codec::{Decode, Encode, MaxEncodedLen}; -use enumflags2::{bitflags, BitFlags}; +use enumflags2::{BitFlag, BitFlags, _internal::RawBitFlags}; use frame_support::{ traits::{ConstU32, Get}, BoundedVec, CloneNoBound, PartialEqNoBound, RuntimeDebugNoBound, @@ -29,6 +29,11 @@ use scale_info::{ use sp_runtime::{traits::Zero, RuntimeDebug}; use sp_std::{fmt::Debug, iter::once, ops::Add, prelude::*}; +/// An identifier for a single name registrar/identity verification service. +pub type RegistrarIndex = u32; + +pub trait U64BitFlag: BitFlag + RawBitFlags {} + /// Either underlying data blob if it is at most 32 bytes, or a hash of it. If the data is greater /// than 32-bytes then it will be truncated when encoding. /// @@ -180,9 +185,6 @@ impl Default for Data { } } -/// An identifier for a single name registrar/identity verification service. -pub type RegistrarIndex = u32; - /// An attestation of a registrar over how accurate some `IdentityInfo` is in describing an account. /// /// NOTE: Registrars may pay little attention to some fields. Registrars may want to make clear @@ -228,143 +230,31 @@ impl` that implements `Codec`. -#[derive(Clone, Copy, PartialEq, Default, RuntimeDebug)] -pub struct IdentityFields(pub BitFlags); - -impl MaxEncodedLen for IdentityFields { - fn max_encoded_len() -> usize { - u64::max_encoded_len() - } -} - -impl Eq for IdentityFields {} -impl Encode for IdentityFields { - fn using_encoded R>(&self, f: F) -> R { - self.0.bits().using_encoded(f) - } -} -impl Decode for IdentityFields { - fn decode(input: &mut I) -> sp_std::result::Result { - let field = u64::decode(input)?; - Ok(Self(>::from_bits(field as u64).map_err(|_| "invalid value")?)) - } -} -impl TypeInfo for IdentityFields { - type Identity = Self; - - fn type_info() -> Type { - Type::builder() - .path(Path::new("BitFlags", module_path!())) - .type_params(vec![TypeParameter::new("T", Some(meta_type::()))]) - .composite(Fields::unnamed().field(|f| f.ty::().type_name("IdentityField"))) - } -} - /// Information concerning the identity of the controller of an account. -/// -/// NOTE: This should be stored at the end of the storage item to facilitate the addition of extra -/// fields in a backwards compatible way through a specialized `Decode` impl. -#[derive( - CloneNoBound, Encode, Decode, Eq, MaxEncodedLen, PartialEqNoBound, RuntimeDebugNoBound, TypeInfo, -)] -#[codec(mel_bound())] -#[cfg_attr(test, derive(frame_support::DefaultNoBound))] -#[scale_info(skip_type_params(FieldLimit))] -pub struct IdentityInfo> { - /// Additional fields of the identity that are not catered for with the struct's explicit - /// fields. - pub additional: BoundedVec<(Data, Data), FieldLimit>, - - /// A reasonable display name for the controller of the account. This should be whatever it is - /// that it is typically known as and should not be confusable with other entities, given - /// reasonable context. - /// - /// Stored as UTF-8. - pub display: Data, - - /// The full legal name in the local jurisdiction of the entity. This might be a bit - /// long-winded. - /// - /// Stored as UTF-8. - pub legal: Data, - - /// A representative website held by the controller of the account. - /// - /// NOTE: `https://` is automatically prepended. - /// - /// Stored as UTF-8. - pub web: Data, - - /// The Riot/Matrix handle held by the controller of the account. - /// - /// Stored as UTF-8. - pub riot: Data, - - /// The email address of the controller of the account. - /// - /// Stored as UTF-8. - pub email: Data, - - /// The PGP/GPG public key of the controller of the account. - pub pgp_fingerprint: Option<[u8; 20]>, - - /// A graphic image representing the controller of the account. Should be a company, - /// organization or project logo or a headshot in the case of a human. - pub image: Data, - - /// The Twitter identity. The leading `@` character may be elided. - pub twitter: Data, -} - -impl> IdentityInfo { - pub(crate) fn fields(&self) -> IdentityFields { - let mut res = >::empty(); - if !self.display.is_none() { - res.insert(IdentityField::Display); - } - if !self.legal.is_none() { - res.insert(IdentityField::Legal); - } - if !self.web.is_none() { - res.insert(IdentityField::Web); - } - if !self.riot.is_none() { - res.insert(IdentityField::Riot); - } - if !self.email.is_none() { - res.insert(IdentityField::Email); - } - if self.pgp_fingerprint.is_some() { - res.insert(IdentityField::PgpFingerprint); - } - if !self.image.is_none() { - res.insert(IdentityField::Image); - } - if !self.twitter.is_none() { - res.insert(IdentityField::Twitter); - } - IdentityFields(res) +pub trait IdentityInformationProvider: + Encode + Decode + MaxEncodedLen + Clone + Debug + Eq + PartialEq + TypeInfo +{ + /// Type capable of representing all of the fields present in the identity information as bit + /// flags in `u64` format. + type IdentityField: Clone + Debug + Eq + PartialEq + TypeInfo + U64BitFlag; + + /// Check if an identity registered information for some given `fields`. + fn has_identity(&self, fields: u64) -> bool; + + /// Interface for providing the number of additional fields this identity information provider + /// holds, used to charge for additional storage and weight. This interface is present for + /// backwards compatibility reasons only and will be removed as soon as the reference identity + /// provider removes additional fields. + #[deprecated] + fn additional(&self) -> usize { + 0 } + + #[cfg(feature = "runtime-benchmarks")] + fn create_identity_info(num_fields: u32) -> Self; } -/// Information concerning the identity of the controller of an account. +/// Information on an identity along with judgements from registrars. /// /// NOTE: This is stored separately primarily to facilitate the addition of extra fields in a /// backwards compatible way through a specialized `Decode` impl. @@ -376,7 +266,7 @@ impl> IdentityInfo { pub struct Registration< Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq, MaxJudgements: Get, - MaxAdditionalFields: Get, + IdentityInfo: IdentityInformationProvider, > { /// Judgements from the registrars on this identity. Stored ordered by `RegistrarIndex`. There /// may be only a single judgement from each registrar. @@ -386,14 +276,14 @@ pub struct Registration< pub deposit: Balance, /// Information on the identity. - pub info: IdentityInfo, + pub info: IdentityInfo, } impl< Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq + Zero + Add, MaxJudgements: Get, - MaxAdditionalFields: Get, - > Registration + IdentityInfo: IdentityInformationProvider, + > Registration { pub(crate) fn total_deposit(&self) -> Balance { self.deposit + @@ -407,8 +297,8 @@ impl< impl< Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq, MaxJudgements: Get, - MaxAdditionalFields: Get, - > Decode for Registration + IdentityInfo: IdentityInformationProvider, + > Decode for Registration { fn decode(input: &mut I) -> sp_std::result::Result { let (judgements, deposit, info) = Decode::decode(&mut AppendZerosInput::new(input))?; @@ -421,6 +311,7 @@ impl< pub struct RegistrarInfo< Balance: Encode + Decode + Clone + Debug + Eq + PartialEq, AccountId: Encode + Decode + Clone + Debug + Eq + PartialEq, + IdField: Clone + Debug + Eq + PartialEq + TypeInfo + U64BitFlag, > { /// The account of the registrar. pub account: AccountId, @@ -430,7 +321,52 @@ pub struct RegistrarInfo< /// Relevant fields for this registrar. Registrar judgements are limited to attestations on /// these fields. - pub fields: IdentityFields, + pub fields: IdentityFields, +} + +/// Wrapper type for `BitFlags` that implements `Codec`. +#[derive(Clone, Copy, PartialEq, RuntimeDebug)] +pub struct IdentityFields(pub BitFlags); + +impl Default for IdentityFields { + fn default() -> Self { + Self(Default::default()) + } +} + +impl MaxEncodedLen for IdentityFields +where + IdentityFields: Encode, +{ + fn max_encoded_len() -> usize { + u64::max_encoded_len() + } +} + +impl Eq for IdentityFields {} +impl Encode for IdentityFields { + fn using_encoded R>(&self, f: F) -> R { + let bits: u64 = self.0.bits(); + bits.using_encoded(f) + } +} +impl Decode for IdentityFields { + fn decode(input: &mut I) -> sp_std::result::Result { + let field = u64::decode(input)?; + Ok(Self(>::from_bits(field).map_err(|_| "invalid value")?)) + } +} +impl TypeInfo + for IdentityFields +{ + type Identity = Self; + + fn type_info() -> Type { + Type::builder() + .path(Path::new("BitFlags", module_path!())) + .type_params(vec![TypeParameter::new("T", Some(meta_type::()))]) + .composite(Fields::unnamed().field(|f| f.ty::().type_name("IdentityField"))) + } } #[cfg(test)]