difftreelog
Merge remote-tracking branch 'origin/feat/set-sub-identities' into develop
in: master
6 files changed
Makefilediffbeforeafterboth--- a/Makefile
+++ b/Makefile
@@ -146,5 +146,5 @@
make _bench PALLET=app-promotion PALLET_DIR=app-promotion
.PHONY: bench
-# Disabled: bench-scheduler, bench-collator-selection, bench-rmrk-core, bench-rmrk-equip
-bench: bench-evm-migration bench-unique bench-structure bench-fungible bench-refungible bench-nonfungible bench-configuration bench-foreign-assets bench-identity
+# Disabled: bench-scheduler, bench-collator-selection, bench-identity, bench-rmrk-core, bench-rmrk-equip
+bench: bench-evm-migration bench-unique bench-structure bench-fungible bench-refungible bench-nonfungible bench-configuration bench-foreign-assets
pallets/identity/src/benchmarking.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// Original license:18// This file is part of Substrate.1920// Copyright (C) 2020-2022 Parity Technologies (UK) Ltd.21// SPDX-License-Identifier: Apache-2.02223// Licensed under the Apache License, Version 2.0 (the "License");24// you may not use this file except in compliance with the License.25// You may obtain a copy of the License at26//27// http://www.apache.org/licenses/LICENSE-2.028//29// Unless required by applicable law or agreed to in writing, software30// distributed under the License is distributed on an "AS IS" BASIS,31// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.32// See the License for the specific language governing permissions and33// limitations under the License.3435//! Identity pallet benchmarking.3637#![cfg(feature = "runtime-benchmarks")]3839use super::*;4041use crate::Pallet as Identity;42use frame_benchmarking::{account, benchmarks, whitelisted_caller};43use frame_support::{44 ensure, assert_ok,45 traits::{EnsureOrigin, Get},46};47use frame_system::RawOrigin;48use sp_runtime::traits::Bounded;4950const SEED: u32 = 0;5152fn assert_last_event<T: Config>(generic_event: <T as Config>::RuntimeEvent) {53 frame_system::Pallet::<T>::assert_last_event(generic_event.into());54}5556// Adds `r` registrars to the Identity Pallet. These registrars will have set fees and fields.57fn add_registrars<T: Config>(r: u32) -> Result<(), &'static str> {58 for i in 0..r {59 let registrar: T::AccountId = account("registrar", i, SEED);60 let registrar_lookup = T::Lookup::unlookup(registrar.clone());61 let _ = T::Currency::make_free_balance_be(®istrar, BalanceOf::<T>::max_value());62 let registrar_origin = T::RegistrarOrigin::successful_origin();63 Identity::<T>::add_registrar(registrar_origin, registrar_lookup)?;64 Identity::<T>::set_fee(RawOrigin::Signed(registrar.clone()).into(), i, 10u32.into())?;65 let fields = IdentityFields(66 IdentityField::Display67 | IdentityField::Legal68 | IdentityField::Web69 | IdentityField::Riot70 | IdentityField::Email71 | IdentityField::PgpFingerprint72 | IdentityField::Image73 | IdentityField::Twitter,74 );75 Identity::<T>::set_fields(RawOrigin::Signed(registrar.clone()).into(), i, fields)?;76 }7778 assert_eq!(Registrars::<T>::get().len(), r as usize);79 Ok(())80}8182// Create `s` sub-accounts for the identity of `who` and return them.83// Each will have 32 bytes of raw data added to it.84fn create_sub_accounts<T: Config>(85 who: &T::AccountId,86 s: u32,87) -> Result<Vec<(T::AccountId, Data)>, &'static str> {88 let mut subs = Vec::new();89 let who_origin = RawOrigin::Signed(who.clone());90 let data = Data::Raw(vec![0; 32].try_into().unwrap());9192 for i in 0..s {93 let sub_account = account("sub", i, SEED);94 subs.push((sub_account, data.clone()));95 }9697 // Set identity so `set_subs` does not fail.98 if IdentityOf::<T>::get(who).is_none() {99 let _ = T::Currency::make_free_balance_be(who, BalanceOf::<T>::max_value() / 2u32.into());100 let info = create_identity_info::<T>(1);101 Identity::<T>::set_identity(who_origin.into(), Box::new(info))?;102 }103104 Ok(subs)105}106107// Adds `s` sub-accounts to the identity of `who`. Each will have 32 bytes of raw data added to it.108// This additionally returns the vector of sub-accounts so it can be modified if needed.109fn add_sub_accounts<T: Config>(110 who: &T::AccountId,111 s: u32,112) -> Result<Vec<(T::AccountId, Data)>, &'static str> {113 let who_origin = RawOrigin::Signed(who.clone());114 let subs = create_sub_accounts::<T>(who, s)?;115116 Identity::<T>::set_subs(who_origin.into(), subs.clone())?;117118 Ok(subs)119}120121// This creates an `IdentityInfo` object with `num_fields` extra fields.122// All data is pre-populated with some arbitrary bytes.123fn create_identity_info<T: Config>(num_fields: u32) -> IdentityInfo<T::MaxAdditionalFields> {124 let data = Data::Raw(vec![0; 32].try_into().unwrap());125126 IdentityInfo {127 additional: vec![(data.clone(), data.clone()); num_fields as usize]128 .try_into()129 .unwrap(),130 display: data.clone(),131 legal: data.clone(),132 web: data.clone(),133 riot: data.clone(),134 email: data.clone(),135 pgp_fingerprint: Some([0; 20]),136 image: data.clone(),137 twitter: data,138 }139}140141benchmarks! {142 add_registrar {143 let r in 1 .. T::MaxRegistrars::get() - 1 => add_registrars::<T>(r)?;144 ensure!(Registrars::<T>::get().len() as u32 == r, "Registrars not set up correctly.");145 let origin = T::RegistrarOrigin::successful_origin();146 let account = T::Lookup::unlookup(account("registrar", r + 1, SEED));147 }: _<T::RuntimeOrigin>(origin, account)148 verify {149 ensure!(Registrars::<T>::get().len() as u32 == r + 1, "Registrars not added.");150 }151152 set_identity {153 let r in 1 .. T::MaxRegistrars::get() => add_registrars::<T>(r)?;154 let x in 0 .. T::MaxAdditionalFields::get();155 let caller = {156 // The target user157 let caller: T::AccountId = whitelisted_caller();158 let caller_lookup = T::Lookup::unlookup(caller.clone());159 let caller_origin: <T as frame_system::Config>::RuntimeOrigin = RawOrigin::Signed(caller.clone()).into();160 let _ = T::Currency::make_free_balance_be(&caller, BalanceOf::<T>::max_value());161162 // Add an initial identity163 let initial_info = create_identity_info::<T>(1);164 Identity::<T>::set_identity(caller_origin.clone(), Box::new(initial_info.clone()))?;165166 // User requests judgement from all the registrars, and they approve167 for i in 0..r {168 let registrar: T::AccountId = account("registrar", i, SEED);169 let registrar_lookup = T::Lookup::unlookup(registrar.clone());170 let balance_to_use = T::Currency::minimum_balance() * 10u32.into();171 let _ = T::Currency::make_free_balance_be(®istrar, balance_to_use);172173 Identity::<T>::request_judgement(caller_origin.clone(), i, 10u32.into())?;174 Identity::<T>::provide_judgement(175 RawOrigin::Signed(registrar).into(),176 i,177 caller_lookup.clone(),178 Judgement::Reasonable,179 T::Hashing::hash_of(&initial_info),180 )?;181 }182 caller183 };184 }: _(RawOrigin::Signed(caller.clone()), Box::new(create_identity_info::<T>(x)))185 verify {186 assert_last_event::<T>(Event::<T>::IdentitySet { who: caller }.into());187 }188189 // We need to split `set_subs` into two benchmarks to accurately isolate the potential190 // writes caused by new or old sub accounts. The actual weight should simply be191 // the sum of these two weights.192 set_subs_new {193 let caller: T::AccountId = whitelisted_caller();194 // Create a new subs vec with s sub accounts195 let s in 0 .. T::MaxSubAccounts::get() => ();196 let subs = create_sub_accounts::<T>(&caller, s)?;197 ensure!(SubsOf::<T>::get(&caller).1.len() == 0, "Caller already has subs");198 }: set_subs(RawOrigin::Signed(caller.clone()), subs)199 verify {200 ensure!(SubsOf::<T>::get(&caller).1.len() as u32 == s, "Subs not added");201 }202203 set_subs_old {204 let caller: T::AccountId = whitelisted_caller();205 // Give them p many previous sub accounts.206 let p in 0 .. T::MaxSubAccounts::get() => {207 let _ = add_sub_accounts::<T>(&caller, p)?;208 };209 // Remove all subs.210 let subs = create_sub_accounts::<T>(&caller, 0)?;211 ensure!(212 SubsOf::<T>::get(&caller).1.len() as u32 == p,213 "Caller does have subs",214 );215 }: set_subs(RawOrigin::Signed(caller.clone()), subs)216 verify {217 ensure!(SubsOf::<T>::get(&caller).1.len() == 0, "Subs not removed");218 }219220 clear_identity {221 let caller: T::AccountId = whitelisted_caller();222 let caller_origin = <T as frame_system::Config>::RuntimeOrigin::from(RawOrigin::Signed(caller.clone()));223 let caller_lookup = <T::Lookup as StaticLookup>::unlookup(caller.clone());224 let _ = T::Currency::make_free_balance_be(&caller, BalanceOf::<T>::max_value());225226 let r in 1 .. T::MaxRegistrars::get() => add_registrars::<T>(r)?;227 let s in 0 .. T::MaxSubAccounts::get() => {228 // Give them s many sub accounts229 let caller: T::AccountId = whitelisted_caller();230 let _ = add_sub_accounts::<T>(&caller, s)?;231 };232 let x in 0 .. T::MaxAdditionalFields::get();233234 // Create their main identity with x additional fields235 let info = create_identity_info::<T>(x);236 let caller: T::AccountId = whitelisted_caller();237 let caller_origin = <T as frame_system::Config>::RuntimeOrigin::from(RawOrigin::Signed(caller.clone()));238 Identity::<T>::set_identity(caller_origin.clone(), Box::new(info.clone()))?;239240 // User requests judgement from all the registrars, and they approve241 for i in 0..r {242 let registrar: T::AccountId = account("registrar", i, SEED);243 let balance_to_use = T::Currency::minimum_balance() * 10u32.into();244 let _ = T::Currency::make_free_balance_be(®istrar, balance_to_use);245246 Identity::<T>::request_judgement(caller_origin.clone(), i, 10u32.into())?;247 Identity::<T>::provide_judgement(248 RawOrigin::Signed(registrar).into(),249 i,250 caller_lookup.clone(),251 Judgement::Reasonable,252 T::Hashing::hash_of(&info),253 )?;254 }255 ensure!(IdentityOf::<T>::contains_key(&caller), "Identity does not exist.");256 }: _(RawOrigin::Signed(caller.clone()))257 verify {258 ensure!(!IdentityOf::<T>::contains_key(&caller), "Identity not cleared.");259 }260261 request_judgement {262 let caller: T::AccountId = whitelisted_caller();263 let _ = T::Currency::make_free_balance_be(&caller, BalanceOf::<T>::max_value());264265 let r in 1 .. T::MaxRegistrars::get() => add_registrars::<T>(r)?;266 let x in 0 .. T::MaxAdditionalFields::get() => {267 // Create their main identity with x additional fields268 let info = create_identity_info::<T>(x);269 let caller: T::AccountId = whitelisted_caller();270 let caller_origin = <T as frame_system::Config>::RuntimeOrigin::from(RawOrigin::Signed(caller));271 Identity::<T>::set_identity(caller_origin, Box::new(info))?;272 };273 }: _(RawOrigin::Signed(caller.clone()), r - 1, 10u32.into())274 verify {275 assert_last_event::<T>(Event::<T>::JudgementRequested { who: caller, registrar_index: r-1 }.into());276 }277278 cancel_request {279 let caller: T::AccountId = whitelisted_caller();280 let caller_origin = <T as frame_system::Config>::RuntimeOrigin::from(RawOrigin::Signed(caller.clone()));281 let _ = T::Currency::make_free_balance_be(&caller, BalanceOf::<T>::max_value());282283 let r in 1 .. T::MaxRegistrars::get() => add_registrars::<T>(r)?;284 let x in 0 .. T::MaxAdditionalFields::get() => {285 // Create their main identity with x additional fields286 let info = create_identity_info::<T>(x);287 let caller: T::AccountId = whitelisted_caller();288 let caller_origin = <T as frame_system::Config>::RuntimeOrigin::from(RawOrigin::Signed(caller));289 Identity::<T>::set_identity(caller_origin, Box::new(info))?;290 };291292 Identity::<T>::request_judgement(caller_origin, r - 1, 10u32.into())?;293 }: _(RawOrigin::Signed(caller.clone()), r - 1)294 verify {295 assert_last_event::<T>(Event::<T>::JudgementUnrequested { who: caller, registrar_index: r-1 }.into());296 }297298 set_fee {299 let caller: T::AccountId = whitelisted_caller();300 let caller_lookup = T::Lookup::unlookup(caller.clone());301302 let r in 1 .. T::MaxRegistrars::get() - 1 => add_registrars::<T>(r)?;303304 let registrar_origin = T::RegistrarOrigin::successful_origin();305 Identity::<T>::add_registrar(registrar_origin, caller_lookup)?;306 let registrars = Registrars::<T>::get();307 ensure!(registrars[r as usize].as_ref().unwrap().fee == 0u32.into(), "Fee already set.");308 }: _(RawOrigin::Signed(caller), r, 100u32.into())309 verify {310 let registrars = Registrars::<T>::get();311 ensure!(registrars[r as usize].as_ref().unwrap().fee == 100u32.into(), "Fee not changed.");312 }313314 set_account_id {315 let caller: T::AccountId = whitelisted_caller();316 let caller_lookup = T::Lookup::unlookup(caller.clone());317 let _ = T::Currency::make_free_balance_be(&caller, BalanceOf::<T>::max_value());318319 let r in 1 .. T::MaxRegistrars::get() - 1 => add_registrars::<T>(r)?;320321 let registrar_origin = T::RegistrarOrigin::successful_origin();322 Identity::<T>::add_registrar(registrar_origin, caller_lookup)?;323 let registrars = Registrars::<T>::get();324 ensure!(registrars[r as usize].as_ref().unwrap().account == caller, "id not set.");325 let new_account = T::Lookup::unlookup(account("new", 0, SEED));326 }: _(RawOrigin::Signed(caller), r, new_account)327 verify {328 let registrars = Registrars::<T>::get();329 ensure!(registrars[r as usize].as_ref().unwrap().account == account("new", 0, SEED), "id not changed.");330 }331332 set_fields {333 let caller: T::AccountId = whitelisted_caller();334 let caller_lookup = T::Lookup::unlookup(caller.clone());335 let _ = T::Currency::make_free_balance_be(&caller, BalanceOf::<T>::max_value());336337 let r in 1 .. T::MaxRegistrars::get() - 1 => add_registrars::<T>(r)?;338339 let registrar_origin = T::RegistrarOrigin::successful_origin();340 Identity::<T>::add_registrar(registrar_origin, caller_lookup)?;341 let fields = IdentityFields(342 IdentityField::Display | IdentityField::Legal | IdentityField::Web | IdentityField::Riot343 | IdentityField::Email | IdentityField::PgpFingerprint | IdentityField::Image | IdentityField::Twitter344 );345 let registrars = Registrars::<T>::get();346 ensure!(registrars[r as usize].as_ref().unwrap().fields == Default::default(), "fields already set.");347 }: _(RawOrigin::Signed(caller), r, fields)348 verify {349 let registrars = Registrars::<T>::get();350 ensure!(registrars[r as usize].as_ref().unwrap().fields != Default::default(), "fields not set.");351 }352353 provide_judgement {354 // The user355 let user: T::AccountId = account("user", r, SEED);356 let user_origin = <T as frame_system::Config>::RuntimeOrigin::from(RawOrigin::Signed(user.clone()));357 let user_lookup = <T::Lookup as StaticLookup>::unlookup(user.clone());358 let _ = T::Currency::make_free_balance_be(&user, BalanceOf::<T>::max_value());359360 let caller: T::AccountId = whitelisted_caller();361 let caller_lookup = T::Lookup::unlookup(caller.clone());362 let _ = T::Currency::make_free_balance_be(&caller, BalanceOf::<T>::max_value());363364 let r in 1 .. T::MaxRegistrars::get() - 1 => add_registrars::<T>(r)?;365 let x in 0 .. T::MaxAdditionalFields::get();366367 let info = create_identity_info::<T>(x);368 let info_hash = T::Hashing::hash_of(&info);369 Identity::<T>::set_identity(user_origin.clone(), Box::new(info))?;370371 let registrar_origin = T::RegistrarOrigin::successful_origin();372 Identity::<T>::add_registrar(registrar_origin, caller_lookup)?;373 Identity::<T>::request_judgement(user_origin, r, 10u32.into())?;374 }: _(RawOrigin::Signed(caller), r, user_lookup, Judgement::Reasonable, info_hash)375 verify {376 assert_last_event::<T>(Event::<T>::JudgementGiven { target: user, registrar_index: r }.into())377 }378379 kill_identity {380 let r in 1 .. T::MaxRegistrars::get() => add_registrars::<T>(r)?;381 let s in 0 .. T::MaxSubAccounts::get();382 let x in 0 .. T::MaxAdditionalFields::get();383384 let target: T::AccountId = account("target", 0, SEED);385 let target_origin: <T as frame_system::Config>::RuntimeOrigin = RawOrigin::Signed(target.clone()).into();386 let target_lookup = T::Lookup::unlookup(target.clone());387 let _ = T::Currency::make_free_balance_be(&target, BalanceOf::<T>::max_value());388389 let info = create_identity_info::<T>(x);390 Identity::<T>::set_identity(target_origin.clone(), Box::new(info.clone()))?;391 let _ = add_sub_accounts::<T>(&target, s)?;392393 // User requests judgement from all the registrars, and they approve394 for i in 0..r {395 let registrar: T::AccountId = account("registrar", i, SEED);396 let balance_to_use = T::Currency::minimum_balance() * 10u32.into();397 let _ = T::Currency::make_free_balance_be(®istrar, balance_to_use);398399 Identity::<T>::request_judgement(target_origin.clone(), i, 10u32.into())?;400 Identity::<T>::provide_judgement(401 RawOrigin::Signed(registrar).into(),402 i,403 target_lookup.clone(),404 Judgement::Reasonable,405 T::Hashing::hash_of(&info),406 )?;407 }408 ensure!(IdentityOf::<T>::contains_key(&target), "Identity not set");409 let origin = T::ForceOrigin::successful_origin();410 }: _<T::RuntimeOrigin>(origin, target_lookup)411 verify {412 ensure!(!IdentityOf::<T>::contains_key(&target), "Identity not removed");413 }414415 force_insert_identities {416 let x in 0 .. T::MaxAdditionalFields::get();417 let n in 0..600;418 use frame_benchmarking::account;419 let identities = (0..n).map(|i| (420 account("caller", i, 0),421 Registration::<BalanceOf<T>, T::MaxRegistrars, T::MaxAdditionalFields> {422 judgements: Default::default(),423 deposit: Default::default(),424 info: create_identity_info::<T>(x),425 },426 )).collect::<Vec<_>>();427 let origin = T::ForceOrigin::successful_origin();428 }: _<T::RuntimeOrigin>(origin, identities)429430 force_remove_identities {431 let x in 0 .. T::MaxAdditionalFields::get();432 let n in 0..600;433 use frame_benchmarking::account;434 let origin = T::ForceOrigin::successful_origin();435 let identities = (0..n).map(|i| (436 account("caller", i, 0),437 Registration::<BalanceOf<T>, T::MaxRegistrars, T::MaxAdditionalFields> {438 judgements: Default::default(),439 deposit: Default::default(),440 info: create_identity_info::<T>(x),441 },442 )).collect::<Vec<_>>();443 assert_ok!(444 Identity::<T>::force_insert_identities(origin.clone(), identities.clone()),445 );446 let identities = identities.into_iter().map(|(acc, _)| acc).collect::<Vec<_>>();447 }: _<T::RuntimeOrigin>(origin, identities)448449 add_sub {450 let s in 0 .. T::MaxSubAccounts::get() - 1;451452 let caller: T::AccountId = whitelisted_caller();453 let _ = add_sub_accounts::<T>(&caller, s)?;454 let sub = account("new_sub", 0, SEED);455 let data = Data::Raw(vec![0; 32].try_into().unwrap());456 ensure!(SubsOf::<T>::get(&caller).1.len() as u32 == s, "Subs not set.");457 }: _(RawOrigin::Signed(caller.clone()), T::Lookup::unlookup(sub), data)458 verify {459 ensure!(SubsOf::<T>::get(&caller).1.len() as u32 == s + 1, "Subs not added.");460 }461462 rename_sub {463 let s in 1 .. T::MaxSubAccounts::get();464465 let caller: T::AccountId = whitelisted_caller();466 let (sub, _) = add_sub_accounts::<T>(&caller, s)?.remove(0);467 let data = Data::Raw(vec![1; 32].try_into().unwrap());468 ensure!(SuperOf::<T>::get(&sub).unwrap().1 != data, "data already set");469 }: _(RawOrigin::Signed(caller), T::Lookup::unlookup(sub.clone()), data.clone())470 verify {471 ensure!(SuperOf::<T>::get(&sub).unwrap().1 == data, "data not set");472 }473474 remove_sub {475 let s in 1 .. T::MaxSubAccounts::get();476477 let caller: T::AccountId = whitelisted_caller();478 let (sub, _) = add_sub_accounts::<T>(&caller, s)?.remove(0);479 ensure!(SuperOf::<T>::contains_key(&sub), "Sub doesn't exists");480 }: _(RawOrigin::Signed(caller), T::Lookup::unlookup(sub.clone()))481 verify {482 ensure!(!SuperOf::<T>::contains_key(&sub), "Sub not removed");483 }484485 quit_sub {486 let s in 0 .. T::MaxSubAccounts::get() - 1;487488 let caller: T::AccountId = whitelisted_caller();489 let sup = account("super", 0, SEED);490 let _ = add_sub_accounts::<T>(&sup, s)?;491 let sup_origin = RawOrigin::Signed(sup).into();492 Identity::<T>::add_sub(sup_origin, T::Lookup::unlookup(caller.clone()), Data::Raw(vec![0; 32].try_into().unwrap()))?;493 ensure!(SuperOf::<T>::contains_key(&caller), "Sub doesn't exists");494 }: _(RawOrigin::Signed(caller.clone()))495 verify {496 ensure!(!SuperOf::<T>::contains_key(&caller), "Sub not removed");497 }498499 impl_benchmark_test_suite!(Identity, crate::tests::new_test_ext(), crate::tests::Test);500}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// Original license:18// This file is part of Substrate.1920// Copyright (C) 2020-2022 Parity Technologies (UK) Ltd.21// SPDX-License-Identifier: Apache-2.02223// Licensed under the Apache License, Version 2.0 (the "License");24// you may not use this file except in compliance with the License.25// You may obtain a copy of the License at26//27// http://www.apache.org/licenses/LICENSE-2.028//29// Unless required by applicable law or agreed to in writing, software30// distributed under the License is distributed on an "AS IS" BASIS,31// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.32// See the License for the specific language governing permissions and33// limitations under the License.3435//! Identity pallet benchmarking.3637#![cfg(feature = "runtime-benchmarks")]3839use super::*;4041use crate::Pallet as Identity;42use frame_benchmarking::{account, benchmarks, whitelisted_caller};43use frame_support::{44 ensure, assert_ok,45 traits::{EnsureOrigin, Get},46};47use frame_system::RawOrigin;48use sp_runtime::traits::Bounded;4950const SEED: u32 = 0;5152fn assert_last_event<T: Config>(generic_event: <T as Config>::RuntimeEvent) {53 frame_system::Pallet::<T>::assert_last_event(generic_event.into());54}5556// Adds `r` registrars to the Identity Pallet. These registrars will have set fees and fields.57fn add_registrars<T: Config>(r: u32) -> Result<(), &'static str> {58 for i in 0..r {59 let registrar: T::AccountId = account("registrar", i, SEED);60 let registrar_lookup = T::Lookup::unlookup(registrar.clone());61 let _ = T::Currency::make_free_balance_be(®istrar, BalanceOf::<T>::max_value());62 let registrar_origin = T::RegistrarOrigin::successful_origin();63 Identity::<T>::add_registrar(registrar_origin, registrar_lookup)?;64 Identity::<T>::set_fee(RawOrigin::Signed(registrar.clone()).into(), i, 10u32.into())?;65 let fields = IdentityFields(66 IdentityField::Display67 | IdentityField::Legal68 | IdentityField::Web69 | IdentityField::Riot70 | IdentityField::Email71 | IdentityField::PgpFingerprint72 | IdentityField::Image73 | IdentityField::Twitter,74 );75 Identity::<T>::set_fields(RawOrigin::Signed(registrar.clone()).into(), i, fields)?;76 }7778 assert_eq!(Registrars::<T>::get().len(), r as usize);79 Ok(())80}8182// Create `s` sub-accounts for the identity of `who` and return them.83// Each will have 32 bytes of raw data added to it.84fn create_sub_accounts<T: Config>(85 who: &T::AccountId,86 s: u32,87) -> Result<Vec<(T::AccountId, Data)>, &'static str> {88 let mut subs = Vec::new();89 let who_origin = RawOrigin::Signed(who.clone());90 let data = Data::Raw(vec![0; 32].try_into().unwrap());9192 for i in 0..s {93 let sub_account = account("sub", i, SEED);94 subs.push((sub_account, data.clone()));95 }9697 // Set identity so `set_subs` does not fail.98 if IdentityOf::<T>::get(who).is_none() {99 let _ = T::Currency::make_free_balance_be(who, BalanceOf::<T>::max_value() / 2u32.into());100 let info = create_identity_info::<T>(1);101 Identity::<T>::set_identity(who_origin.into(), Box::new(info))?;102 }103104 Ok(subs)105}106107// Adds `s` sub-accounts to the identity of `who`. Each will have 32 bytes of raw data added to it.108// This additionally returns the vector of sub-accounts so it can be modified if needed.109fn add_sub_accounts<T: Config>(110 who: &T::AccountId,111 s: u32,112) -> Result<Vec<(T::AccountId, Data)>, &'static str> {113 let who_origin = RawOrigin::Signed(who.clone());114 let subs = create_sub_accounts::<T>(who, s)?;115116 Identity::<T>::set_subs(who_origin.into(), subs.clone())?;117118 Ok(subs)119}120121// This creates an `IdentityInfo` object with `num_fields` extra fields.122// All data is pre-populated with some arbitrary bytes.123fn create_identity_info<T: Config>(num_fields: u32) -> IdentityInfo<T::MaxAdditionalFields> {124 let data = Data::Raw(vec![0; 32].try_into().unwrap());125126 IdentityInfo {127 additional: vec![(data.clone(), data.clone()); num_fields as usize]128 .try_into()129 .unwrap(),130 display: data.clone(),131 legal: data.clone(),132 web: data.clone(),133 riot: data.clone(),134 email: data.clone(),135 pgp_fingerprint: Some([0; 20]),136 image: data.clone(),137 twitter: data,138 }139}140141benchmarks! {142 add_registrar {143 let r in 1 .. T::MaxRegistrars::get() - 1 => add_registrars::<T>(r)?;144 ensure!(Registrars::<T>::get().len() as u32 == r, "Registrars not set up correctly.");145 let origin = T::RegistrarOrigin::successful_origin();146 let account = T::Lookup::unlookup(account("registrar", r + 1, SEED));147 }: _<T::RuntimeOrigin>(origin, account)148 verify {149 ensure!(Registrars::<T>::get().len() as u32 == r + 1, "Registrars not added.");150 }151152 set_identity {153 let r in 1 .. T::MaxRegistrars::get() => add_registrars::<T>(r)?;154 let x in 0 .. T::MaxAdditionalFields::get();155 let caller = {156 // The target user157 let caller: T::AccountId = whitelisted_caller();158 let caller_lookup = T::Lookup::unlookup(caller.clone());159 let caller_origin: <T as frame_system::Config>::RuntimeOrigin = RawOrigin::Signed(caller.clone()).into();160 let _ = T::Currency::make_free_balance_be(&caller, BalanceOf::<T>::max_value());161162 // Add an initial identity163 let initial_info = create_identity_info::<T>(1);164 Identity::<T>::set_identity(caller_origin.clone(), Box::new(initial_info.clone()))?;165166 // User requests judgement from all the registrars, and they approve167 for i in 0..r {168 let registrar: T::AccountId = account("registrar", i, SEED);169 let registrar_lookup = T::Lookup::unlookup(registrar.clone());170 let balance_to_use = T::Currency::minimum_balance() * 10u32.into();171 let _ = T::Currency::make_free_balance_be(®istrar, balance_to_use);172173 Identity::<T>::request_judgement(caller_origin.clone(), i, 10u32.into())?;174 Identity::<T>::provide_judgement(175 RawOrigin::Signed(registrar).into(),176 i,177 caller_lookup.clone(),178 Judgement::Reasonable,179 T::Hashing::hash_of(&initial_info),180 )?;181 }182 caller183 };184 }: _(RawOrigin::Signed(caller.clone()), Box::new(create_identity_info::<T>(x)))185 verify {186 assert_last_event::<T>(Event::<T>::IdentitySet { who: caller }.into());187 }188189 // We need to split `set_subs` into two benchmarks to accurately isolate the potential190 // writes caused by new or old sub accounts. The actual weight should simply be191 // the sum of these two weights.192 set_subs_new {193 let caller: T::AccountId = whitelisted_caller();194 // Create a new subs vec with s sub accounts195 let s in 0 .. T::MaxSubAccounts::get() => ();196 let subs = create_sub_accounts::<T>(&caller, s)?;197 ensure!(SubsOf::<T>::get(&caller).1.len() == 0, "Caller already has subs");198 }: set_subs(RawOrigin::Signed(caller.clone()), subs)199 verify {200 ensure!(SubsOf::<T>::get(&caller).1.len() as u32 == s, "Subs not added");201 }202203 set_subs_old {204 let caller: T::AccountId = whitelisted_caller();205 // Give them p many previous sub accounts.206 let p in 0 .. T::MaxSubAccounts::get() => {207 let _ = add_sub_accounts::<T>(&caller, p)?;208 };209 // Remove all subs.210 let subs = create_sub_accounts::<T>(&caller, 0)?;211 ensure!(212 SubsOf::<T>::get(&caller).1.len() as u32 == p,213 "Caller does have subs",214 );215 }: set_subs(RawOrigin::Signed(caller.clone()), subs)216 verify {217 ensure!(SubsOf::<T>::get(&caller).1.len() == 0, "Subs not removed");218 }219220 clear_identity {221 let caller: T::AccountId = whitelisted_caller();222 let caller_origin = <T as frame_system::Config>::RuntimeOrigin::from(RawOrigin::Signed(caller.clone()));223 let caller_lookup = <T::Lookup as StaticLookup>::unlookup(caller.clone());224 let _ = T::Currency::make_free_balance_be(&caller, BalanceOf::<T>::max_value());225226 let r in 1 .. T::MaxRegistrars::get() => add_registrars::<T>(r)?;227 let s in 0 .. T::MaxSubAccounts::get() => {228 // Give them s many sub accounts229 let caller: T::AccountId = whitelisted_caller();230 let _ = add_sub_accounts::<T>(&caller, s)?;231 };232 let x in 0 .. T::MaxAdditionalFields::get();233234 // Create their main identity with x additional fields235 let info = create_identity_info::<T>(x);236 let caller: T::AccountId = whitelisted_caller();237 let caller_origin = <T as frame_system::Config>::RuntimeOrigin::from(RawOrigin::Signed(caller.clone()));238 Identity::<T>::set_identity(caller_origin.clone(), Box::new(info.clone()))?;239240 // User requests judgement from all the registrars, and they approve241 for i in 0..r {242 let registrar: T::AccountId = account("registrar", i, SEED);243 let balance_to_use = T::Currency::minimum_balance() * 10u32.into();244 let _ = T::Currency::make_free_balance_be(®istrar, balance_to_use);245246 Identity::<T>::request_judgement(caller_origin.clone(), i, 10u32.into())?;247 Identity::<T>::provide_judgement(248 RawOrigin::Signed(registrar).into(),249 i,250 caller_lookup.clone(),251 Judgement::Reasonable,252 T::Hashing::hash_of(&info),253 )?;254 }255 ensure!(IdentityOf::<T>::contains_key(&caller), "Identity does not exist.");256 }: _(RawOrigin::Signed(caller.clone()))257 verify {258 ensure!(!IdentityOf::<T>::contains_key(&caller), "Identity not cleared.");259 }260261 request_judgement {262 let caller: T::AccountId = whitelisted_caller();263 let _ = T::Currency::make_free_balance_be(&caller, BalanceOf::<T>::max_value());264265 let r in 1 .. T::MaxRegistrars::get() => add_registrars::<T>(r)?;266 let x in 0 .. T::MaxAdditionalFields::get() => {267 // Create their main identity with x additional fields268 let info = create_identity_info::<T>(x);269 let caller: T::AccountId = whitelisted_caller();270 let caller_origin = <T as frame_system::Config>::RuntimeOrigin::from(RawOrigin::Signed(caller));271 Identity::<T>::set_identity(caller_origin, Box::new(info))?;272 };273 }: _(RawOrigin::Signed(caller.clone()), r - 1, 10u32.into())274 verify {275 assert_last_event::<T>(Event::<T>::JudgementRequested { who: caller, registrar_index: r-1 }.into());276 }277278 cancel_request {279 let caller: T::AccountId = whitelisted_caller();280 let caller_origin = <T as frame_system::Config>::RuntimeOrigin::from(RawOrigin::Signed(caller.clone()));281 let _ = T::Currency::make_free_balance_be(&caller, BalanceOf::<T>::max_value());282283 let r in 1 .. T::MaxRegistrars::get() => add_registrars::<T>(r)?;284 let x in 0 .. T::MaxAdditionalFields::get() => {285 // Create their main identity with x additional fields286 let info = create_identity_info::<T>(x);287 let caller: T::AccountId = whitelisted_caller();288 let caller_origin = <T as frame_system::Config>::RuntimeOrigin::from(RawOrigin::Signed(caller));289 Identity::<T>::set_identity(caller_origin, Box::new(info))?;290 };291292 Identity::<T>::request_judgement(caller_origin, r - 1, 10u32.into())?;293 }: _(RawOrigin::Signed(caller.clone()), r - 1)294 verify {295 assert_last_event::<T>(Event::<T>::JudgementUnrequested { who: caller, registrar_index: r-1 }.into());296 }297298 set_fee {299 let caller: T::AccountId = whitelisted_caller();300 let caller_lookup = T::Lookup::unlookup(caller.clone());301302 let r in 1 .. T::MaxRegistrars::get() - 1 => add_registrars::<T>(r)?;303304 let registrar_origin = T::RegistrarOrigin::successful_origin();305 Identity::<T>::add_registrar(registrar_origin, caller_lookup)?;306 let registrars = Registrars::<T>::get();307 ensure!(registrars[r as usize].as_ref().unwrap().fee == 0u32.into(), "Fee already set.");308 }: _(RawOrigin::Signed(caller), r, 100u32.into())309 verify {310 let registrars = Registrars::<T>::get();311 ensure!(registrars[r as usize].as_ref().unwrap().fee == 100u32.into(), "Fee not changed.");312 }313314 set_account_id {315 let caller: T::AccountId = whitelisted_caller();316 let caller_lookup = T::Lookup::unlookup(caller.clone());317 let _ = T::Currency::make_free_balance_be(&caller, BalanceOf::<T>::max_value());318319 let r in 1 .. T::MaxRegistrars::get() - 1 => add_registrars::<T>(r)?;320321 let registrar_origin = T::RegistrarOrigin::successful_origin();322 Identity::<T>::add_registrar(registrar_origin, caller_lookup)?;323 let registrars = Registrars::<T>::get();324 ensure!(registrars[r as usize].as_ref().unwrap().account == caller, "id not set.");325 let new_account = T::Lookup::unlookup(account("new", 0, SEED));326 }: _(RawOrigin::Signed(caller), r, new_account)327 verify {328 let registrars = Registrars::<T>::get();329 ensure!(registrars[r as usize].as_ref().unwrap().account == account("new", 0, SEED), "id not changed.");330 }331332 set_fields {333 let caller: T::AccountId = whitelisted_caller();334 let caller_lookup = T::Lookup::unlookup(caller.clone());335 let _ = T::Currency::make_free_balance_be(&caller, BalanceOf::<T>::max_value());336337 let r in 1 .. T::MaxRegistrars::get() - 1 => add_registrars::<T>(r)?;338339 let registrar_origin = T::RegistrarOrigin::successful_origin();340 Identity::<T>::add_registrar(registrar_origin, caller_lookup)?;341 let fields = IdentityFields(342 IdentityField::Display | IdentityField::Legal | IdentityField::Web | IdentityField::Riot343 | IdentityField::Email | IdentityField::PgpFingerprint | IdentityField::Image | IdentityField::Twitter344 );345 let registrars = Registrars::<T>::get();346 ensure!(registrars[r as usize].as_ref().unwrap().fields == Default::default(), "fields already set.");347 }: _(RawOrigin::Signed(caller), r, fields)348 verify {349 let registrars = Registrars::<T>::get();350 ensure!(registrars[r as usize].as_ref().unwrap().fields != Default::default(), "fields not set.");351 }352353 provide_judgement {354 // The user355 let user: T::AccountId = account("user", r, SEED);356 let user_origin = <T as frame_system::Config>::RuntimeOrigin::from(RawOrigin::Signed(user.clone()));357 let user_lookup = <T::Lookup as StaticLookup>::unlookup(user.clone());358 let _ = T::Currency::make_free_balance_be(&user, BalanceOf::<T>::max_value());359360 let caller: T::AccountId = whitelisted_caller();361 let caller_lookup = T::Lookup::unlookup(caller.clone());362 let _ = T::Currency::make_free_balance_be(&caller, BalanceOf::<T>::max_value());363364 let r in 1 .. T::MaxRegistrars::get() - 1 => add_registrars::<T>(r)?;365 let x in 0 .. T::MaxAdditionalFields::get();366367 let info = create_identity_info::<T>(x);368 let info_hash = T::Hashing::hash_of(&info);369 Identity::<T>::set_identity(user_origin.clone(), Box::new(info))?;370371 let registrar_origin = T::RegistrarOrigin::successful_origin();372 Identity::<T>::add_registrar(registrar_origin, caller_lookup)?;373 Identity::<T>::request_judgement(user_origin, r, 10u32.into())?;374 }: _(RawOrigin::Signed(caller), r, user_lookup, Judgement::Reasonable, info_hash)375 verify {376 assert_last_event::<T>(Event::<T>::JudgementGiven { target: user, registrar_index: r }.into())377 }378379 kill_identity {380 let r in 1 .. T::MaxRegistrars::get() => add_registrars::<T>(r)?;381 let s in 0 .. T::MaxSubAccounts::get();382 let x in 0 .. T::MaxAdditionalFields::get();383384 let target: T::AccountId = account("target", 0, SEED);385 let target_origin: <T as frame_system::Config>::RuntimeOrigin = RawOrigin::Signed(target.clone()).into();386 let target_lookup = T::Lookup::unlookup(target.clone());387 let _ = T::Currency::make_free_balance_be(&target, BalanceOf::<T>::max_value());388389 let info = create_identity_info::<T>(x);390 Identity::<T>::set_identity(target_origin.clone(), Box::new(info.clone()))?;391 let _ = add_sub_accounts::<T>(&target, s)?;392393 // User requests judgement from all the registrars, and they approve394 for i in 0..r {395 let registrar: T::AccountId = account("registrar", i, SEED);396 let balance_to_use = T::Currency::minimum_balance() * 10u32.into();397 let _ = T::Currency::make_free_balance_be(®istrar, balance_to_use);398399 Identity::<T>::request_judgement(target_origin.clone(), i, 10u32.into())?;400 Identity::<T>::provide_judgement(401 RawOrigin::Signed(registrar).into(),402 i,403 target_lookup.clone(),404 Judgement::Reasonable,405 T::Hashing::hash_of(&info),406 )?;407 }408 ensure!(IdentityOf::<T>::contains_key(&target), "Identity not set");409 let origin = T::ForceOrigin::successful_origin();410 }: _<T::RuntimeOrigin>(origin, target_lookup)411 verify {412 ensure!(!IdentityOf::<T>::contains_key(&target), "Identity not removed");413 }414415 force_insert_identities {416 let x in 0 .. T::MaxAdditionalFields::get();417 let n in 0..600;418 use frame_benchmarking::account;419 let identities = (0..n).map(|i| (420 account("caller", i, SEED),421 Registration::<BalanceOf<T>, T::MaxRegistrars, T::MaxAdditionalFields> {422 judgements: Default::default(),423 deposit: Default::default(),424 info: create_identity_info::<T>(x),425 },426 )).collect::<Vec<_>>();427 let origin = T::ForceOrigin::successful_origin();428 }: _<T::RuntimeOrigin>(origin, identities)429430 force_remove_identities {431 let x in 0 .. T::MaxAdditionalFields::get();432 let n in 0..600;433 use frame_benchmarking::account;434 let origin = T::ForceOrigin::successful_origin();435 let identities = (0..n).map(|i| (436 account("caller", i, SEED),437 Registration::<BalanceOf<T>, T::MaxRegistrars, T::MaxAdditionalFields> {438 judgements: Default::default(),439 deposit: Default::default(),440 info: create_identity_info::<T>(x),441 },442 )).collect::<Vec<_>>();443 assert_ok!(444 Identity::<T>::force_insert_identities(origin.clone(), identities.clone()),445 );446 let identities = identities.into_iter().map(|(acc, _)| acc).collect::<Vec<_>>();447 }: _<T::RuntimeOrigin>(origin, identities)448449 force_set_subs {450 let s in 0 .. T::MaxSubAccounts::get();451 let n in 0..600;452 use frame_benchmarking::account;453 let identities = (0..n).map(|i| (454 account("caller", i, SEED),455 (456 BalanceOf::<T>::max_value(),457 create_sub_accounts::<T>(&caller, s)?.try_into().unwrap(),458 ),459 )).collect::<Vec<_>>();460 let origin = T::ForceOrigin::successful_origin();461 }: _<T::RuntimeOrigin>(origin, identities)462463 add_sub {464 let s in 0 .. T::MaxSubAccounts::get() - 1;465466 let caller: T::AccountId = whitelisted_caller();467 let _ = add_sub_accounts::<T>(&caller, s)?;468 let sub = account("new_sub", 0, SEED);469 let data = Data::Raw(vec![0; 32].try_into().unwrap());470 ensure!(SubsOf::<T>::get(&caller).1.len() as u32 == s, "Subs not set.");471 }: _(RawOrigin::Signed(caller.clone()), T::Lookup::unlookup(sub), data)472 verify {473 ensure!(SubsOf::<T>::get(&caller).1.len() as u32 == s + 1, "Subs not added.");474 }475476 rename_sub {477 let s in 1 .. T::MaxSubAccounts::get();478479 let caller: T::AccountId = whitelisted_caller();480 let (sub, _) = add_sub_accounts::<T>(&caller, s)?.remove(0);481 let data = Data::Raw(vec![1; 32].try_into().unwrap());482 ensure!(SuperOf::<T>::get(&sub).unwrap().1 != data, "data already set");483 }: _(RawOrigin::Signed(caller), T::Lookup::unlookup(sub.clone()), data.clone())484 verify {485 ensure!(SuperOf::<T>::get(&sub).unwrap().1 == data, "data not set");486 }487488 remove_sub {489 let s in 1 .. T::MaxSubAccounts::get();490491 let caller: T::AccountId = whitelisted_caller();492 let (sub, _) = add_sub_accounts::<T>(&caller, s)?.remove(0);493 ensure!(SuperOf::<T>::contains_key(&sub), "Sub doesn't exists");494 }: _(RawOrigin::Signed(caller), T::Lookup::unlookup(sub.clone()))495 verify {496 ensure!(!SuperOf::<T>::contains_key(&sub), "Sub not removed");497 }498499 quit_sub {500 let s in 0 .. T::MaxSubAccounts::get() - 1;501502 let caller: T::AccountId = whitelisted_caller();503 let sup = account("super", 0, SEED);504 let _ = add_sub_accounts::<T>(&sup, s)?;505 let sup_origin = RawOrigin::Signed(sup).into();506 Identity::<T>::add_sub(sup_origin, T::Lookup::unlookup(caller.clone()), Data::Raw(vec![0; 32].try_into().unwrap()))?;507 ensure!(SuperOf::<T>::contains_key(&caller), "Sub doesn't exists");508 }: _(RawOrigin::Signed(caller.clone()))509 verify {510 ensure!(!SuperOf::<T>::contains_key(&caller), "Sub not removed");511 }512513 impl_benchmark_test_suite!(Identity, crate::tests::new_test_ext(), crate::tests::Test);514}pallets/identity/src/lib.rsdiffbeforeafterboth--- a/pallets/identity/src/lib.rs
+++ b/pallets/identity/src/lib.rs
@@ -314,6 +314,8 @@
main: T::AccountId,
deposit: BalanceOf<T>,
},
+ /// A number of identities were forcibly updated with new sub-identities.
+ SubIdentitiesInserted { amount: u32 },
}
#[pallet::call]
@@ -1137,13 +1139,64 @@
) -> DispatchResult {
T::ForceOrigin::ensure_origin(origin)?;
for identity in identities.clone() {
- IdentityOf::<T>::set(identity, None);
+ let (_, sub_ids) = <SubsOf<T>>::take(&identity);
+ <IdentityOf<T>>::remove(&identity);
+ for sub in sub_ids.iter() {
+ <SuperOf<T>>::remove(sub);
+ }
}
Self::deposit_event(Event::IdentitiesRemoved {
amount: identities.len() as u32,
});
Ok(())
}
+
+ /// Set sub-identities to be associated with the provided accounts as force origin.
+ ///
+ /// This is not meant to operate in tandem with the identity pallet as is,
+ /// and be instead used to keep identities made and verified externally,
+ /// forbidden from interacting with an ordinary user, since it ignores any safety mechanism.
+ #[pallet::call_index(17)]
+ #[pallet::weight(T::WeightInfo::force_set_subs(
+ T::MaxSubAccounts::get(), // S
+ subs.len() as u32, // N
+ ))]
+ pub fn force_set_subs(
+ origin: OriginFor<T>,
+ subs: Vec<(
+ T::AccountId,
+ (
+ BalanceOf<T>,
+ BoundedVec<(T::AccountId, Data), T::MaxSubAccounts>,
+ ),
+ )>,
+ ) -> DispatchResult {
+ T::ForceOrigin::ensure_origin(origin)?;
+ for identity in subs.clone() {
+ let account = identity.0;
+ let (_, old_subs) = <SubsOf<T>>::get(&account);
+ for old_sub in old_subs {
+ <SuperOf<T>>::remove(old_sub);
+ }
+
+ let mut ids = BoundedVec::<T::AccountId, T::MaxSubAccounts>::default();
+ for (id, name) in identity.1 .1 {
+ <SuperOf<T>>::insert(&id, (account.clone(), name));
+ ids.try_push(id)
+ .expect("subs length is less than T::MaxSubAccounts; qed");
+ }
+
+ if ids.is_empty() {
+ <SubsOf<T>>::remove(&account);
+ } else {
+ <SubsOf<T>>::insert(account, (identity.1 .0, ids));
+ }
+ }
+ Self::deposit_event(Event::SubIdentitiesInserted {
+ amount: subs.len() as u32,
+ });
+ Ok(())
+ }
}
}
pallets/identity/src/weights.rsdiffbeforeafterboth--- a/pallets/identity/src/weights.rs
+++ b/pallets/identity/src/weights.rs
@@ -78,6 +78,7 @@
fn kill_identity(r: u32, s: u32, x: u32, ) -> Weight;
fn force_insert_identities(x: u32, n: u32, ) -> Weight;
fn force_remove_identities(x: u32, n: u32, ) -> Weight;
+ fn force_set_subs(s: u32, n: u32, ) -> Weight;
fn add_sub(s: u32, ) -> Weight;
fn rename_sub(s: u32, ) -> Weight;
fn remove_sub(s: u32, ) -> Weight;
@@ -273,6 +274,20 @@
.saturating_add(T::DbWeight::get().reads(1 as u64))
.saturating_add(T::DbWeight::get().writes(1 as u64).saturating_mul(n as u64))
}
+ // Storage: Identity IdentityOf (r:1 w:1)
+ // todo:collator
+ /// The range of component `s` is `[0, 100]`.
+ /// The range of component `n` is `[0, 600]`.
+ fn force_set_subs(s: u32, n: u32) -> Weight {
+ // Minimum execution time: 41_872 nanoseconds.
+ Weight::from_ref_time(40_230_216 as u64)
+ // Standard Error: 2_342
+ .saturating_add(Weight::from_ref_time(145_168 as u64))
+ // Standard Error: 457
+ .saturating_add(Weight::from_ref_time(291_732 as u64).saturating_mul(s as u64))
+ .saturating_add(T::DbWeight::get().reads(1 as u64))
+ .saturating_add(T::DbWeight::get().writes(1 as u64).saturating_mul(n as u64))
+ }
// Storage: Identity IdentityOf (r:1 w:0)
// Storage: Identity SuperOf (r:1 w:1)
// Storage: Identity SubsOf (r:1 w:1)
@@ -509,6 +524,20 @@
.saturating_add(RocksDbWeight::get().reads(1 as u64))
.saturating_add(RocksDbWeight::get().writes(1 as u64).saturating_mul(n as u64))
}
+ // Storage: Identity IdentityOf (r:1 w:1)
+ // todo:collator
+ /// The range of component `xs is `[0, 100]`.
+ /// The range of component `n` is `[0, 600]`.
+ fn force_set_subs(s: u32, n: u32) -> Weight {
+ // Minimum execution time: 41_872 nanoseconds.
+ Weight::from_ref_time(40_230_216 as u64)
+ // Standard Error: 2_342
+ .saturating_add(Weight::from_ref_time(145_168 as u64))
+ // Standard Error: 457
+ .saturating_add(Weight::from_ref_time(291_732 as u64).saturating_mul(s as u64))
+ .saturating_add(RocksDbWeight::get().reads(1 as u64))
+ .saturating_add(RocksDbWeight::get().writes(1 as u64).saturating_mul(n as u64))
+ }
// Storage: Identity IdentityOf (r:1 w:0)
// Storage: Identity SuperOf (r:1 w:1)
// Storage: Identity SubsOf (r:1 w:1)
tests/src/collator-selection/identity.seqtest.tsdiffbeforeafterboth--- a/tests/src/collator-selection/identity.seqtest.ts
+++ b/tests/src/collator-selection/identity.seqtest.ts
@@ -29,6 +29,14 @@
return (await getIdentities(helper)).flatMap(([key, _value]) => key);
}
+async function getSubIdentityAccounts(helper: UniqueHelper, address: string) {
+ return ((await helper.getApi().query.identity.subsOf(address)).toHuman() as any)[1];
+}
+
+async function getSubIdentityName(helper: UniqueHelper, address: string) {
+ return ((await helper.getApi().query.identity.superOf(address)).toHuman() as any);
+}
+
describe('Integration Test: Identities Manipulation', () => {
let superuser: IKeyringPair;
@@ -47,49 +55,220 @@
.to.be.rejectedWith(/Transaction call is not expected/);
});
- itSub('Sets identities', async ({helper}) => {
- const oldIdentitiesCount = (await getIdentityAccounts(helper)).length;
+ describe('Identities', () => {
+ itSub('Sets identities', async ({helper}) => {
+ const oldIdentitiesCount = (await getIdentityAccounts(helper)).length;
- const crowdSize = 10;
- const crowd = await helper.arrange.createCrowd(crowdSize, 0n, superuser);
- const identities = crowd.map((acc, i) => [acc.address, {info: {display: {Raw: `accounter #${i}`}}}]);
- await helper.getSudo().executeExtrinsic(superuser, 'api.tx.identity.forceInsertIdentities', [identities]);
+ const crowdSize = 10;
+ const crowd = await helper.arrange.createCrowd(crowdSize, 0n, superuser);
+ const identities = crowd.map((acc, i) => [acc.address, {info: {display: {Raw: `accounter #${i}`}}}]);
+ await helper.getSudo().executeExtrinsic(superuser, 'api.tx.identity.forceInsertIdentities', [identities]);
- expect((await getIdentityAccounts(helper)).length).to.be.equal(oldIdentitiesCount + crowdSize);
- });
+ expect((await getIdentityAccounts(helper)).length).to.be.equal(oldIdentitiesCount + crowdSize);
+ });
- itSub('Setting identities does not delete existing but does overwrite', async ({helper}) => {
- const crowd = await helper.arrange.createCrowd(10, 0n, superuser);
- const identities = crowd.map((acc, i) => [acc.address, {info: {display: {Raw: `accounter #${i}`}}}]);
+ itSub('Setting identities does not delete existing but does overwrite', async ({helper}) => {
+ const crowd = await helper.arrange.createCrowd(10, 0n, superuser);
+ const identities = crowd.map((acc, i) => [acc.address, {info: {display: {Raw: `accounter #${i}`}}}]);
+
+ // insert a single identity
+ let singleIdentity = identities.pop()!;
+ await helper.getSudo().executeExtrinsic(superuser, 'api.tx.identity.forceInsertIdentities', [[singleIdentity]]);
- // insert a single identity
- let singleIdentity = identities.pop()!;
- await helper.getSudo().executeExtrinsic(superuser, 'api.tx.identity.forceInsertIdentities', [[singleIdentity]]);
+ const oldIdentitiesCount = (await getIdentityAccounts(helper)).length;
- const oldIdentitiesCount = (await getIdentityAccounts(helper)).length;
+ // change an identity and push it with a few new others
+ singleIdentity = [singleIdentity[0], {info: {display: {Raw: 'something special'}}}];
+ identities.push(singleIdentity);
+ await helper.getSudo().executeExtrinsic(superuser, 'api.tx.identity.forceInsertIdentities', [identities]);
- // change an identity and push it with a few new others
- singleIdentity = [singleIdentity[0], {info: {display: {Raw: 'something special'}}}];
- identities.push(singleIdentity);
- await helper.getSudo().executeExtrinsic(superuser, 'api.tx.identity.forceInsertIdentities', [identities]);
+ // oldIdentitiesCount + 9 because one identity is overwritten, not inserted on top
+ expect((await getIdentityAccounts(helper)).length).to.be.equal(oldIdentitiesCount + 9);
+ expect((await helper.callRpc('api.query.identity.identityOf', [singleIdentity[0]])).toHuman().info.display)
+ .to.be.deep.equal({Raw: 'something special'});
+ });
- // oldIdentitiesCount + 9 because one identity is overwritten, not inserted on top
- expect((await getIdentityAccounts(helper)).length).to.be.equal(oldIdentitiesCount + 9);
- expect((await helper.callRpc('api.query.identity.identityOf', [singleIdentity[0]])).toHuman().info.display)
- .to.be.deep.equal({Raw: 'something special'});
+ itSub('Removes identities', async ({helper}) => {
+ const crowd = await helper.arrange.createCrowd(10, 0n, superuser);
+ const identities = crowd.map((acc, i) => [acc.address, {info: {display: {Raw: `accounter #${i}`}}}]);
+ await helper.getSudo().executeExtrinsic(superuser, 'api.tx.identity.forceInsertIdentities', [identities]);
+ const oldIdentities = await getIdentityAccounts(helper);
+
+ // delete a couple, check that they are no longer there
+ const scapegoats = [crowd.pop()!.address, crowd.pop()!.address];
+ await helper.getSudo().executeExtrinsic(superuser, 'api.tx.identity.forceRemoveIdentities', [scapegoats]);
+ const newIdentities = await getIdentityAccounts(helper);
+ expect(newIdentities.concat(scapegoats)).to.be.have.members(oldIdentities);
+ });
});
- itSub('Removes identities', async ({helper}) => {
- const crowd = await helper.arrange.createCrowd(10, 0n, superuser);
- const identities = crowd.map((acc, i) => [acc.address, {info: {display: {Raw: `accounter #${i}`}}}]);
- await helper.getSudo().executeExtrinsic(superuser, 'api.tx.identity.forceInsertIdentities', [identities]);
- const oldIdentities = await getIdentityAccounts(helper);
+ describe('Sub-identities', () => {
+ itSub('Sets subs', async ({helper}) => {
+ const crowdSize = 18;
+ const crowd = await helper.arrange.createCrowd(crowdSize, 0n, superuser);
+ const supers = [crowd.pop()!, crowd.pop()!, crowd.pop()!];
- // delete a couple, check that they are no longer there
- const scapegoats = [crowd.pop()!.address, crowd.pop()!.address];
- await helper.getSudo().executeExtrinsic(superuser, 'api.tx.identity.forceRemoveIdentities', [scapegoats]);
- const newIdentities = await getIdentityAccounts(helper);
- expect(newIdentities.concat(scapegoats)).to.be.have.members(oldIdentities);
+ const subsPerSup = crowd.length / supers.length;
+ let subCount = 0;
+ const subs = [
+ crowd.slice(subCount, subCount += subsPerSup + 1),
+ crowd.slice(subCount, subCount += subsPerSup),
+ crowd.slice(subCount, subCount += subsPerSup - 1),
+ ];
+
+ const subsInfo = supers.map((acc, i) => [
+ acc.address, [
+ 1000000n + BigInt(i + 1),
+ subs[i].map((sub, j) => [
+ sub.address, {Raw: `accounter #${j}`},
+ ]),
+ ],
+ ]);
+ await helper.getSudo().executeExtrinsic(superuser, 'api.tx.identity.forceSetSubs', [subsInfo]);
+
+ for (let i = 0; i < supers.length; i++) {
+ // check deposit
+ expect(((await helper.getApi().query.identity.subsOf(supers[i].address)).toJSON() as any)[0]).to.be.equal(1000001 + i);
+
+ const subsAccounts = await getSubIdentityAccounts(helper, supers[i].address);
+ // check sub-identities as account ids
+ expect(subsAccounts).to.include.members(subs[i].map(x => x.address));
+
+ for (let j = 0; j < subsAccounts.length; j++) {
+ // check sub-identities' names
+ expect((await getSubIdentityName(helper, subsAccounts[j]))[1]).to.be.deep.equal({Raw: `accounter #${j}`});
+ }
+ }
+ });
+
+ itSub('Setting sub-identities does not delete other existing but does overwrite own', async ({helper}) => {
+ const crowdSize = 18;
+ const crowd = await helper.arrange.createCrowd(crowdSize, 0n, superuser);
+ const supers = [crowd.pop()!, crowd.pop()!, crowd.pop()!];
+
+ const subsPerSup = crowd.length / supers.length;
+ let subCount = 0;
+ const subs = [
+ crowd.slice(subCount, subCount += subsPerSup + 1),
+ crowd.slice(subCount, subCount += subsPerSup),
+ crowd.slice(subCount, subCount += subsPerSup - 1),
+ ];
+
+ const subsInfo1 = supers.map((acc, i) => [
+ acc.address, [
+ 1000000n + BigInt(i + 1),
+ subs[i].map((sub, j) => [
+ sub.address, {Raw: `accounter #${j}`},
+ ]),
+ ],
+ ]);
+ await helper.getSudo().executeExtrinsic(superuser, 'api.tx.identity.forceSetSubs', [subsInfo1]);
+
+ // change some sub-identities...
+ subs[2].pop(); subs[2].pop(); subs[2].push(...await helper.arrange.createAccounts([0n], superuser));
+
+ // ...and set them
+ const subsInfo2 = [[
+ supers[2].address, [
+ 999999n,
+ subs[2].map((sub, j) => [
+ sub.address, {Raw: `discounter #${j}`},
+ ]),
+ ],
+ ]];
+ await helper.getSudo().executeExtrinsic(superuser, 'api.tx.identity.forceSetSubs', [subsInfo2]);
+
+ // make sure everything else is the same
+ for (let i = 0; i < supers.length - 1; i++) {
+ // check deposit
+ expect(((await helper.getApi().query.identity.subsOf(supers[i].address)).toJSON() as any)[0]).to.be.equal(1000001 + i);
+
+ const subsAccounts = await getSubIdentityAccounts(helper, supers[i].address);
+ // check sub-identities as account ids
+ expect(subsAccounts).to.include.members(subs[i].map(x => x.address));
+
+ for (let j = 0; j < subsAccounts; j++) {
+ // check sub-identities' names
+ expect((await getSubIdentityName(helper, subsAccounts[j]))[1]).to.be.deep.equal({Raw: `accounter #${j}`});
+ }
+ }
+
+ // check deposit
+ expect(((await helper.getApi().query.identity.subsOf(supers[2].address)).toJSON() as any)[0]).to.be.equal(999999);
+
+ const subsAccounts = await getSubIdentityAccounts(helper, supers[2].address);
+ // check sub-identities as account ids
+ expect(subsAccounts).to.include.members(subs[2].map(x => x.address));
+
+ for (let j = 0; j < subsAccounts.length; j++) {
+ // check sub-identities' names
+ expect((await getSubIdentityName(helper, subsAccounts[j]))[1]).to.be.deep.equal({Raw: `discounter #${j}`});
+ }
+ });
+
+ itSub('Removes sub-identities', async ({helper}) => {
+ const crowdSize = 3;
+ const crowd = await helper.arrange.createCrowd(crowdSize, 0n, superuser);
+ const sup = crowd.pop()!;
+
+ const subsInfo1 = [[
+ sup.address, [
+ 1000000n,
+ crowd.map((sub, j) => [
+ sub.address, {Raw: `accounter #${j}`},
+ ]),
+ ],
+ ]];
+ await helper.getSudo().executeExtrinsic(superuser, 'api.tx.identity.forceSetSubs', [subsInfo1]);
+
+ // empty sub-identities should delete the records
+ const subsInfo2 = [[
+ sup.address, [
+ 1000000n,
+ [],
+ ],
+ ]];
+ await helper.getSudo().executeExtrinsic(superuser, 'api.tx.identity.forceSetSubs', [subsInfo2]);
+
+ // check deposit
+ expect((await helper.getApi().query.identity.subsOf(sup.address)).toHuman()).to.be.deep.equal(['0', []]);
+
+ for (let j = 0; j < crowd.length; j++) {
+ // check sub-identities' names
+ expect((await getSubIdentityName(helper, crowd[j].address))).to.be.null;
+ }
+ });
+
+ itSub('Removing identities deletes associated sub-identities', async ({helper}) => {
+ const crowd = await helper.arrange.createCrowd(3, 0n, superuser);
+ const sup = crowd.pop()!;
+
+ // insert identity
+ const identities = [[sup.address, {info: {display: {Raw: 'mental'}}}]];
+ await helper.getSudo().executeExtrinsic(superuser, 'api.tx.identity.forceInsertIdentities', [identities]);
+
+ // and its sub-identities
+ const subsInfo = [[
+ sup.address, [
+ 1000000n,
+ crowd.map((sub, j) => [
+ sub.address, {Raw: `accounter #${j}`},
+ ]),
+ ],
+ ]];
+ await helper.getSudo().executeExtrinsic(superuser, 'api.tx.identity.forceSetSubs', [subsInfo]);
+
+ // delete top identity
+ await helper.getSudo().executeExtrinsic(superuser, 'api.tx.identity.forceRemoveIdentities', [[sup.address]]);
+
+ // check that sub-identities are deleted
+ expect((await helper.getApi().query.identity.subsOf(sup.address)).toHuman()).to.be.deep.equal(['0', []]);
+
+ for (let j = 0; j < crowd.length; j++) {
+ // check sub-identities' names
+ expect((await getSubIdentityName(helper, crowd[j].address))).to.be.null;
+ }
+ });
});
after(async function() {
tests/src/util/identitySetter.tsdiffbeforeafterboth--- a/tests/src/util/identitySetter.ts
+++ b/tests/src/util/identitySetter.ts
@@ -1,5 +1,8 @@
// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
// SPDX-License-Identifier: Apache-2.0
+//
+// Usage: `yarn setIdentities [relay WS URL] [parachain WS URL] [sudo key]`
+// Example: `yarn setIdentities wss://polkadot-rpc.dwellir.com ws://localhost:9944 escape pattern miracle train sudden cart adapt embark wedding alien lamp mesh`
import {encodeAddress} from '@polkadot/keyring';
import {usingPlaygrounds, Pallets} from './index';
@@ -9,36 +12,81 @@
const paraUrl = process.argv[3] ?? 'ws://localhost:9944';
const key = process.argv.length > 4 ? process.argv.slice(4).join(' ') : '//Alice';
+function extractAccountId(key: any): string {
+ return (key as any).toHuman()[0];
+}
+
function extractIdentity(key: any, value: any): [string, any] {
- return [(key as any).toHuman()[0], (value as any).unwrap()];
+ return [extractAccountId(key), (value as any).unwrap()];
}
-async function getIdentities(helper: ChainHelperBase) {
+async function getIdentities(helper: ChainHelperBase, noneCasePredicate?: (key: any, value: any) => void) {
const identities: [string, any][] = [];
- for(const [key, value] of await helper.getApi().query.identity.identityOf.entries())
+ for(const [key, v] of await helper.getApi().query.identity.identityOf.entries()) {
+ const value = v as any;
+ if (value.isNone) {
+ if (noneCasePredicate) noneCasePredicate(key, value);
+ continue;
+ }
identities.push(extractIdentity(key, value));
+ }
return identities;
}
-// This is a utility for pulling
+function constructSubInfo(identityAccount: string, subQuery: any, supers: any[], ss58?: number): [string, any] {
+ const deposit = subQuery.toJSON()[0];
+ const subIdentities = subQuery.toHuman()[1];
+ subIdentities.map((sub: string) => supers.find((sup: any) => sup[0] === sub));
+ // supers.find((x: any) => x[0] === subIdentities[0])![1].toHuman();
+ return [
+ encodeAddress(identityAccount, ss58), [
+ deposit,
+ subIdentities.map((sub: string) => [
+ encodeAddress(sub, ss58),
+ supers.find((sup: any) => sup[0] === sub)![1].toJSON()[1],
+ ]),
+ ],
+ ];
+}
+
+async function getSubs(helper: ChainHelperBase) {
+ return (await helper.getApi().query.identity.subsOf.entries()).map(([key, value]) => [extractAccountId(key), value as any]);
+}
+
+async function getSupers(helper: ChainHelperBase) {
+ return (await helper.getApi().query.identity.superOf.entries()).map(([key, value]) => [extractAccountId(key), value as any]);
+}
+
+// The utility for pulling identity and sub-identity data
const forceInsertIdentities = async (): Promise<void> => {
const identitiesOnRelay: any[] = [];
+ const subsOnRelay: any[] = [];
const identitiesToRemove: string[] = [];
await usingPlaygrounds(async helper => {
try {
// iterate over every identity
- for(const [key, v] of await helper.getApi().query.identity.identityOf.entries()) {
- const value = v as any;
- if (value.isNone) {
- // in the nigh-impossible case that storage map would actually give None for a value, might as well delete it
- identitiesToRemove.push((key as any).toHuman()[0]);
- continue;
- }
-
+ for(const [key, value] of await getIdentities(helper, (key, _value) => identitiesToRemove.push((key as any).toHuman()[0]))) {
// if any of the judgements resulted in a good confirmed outcome, keep this identity
- if (value.unwrap().toHuman().judgements.filter((x: any) => x[1] == 'Reasonable' || x[1] == 'KnownGood').length == 0) continue;
- identitiesOnRelay.push(extractIdentity(key, value));
+ if (value.toHuman().judgements.filter((x: any) => x[1] == 'Reasonable' || x[1] == 'KnownGood').length == 0) continue;
+ identitiesOnRelay.push([key, value]);
+ }
+
+ const sublessIdentities = [...identitiesOnRelay];
+ const supersOfSubs = await getSupers(helper);
+
+ // iterate over every sub-identity
+ for(const [key, value] of await getSubs(helper)) {
+ // only get subs of the identities interesting to us
+ const identityIndex = sublessIdentities.findIndex((x: any) => x[0] == key);
+ if (identityIndex == -1) continue;
+ sublessIdentities.splice(identityIndex, 1);
+ subsOnRelay.push(constructSubInfo(key, value, supersOfSubs));
}
+
+ // mark the rest of sub-identities for deletion with empty arrays
+ /*for(const [account, _identity] of sublessIdentities) {
+ subsOnRelay.push([account, ['0', []]]);
+ }*/
} catch (error) {
console.error(error);
throw Error('Error during fetching identities');
@@ -60,7 +108,7 @@
const identity = paraIdentities.find(i => i[0] === encodedKey);
if (identity) {
// only update if the identity info does not exist or is changed
- if (value.toString() === identity[1].toString()) {
+ if (JSON.stringify(value) === JSON.stringify(identity[1])) {
continue;
}
}
@@ -71,11 +119,36 @@
// identitiesToRemove.push((key as any).toHuman()[0]);
}
- // await helper.getSudo().executeExtrinsic(superuser, 'api.tx.identity.forceRemoveIdentities', [identitiesToRemove]);
- await helper.getSudo().executeExtrinsic(superuser, 'api.tx.identity.forceInsertIdentities', [identitiesToAdd]);
- console.log(`Tried to upload ${identitiesToAdd.length} identities `
- + `and found ${identitiesToRemove.length} identities for potential removal. `
- + `Now there are ${(await helper.getApi().query.identity.identityOf.keys()).length}.`);
+ const paraSubs = await getSubs(helper);
+ const supersOfSubs = await getSupers(helper);
+ const subsToUpdate: any[] = [];
+
+ if (identitiesToRemove.length != 0)
+ await helper.getSudo().executeExtrinsic(superuser, 'api.tx.identity.forceRemoveIdentities', [identitiesToRemove]);
+ if (identitiesToAdd.length != 0)
+ await helper.getSudo().executeExtrinsic(superuser, 'api.tx.identity.forceInsertIdentities', [identitiesToAdd]);
+
+ console.log(`Tried to upload ${identitiesToAdd.length} identities`
+ + ` and found ${identitiesToRemove.length} identities for potential removal.`
+ + ` Now there are ${(await helper.getApi().query.identity.identityOf.keys()).length}.`);
+
+ for (const [key, value] of subsOnRelay) {
+ const encodedKey = encodeAddress(key, ss58Format);
+ const sub = paraSubs.find(i => i[0] === encodedKey);
+ if (sub) {
+ // only update if the sub-identity info does not exist or is changed
+ if (JSON.stringify(value) === JSON.stringify(constructSubInfo(sub[0], sub[1], supersOfSubs)[1])) {
+ continue;
+ }
+ }
+ subsToUpdate.push([key, value]);
+ }
+
+ if (subsToUpdate.length != 0)
+ await helper.getSudo().executeExtrinsic(superuser, 'api.tx.identity.forceSetSubs', [subsToUpdate]);
+
+ console.log(`Also tried to update ${subsToUpdate.length} identities with their sub-identities.`
+ + ` Now there are ${(await helper.getApi().query.identity.subsOf.keys()).length} identities with subs.`);
} catch (error) {
console.error(error);
throw Error('Error during setting identities');