Run cargo fmt on the whole code base (#9394)

* Run cargo fmt on the whole code base

* Second run

* Add CI check

* Fix compilation

* More unnecessary braces

* Handle weights

* Use --all

* Use correct attributes...

* Fix UI tests

* AHHHHHHHHH

* 🤦

* Docs

* Fix compilation

* 🤷

* Please stop

* 🤦 x 2

* More

* make rustfmt.toml consistent with polkadot

Co-authored-by: André Silva <andrerfosilva@gmail.com>
This commit is contained in:
Bastian Köcher
2021-07-21 16:32:32 +02:00
committed by GitHub
parent d451c38c1c
commit 7b56ab15b4
1010 changed files with 53339 additions and 51208 deletions
+26 -16
View File
@@ -21,11 +21,11 @@
use super::*;
use frame_system::RawOrigin;
use frame_benchmarking::{benchmarks, account, whitelisted_caller, impl_benchmark_test_suite};
use sp_runtime::traits::Bounded;
use frame_support::{ensure, traits::Get};
use crate::Pallet as Identity;
use frame_benchmarking::{account, benchmarks, impl_benchmark_test_suite, whitelisted_caller};
use frame_support::{ensure, traits::Get};
use frame_system::RawOrigin;
use sp_runtime::traits::Bounded;
const SEED: u32 = 0;
@@ -39,11 +39,19 @@ fn add_registrars<T: Config>(r: u32) -> Result<(), &'static str> {
let registrar: T::AccountId = account("registrar", i, SEED);
let _ = T::Currency::make_free_balance_be(&registrar, BalanceOf::<T>::max_value());
Identity::<T>::add_registrar(RawOrigin::Root.into(), registrar.clone())?;
Identity::<T>::set_fee(RawOrigin::Signed(registrar.clone()).into(), i.into(), 10u32.into())?;
let fields = IdentityFields(
IdentityField::Display | IdentityField::Legal | IdentityField::Web | IdentityField::Riot
| IdentityField::Email | IdentityField::PgpFingerprint | IdentityField::Image | IdentityField::Twitter
);
Identity::<T>::set_fee(
RawOrigin::Signed(registrar.clone()).into(),
i.into(),
10u32.into(),
)?;
let fields =
IdentityFields(
IdentityField::Display |
IdentityField::Legal | IdentityField::Web |
IdentityField::Riot | IdentityField::Email |
IdentityField::PgpFingerprint |
IdentityField::Image | IdentityField::Twitter,
);
Identity::<T>::set_fields(RawOrigin::Signed(registrar.clone()).into(), i.into(), fields)?;
}
@@ -53,7 +61,10 @@ fn add_registrars<T: Config>(r: u32) -> Result<(), &'static str> {
// Create `s` sub-accounts for the identity of `who` and return them.
// Each will have 32 bytes of raw data added to it.
fn create_sub_accounts<T: Config>(who: &T::AccountId, s: u32) -> Result<Vec<(T::AccountId, Data)>, &'static str> {
fn create_sub_accounts<T: Config>(
who: &T::AccountId,
s: u32,
) -> Result<Vec<(T::AccountId, Data)>, &'static str> {
let mut subs = Vec::new();
let who_origin = RawOrigin::Signed(who.clone());
let data = Data::Raw(vec![0; 32].try_into().unwrap());
@@ -73,7 +84,10 @@ fn create_sub_accounts<T: Config>(who: &T::AccountId, s: u32) -> Result<Vec<(T::
// Adds `s` sub-accounts to the identity of `who`. Each will have 32 bytes of raw data added to it.
// This additionally returns the vector of sub-accounts so it can be modified if needed.
fn add_sub_accounts<T: Config>(who: &T::AccountId, s: u32) -> Result<Vec<(T::AccountId, Data)>, &'static str> {
fn add_sub_accounts<T: Config>(
who: &T::AccountId,
s: u32,
) -> Result<Vec<(T::AccountId, Data)>, &'static str> {
let who_origin = RawOrigin::Signed(who.clone());
let subs = create_sub_accounts::<T>(who, s)?;
@@ -399,8 +413,4 @@ benchmarks! {
}
impl_benchmark_test_suite!(
Identity,
crate::tests::new_test_ext(),
crate::tests::Test,
);
impl_benchmark_test_suite!(Identity, crate::tests::new_test_ext(), crate::tests::Test,);
+148 -86
View File
@@ -72,32 +72,34 @@
#![cfg_attr(not(feature = "std"), no_std)]
mod benchmarking;
#[cfg(test)]
mod tests;
mod types;
mod benchmarking;
pub mod weights;
use sp_std::prelude::*;
use sp_std::convert::TryInto;
use sp_runtime::traits::{StaticLookup, Zero, AppendZerosInput, Saturating};
use frame_support::traits::{BalanceStatus, Currency, OnUnbalanced, ReservableCurrency};
use sp_runtime::traits::{AppendZerosInput, Saturating, StaticLookup, Zero};
use sp_std::{convert::TryInto, prelude::*};
pub use weights::WeightInfo;
pub use pallet::*;
pub use types::{
Data, IdentityField, IdentityFields, IdentityInfo, Judgement, RegistrarIndex,
RegistrarInfo, Registration,
Data, IdentityField, IdentityFields, IdentityInfo, Judgement, RegistrarIndex, RegistrarInfo,
Registration,
};
type BalanceOf<T> = <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
type NegativeImbalanceOf<T> = <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::NegativeImbalance;
type BalanceOf<T> =
<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
type NegativeImbalanceOf<T> = <<T as Config>::Currency as Currency<
<T as frame_system::Config>::AccountId,
>>::NegativeImbalance;
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
use super::*;
#[pallet::config]
pub trait Config: frame_system::Config {
@@ -121,7 +123,6 @@ pub mod pallet {
#[pallet::constant]
type SubAccountDeposit: Get<BalanceOf<Self>>;
/// The maximum number of sub-accounts allowed per identified account.
#[pallet::constant]
type MaxSubAccounts: Get<u32>;
@@ -171,13 +172,8 @@ pub mod pallet {
/// context. If the account is not some other account's sub-identity, then just `None`.
#[pallet::storage]
#[pallet::getter(fn super_of)]
pub(super) type SuperOf<T: Config> = StorageMap<
_,
Blake2_128Concat,
T::AccountId,
(T::AccountId, Data),
OptionQuery,
>;
pub(super) type SuperOf<T: Config> =
StorageMap<_, Blake2_128Concat, T::AccountId, (T::AccountId, Data), OptionQuery>;
/// Alternative "sub" identities of this account.
///
@@ -239,7 +235,7 @@ pub mod pallet {
/// Sender is not a sub-account.
NotSub,
/// Sub-account isn't owned by sender.
NotOwned
NotOwned,
}
#[pallet::event]
@@ -290,17 +286,23 @@ pub mod pallet {
/// - One event.
/// # </weight>
#[pallet::weight(T::WeightInfo::add_registrar(T::MaxRegistrars::get()))]
pub fn add_registrar(origin: OriginFor<T>, account: T::AccountId) -> DispatchResultWithPostInfo {
pub fn add_registrar(
origin: OriginFor<T>,
account: T::AccountId,
) -> DispatchResultWithPostInfo {
T::RegistrarOrigin::ensure_origin(origin)?;
let (i, registrar_count) = <Registrars<T>>::try_mutate(
|registrars| -> Result<(RegistrarIndex, usize), DispatchError> {
registrars.try_push(Some(RegistrarInfo {
account, fee: Zero::zero(), fields: Default::default()
}))
.map_err(|_| Error::<T>::TooManyRegistrars)?;
registrars
.try_push(Some(RegistrarInfo {
account,
fee: Zero::zero(),
fields: Default::default(),
}))
.map_err(|_| Error::<T>::TooManyRegistrars)?;
Ok(((registrars.len() - 1) as RegistrarIndex, registrars.len()))
}
},
)?;
Self::deposit_event(Event::RegistrarAdded(i));
@@ -331,7 +333,10 @@ pub mod pallet {
T::MaxRegistrars::get().into(), // R
T::MaxAdditionalFields::get().into(), // X
))]
pub fn set_identity(origin: OriginFor<T>, info: IdentityInfo<T::MaxAdditionalFields>) -> DispatchResultWithPostInfo {
pub fn set_identity(
origin: OriginFor<T>,
info: IdentityInfo<T::MaxAdditionalFields>,
) -> DispatchResultWithPostInfo {
let sender = ensure_signed(origin)?;
let extra_fields = info.additional.len() as u32;
ensure!(extra_fields <= T::MaxAdditionalFields::get(), Error::<T>::TooManyFields);
@@ -343,8 +348,9 @@ pub mod pallet {
id.judgements.retain(|j| j.1.is_sticky());
id.info = info;
id
}
None => Registration { info, judgements: BoundedVec::default(), deposit: Zero::zero() },
},
None =>
Registration { info, judgements: BoundedVec::default(), deposit: Zero::zero() },
};
let old_deposit = id.deposit;
@@ -363,8 +369,9 @@ pub mod pallet {
Ok(Some(T::WeightInfo::set_identity(
judgements as u32, // R
extra_fields // X
)).into())
extra_fields, // X
))
.into())
}
/// Set the sub-accounts of the sender.
@@ -397,15 +404,22 @@ pub mod pallet {
#[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.
)]
pub fn set_subs(origin: OriginFor<T>, subs: Vec<(T::AccountId, Data)>) -> DispatchResultWithPostInfo {
pub fn set_subs(
origin: OriginFor<T>,
subs: Vec<(T::AccountId, Data)>,
) -> DispatchResultWithPostInfo {
let sender = ensure_signed(origin)?;
ensure!(<IdentityOf<T>>::contains_key(&sender), Error::<T>::NotFound);
ensure!(subs.len() <= T::MaxSubAccounts::get() as usize, Error::<T>::TooManySubAccounts);
ensure!(
subs.len() <= T::MaxSubAccounts::get() as usize,
Error::<T>::TooManySubAccounts
);
let (old_deposit, old_ids) = <SubsOf<T>>::get(&sender);
let new_deposit = T::SubAccountDeposit::get() * <BalanceOf<T>>::from(subs.len() as u32);
let not_other_sub = subs.iter().filter_map(|i| SuperOf::<T>::get(&i.0)).all(|i| &i.0 == &sender);
let not_other_sub =
subs.iter().filter_map(|i| SuperOf::<T>::get(&i.0)).all(|i| &i.0 == &sender);
ensure!(not_other_sub, Error::<T>::AlreadyClaimed);
if old_deposit < new_deposit {
@@ -434,8 +448,9 @@ pub mod pallet {
Ok(Some(
T::WeightInfo::set_subs_old(old_ids.len() as u32) // P: Real number of old accounts removed.
.saturating_add(T::WeightInfo::set_subs_new(new_subs as u32)) // S: New subs added.
).into())
.saturating_add(T::WeightInfo::set_subs_new(new_subs as u32)), /* S: New subs added. */
)
.into())
}
/// Clear an account's identity info and all sub-accounts and return all deposits.
@@ -477,10 +492,11 @@ pub mod pallet {
Self::deposit_event(Event::IdentityCleared(sender, deposit));
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
)).into())
id.judgements.len() as u32, // R
sub_ids.len() as u32, // S
id.info.additional.len() as u32, // X
))
.into())
}
/// Request a judgement from a registrar.
@@ -510,28 +526,30 @@ pub mod pallet {
T::MaxRegistrars::get().into(), // R
T::MaxAdditionalFields::get().into(), // X
))]
pub fn request_judgement(origin: OriginFor<T>,
pub fn request_judgement(
origin: OriginFor<T>,
#[pallet::compact] reg_index: RegistrarIndex,
#[pallet::compact] max_fee: BalanceOf<T>,
) -> DispatchResultWithPostInfo {
let sender = ensure_signed(origin)?;
let registrars = <Registrars<T>>::get();
let registrar = registrars.get(reg_index as usize).and_then(Option::as_ref)
let registrar = registrars
.get(reg_index as usize)
.and_then(Option::as_ref)
.ok_or(Error::<T>::EmptyIndex)?;
ensure!(max_fee >= registrar.fee, Error::<T>::FeeChanged);
let mut id = <IdentityOf<T>>::get(&sender).ok_or(Error::<T>::NoIdentity)?;
let item = (reg_index, Judgement::FeePaid(registrar.fee));
match id.judgements.binary_search_by_key(&reg_index, |x| x.0) {
Ok(i) => if id.judgements[i].1.is_sticky() {
Err(Error::<T>::StickyJudgement)?
} else {
id.judgements[i] = item
},
Err(i) => id
.judgements
.try_insert(i, item)
.map_err(|_| Error::<T>::TooManyRegistrars)?,
Ok(i) =>
if id.judgements[i].1.is_sticky() {
Err(Error::<T>::StickyJudgement)?
} else {
id.judgements[i] = item
},
Err(i) =>
id.judgements.try_insert(i, item).map_err(|_| Error::<T>::TooManyRegistrars)?,
}
T::Currency::reserve(&sender, registrar.fee)?;
@@ -542,10 +560,8 @@ pub mod pallet {
Self::deposit_event(Event::JudgementRequested(sender, reg_index));
Ok(Some(T::WeightInfo::request_judgement(
judgements as u32,
extra_fields as u32,
)).into())
Ok(Some(T::WeightInfo::request_judgement(judgements as u32, extra_fields as u32))
.into())
}
/// Cancel a previous request.
@@ -569,11 +585,16 @@ pub mod pallet {
T::MaxRegistrars::get().into(), // R
T::MaxAdditionalFields::get().into(), // X
))]
pub fn cancel_request(origin: OriginFor<T>, reg_index: RegistrarIndex) -> DispatchResultWithPostInfo {
pub fn cancel_request(
origin: OriginFor<T>,
reg_index: RegistrarIndex,
) -> DispatchResultWithPostInfo {
let sender = ensure_signed(origin)?;
let mut id = <IdentityOf<T>>::get(&sender).ok_or(Error::<T>::NoIdentity)?;
let pos = id.judgements.binary_search_by_key(&reg_index, |x| x.0)
let pos = id
.judgements
.binary_search_by_key(&reg_index, |x| x.0)
.map_err(|_| Error::<T>::NotFound)?;
let fee = if let Judgement::FeePaid(fee) = id.judgements.remove(pos).1 {
fee
@@ -589,10 +610,7 @@ pub mod pallet {
Self::deposit_event(Event::JudgementUnrequested(sender, reg_index));
Ok(Some(T::WeightInfo::cancel_request(
judgements as u32,
extra_fields as u32
)).into())
Ok(Some(T::WeightInfo::cancel_request(judgements as u32, extra_fields as u32)).into())
}
/// Set the fee required for a judgement to be requested from a registrar.
@@ -609,7 +627,8 @@ pub mod pallet {
/// - Benchmark: 7.315 + R * 0.329 µs (min squares analysis)
/// # </weight>
#[pallet::weight(T::WeightInfo::set_fee(T::MaxRegistrars::get()))] // R
pub fn set_fee(origin: OriginFor<T>,
pub fn set_fee(
origin: OriginFor<T>,
#[pallet::compact] index: RegistrarIndex,
#[pallet::compact] fee: BalanceOf<T>,
) -> DispatchResultWithPostInfo {
@@ -618,7 +637,14 @@ pub mod pallet {
let registrars = <Registrars<T>>::mutate(|rs| -> Result<usize, DispatchError> {
rs.get_mut(index as usize)
.and_then(|x| x.as_mut())
.and_then(|r| if r.account == who { r.fee = fee; Some(()) } else { None })
.and_then(|r| {
if r.account == who {
r.fee = fee;
Some(())
} else {
None
}
})
.ok_or_else(|| DispatchError::from(Error::<T>::InvalidIndex))?;
Ok(rs.len())
})?;
@@ -639,7 +665,8 @@ pub mod pallet {
/// - Benchmark: 8.823 + R * 0.32 µs (min squares analysis)
/// # </weight>
#[pallet::weight(T::WeightInfo::set_account_id(T::MaxRegistrars::get()))] // R
pub fn set_account_id(origin: OriginFor<T>,
pub fn set_account_id(
origin: OriginFor<T>,
#[pallet::compact] index: RegistrarIndex,
new: T::AccountId,
) -> DispatchResultWithPostInfo {
@@ -648,7 +675,14 @@ pub mod pallet {
let registrars = <Registrars<T>>::mutate(|rs| -> Result<usize, DispatchError> {
rs.get_mut(index as usize)
.and_then(|x| x.as_mut())
.and_then(|r| if r.account == who { r.account = new; Some(()) } else { None })
.and_then(|r| {
if r.account == who {
r.account = new;
Some(())
} else {
None
}
})
.ok_or_else(|| DispatchError::from(Error::<T>::InvalidIndex))?;
Ok(rs.len())
})?;
@@ -669,7 +703,8 @@ pub mod pallet {
/// - Benchmark: 7.464 + R * 0.325 µs (min squares analysis)
/// # </weight>
#[pallet::weight(T::WeightInfo::set_fields(T::MaxRegistrars::get()))] // R
pub fn set_fields(origin: OriginFor<T>,
pub fn set_fields(
origin: OriginFor<T>,
#[pallet::compact] index: RegistrarIndex,
fields: IdentityFields,
) -> DispatchResultWithPostInfo {
@@ -678,13 +713,21 @@ pub mod pallet {
let registrars = <Registrars<T>>::mutate(|rs| -> Result<usize, DispatchError> {
rs.get_mut(index as usize)
.and_then(|x| x.as_mut())
.and_then(|r| if r.account == who { r.fields = fields; Some(()) } else { None })
.and_then(|r| {
if r.account == who {
r.fields = fields;
Some(())
} else {
None
}
})
.ok_or_else(|| DispatchError::from(Error::<T>::InvalidIndex))?;
Ok(rs.len())
})?;
Ok(Some(T::WeightInfo::set_fields(
registrars as u32 // R
)).into())
registrars as u32, // R
))
.into())
}
/// Provide a judgement for an account's identity.
@@ -710,7 +753,8 @@ pub mod pallet {
T::MaxRegistrars::get().into(), // R
T::MaxAdditionalFields::get().into(), // X
))]
pub fn provide_judgement(origin: OriginFor<T>,
pub fn provide_judgement(
origin: OriginFor<T>,
#[pallet::compact] reg_index: RegistrarIndex,
target: <T::Lookup as StaticLookup>::Source,
judgement: Judgement<BalanceOf<T>>,
@@ -729,10 +773,15 @@ pub mod pallet {
match id.judgements.binary_search_by_key(&reg_index, |x| x.0) {
Ok(position) => {
if let Judgement::FeePaid(fee) = id.judgements[position].1 {
let _ = T::Currency::repatriate_reserved(&target, &sender, fee, BalanceStatus::Free);
let _ = T::Currency::repatriate_reserved(
&target,
&sender,
fee,
BalanceStatus::Free,
);
}
id.judgements[position] = item
}
},
Err(position) => id
.judgements
.try_insert(position, item)
@@ -744,10 +793,8 @@ pub mod pallet {
<IdentityOf<T>>::insert(&target, id);
Self::deposit_event(Event::JudgementGiven(target, reg_index));
Ok(Some(T::WeightInfo::provide_judgement(
judgements as u32,
extra_fields as u32,
)).into())
Ok(Some(T::WeightInfo::provide_judgement(judgements as u32, extra_fields as u32))
.into())
}
/// Remove an account's identity and sub-account information and slash the deposits.
@@ -775,7 +822,8 @@ pub mod pallet {
T::MaxAdditionalFields::get().into(), // X
))]
pub fn kill_identity(
origin: OriginFor<T>, target: <T::Lookup as StaticLookup>::Source
origin: OriginFor<T>,
target: <T::Lookup as StaticLookup>::Source,
) -> DispatchResultWithPostInfo {
T::ForceOrigin::ensure_origin(origin)?;
@@ -794,10 +842,11 @@ pub mod pallet {
Self::deposit_event(Event::IdentityKilled(target, deposit));
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
)).into())
id.judgements.len() as u32, // R
sub_ids.len() as u32, // S
id.info.additional.len() as u32, // X
))
.into())
}
/// Add the given account to the sender's subs.
@@ -808,7 +857,11 @@ pub mod pallet {
/// The dispatch origin for this call must be _Signed_ and the sender must have a registered
/// sub identity of `sub`.
#[pallet::weight(T::WeightInfo::add_sub(T::MaxSubAccounts::get()))]
pub fn add_sub(origin: OriginFor<T>, sub: <T::Lookup as StaticLookup>::Source, data: Data) -> DispatchResult {
pub fn add_sub(
origin: OriginFor<T>,
sub: <T::Lookup as StaticLookup>::Source,
data: Data,
) -> DispatchResult {
let sender = ensure_signed(origin)?;
let sub = T::Lookup::lookup(sub)?;
ensure!(IdentityOf::<T>::contains_key(&sender), Error::<T>::NoIdentity);
@@ -818,7 +871,10 @@ pub mod pallet {
SubsOf::<T>::try_mutate(&sender, |(ref mut subs_deposit, ref mut sub_ids)| {
// Ensure there is space and that the deposit is paid.
ensure!(sub_ids.len() < T::MaxSubAccounts::get() as usize, Error::<T>::TooManySubAccounts);
ensure!(
sub_ids.len() < T::MaxSubAccounts::get() as usize,
Error::<T>::TooManySubAccounts
);
let deposit = T::SubAccountDeposit::get();
T::Currency::reserve(&sender, deposit)?;
@@ -837,7 +893,9 @@ pub mod pallet {
/// sub identity of `sub`.
#[pallet::weight(T::WeightInfo::rename_sub(T::MaxSubAccounts::get()))]
pub fn rename_sub(
origin: OriginFor<T>, sub: <T::Lookup as StaticLookup>::Source, data: Data
origin: OriginFor<T>,
sub: <T::Lookup as StaticLookup>::Source,
data: Data,
) -> DispatchResult {
let sender = ensure_signed(origin)?;
let sub = T::Lookup::lookup(sub)?;
@@ -855,7 +913,10 @@ pub mod pallet {
/// The dispatch origin for this call must be _Signed_ and the sender must have a registered
/// sub identity of `sub`.
#[pallet::weight(T::WeightInfo::remove_sub(T::MaxSubAccounts::get()))]
pub fn remove_sub(origin: OriginFor<T>, sub: <T::Lookup as StaticLookup>::Source) -> DispatchResult {
pub fn remove_sub(
origin: OriginFor<T>,
sub: <T::Lookup as StaticLookup>::Source,
) -> DispatchResult {
let sender = ensure_signed(origin)?;
ensure!(IdentityOf::<T>::contains_key(&sender), Error::<T>::NoIdentity);
let sub = T::Lookup::lookup(sub)?;
@@ -891,19 +952,20 @@ pub mod pallet {
sub_ids.retain(|x| x != &sender);
let deposit = T::SubAccountDeposit::get().min(*subs_deposit);
*subs_deposit -= deposit;
let _ = T::Currency::repatriate_reserved(&sup, &sender, deposit, BalanceStatus::Free);
let _ =
T::Currency::repatriate_reserved(&sup, &sender, deposit, BalanceStatus::Free);
Self::deposit_event(Event::SubIdentityRevoked(sender, sup.clone(), deposit));
});
Ok(())
}
}
}
impl<T: Config> Pallet<T> {
/// Get the subs of an account.
pub fn subs(who: &T::AccountId) -> Vec<(T::AccountId, Data)> {
SubsOf::<T>::get(who).1
SubsOf::<T>::get(who)
.1
.into_iter()
.filter_map(|a| SuperOf::<T>::get(&a).map(|x| (a, x.1)))
.collect()
+75 -47
View File
@@ -20,13 +20,13 @@
use super::*;
use crate as pallet_identity;
use codec::{Encode, Decode};
use sp_runtime::traits::BadOrigin;
use frame_support::{assert_ok, assert_noop, parameter_types, ord_parameter_types, BoundedVec};
use codec::{Decode, Encode};
use frame_support::{assert_noop, assert_ok, ord_parameter_types, parameter_types, BoundedVec};
use frame_system::{EnsureOneOf, EnsureRoot, EnsureSignedBy};
use sp_core::H256;
use frame_system::{EnsureSignedBy, EnsureOneOf, EnsureRoot};
use sp_runtime::{
testing::Header, traits::{BlakeTwo256, IdentityLookup},
testing::Header,
traits::{BadOrigin, BlakeTwo256, IdentityLookup},
};
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
@@ -100,16 +100,8 @@ ord_parameter_types! {
pub const One: u64 = 1;
pub const Two: u64 = 2;
}
type EnsureOneOrRoot = EnsureOneOf<
u64,
EnsureRoot<u64>,
EnsureSignedBy<One, u64>
>;
type EnsureTwoOrRoot = EnsureOneOf<
u64,
EnsureRoot<u64>,
EnsureSignedBy<Two, u64>
>;
type EnsureOneOrRoot = EnsureOneOf<u64, EnsureRoot<u64>, EnsureSignedBy<One, u64>>;
type EnsureTwoOrRoot = EnsureOneOf<u64, EnsureRoot<u64>, EnsureSignedBy<Two, u64>>;
impl pallet_identity::Config for Test {
type Event = Event;
type Currency = Balances;
@@ -128,15 +120,10 @@ impl pallet_identity::Config for Test {
pub fn new_test_ext() -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
pallet_balances::GenesisConfig::<Test> {
balances: vec![
(1, 10),
(2, 10),
(3, 10),
(10, 100),
(20, 100),
(30, 100),
],
}.assimilate_storage(&mut t).unwrap();
balances: vec![(1, 10), (2, 10), (3, 10), (10, 100), (20, 100), (30, 100)],
}
.assimilate_storage(&mut t)
.unwrap();
t.into()
}
@@ -144,7 +131,7 @@ fn ten() -> IdentityInfo<MaxAdditionalFields> {
IdentityInfo {
display: Data::Raw(b"ten".to_vec().try_into().unwrap()),
legal: Data::Raw(b"The Right Ordinal Ten, Esq.".to_vec().try_into().unwrap()),
.. Default::default()
..Default::default()
}
}
@@ -152,7 +139,7 @@ fn twenty() -> IdentityInfo<MaxAdditionalFields> {
IdentityInfo {
display: Data::Raw(b"twenty".to_vec().try_into().unwrap()),
legal: Data::Raw(b"The Right Ordinal Twenty, Esq.".to_vec().try_into().unwrap()),
.. Default::default()
..Default::default()
}
}
@@ -177,7 +164,10 @@ fn editing_subaccounts_should_work() {
assert_eq!(Balances::free_balance(10), 70);
// third sub account is too many
assert_noop!(Identity::add_sub(Origin::signed(10), 3, data(3)), Error::<Test>::TooManySubAccounts);
assert_noop!(
Identity::add_sub(Origin::signed(10), 3, data(3)),
Error::<Test>::TooManySubAccounts
);
// rename first sub account
assert_ok!(Identity::rename_sub(Origin::signed(10), 1, data(11)));
@@ -214,7 +204,10 @@ fn resolving_subaccount_ownership_works() {
assert_eq!(Balances::free_balance(10), 80);
assert_eq!(Balances::reserved_balance(10), 20);
// 20 cannot claim 1 now
assert_noop!(Identity::add_sub(Origin::signed(20), 1, data(1)), Error::<Test>::AlreadyClaimed);
assert_noop!(
Identity::add_sub(Origin::signed(20), 1, data(1)),
Error::<Test>::AlreadyClaimed
);
// 1 wants to be with 20 so it quits from 10
assert_ok!(Identity::quit_sub(Origin::signed(1)));
// 1 gets the 10 that 10 paid.
@@ -243,9 +236,10 @@ fn adding_registrar_should_work() {
assert_ok!(Identity::set_fee(Origin::signed(3), 0, 10));
let fields = IdentityFields(IdentityField::Display | IdentityField::Legal);
assert_ok!(Identity::set_fields(Origin::signed(3), 0, fields));
assert_eq!(Identity::registrars(), vec![
Some(RegistrarInfo { account: 3, fee: 10, fields })
]);
assert_eq!(
Identity::registrars(),
vec![Some(RegistrarInfo { account: 3, fee: 10, fields })]
);
});
}
@@ -370,7 +364,10 @@ fn setting_subaccounts_should_work() {
assert_eq!(Identity::super_of(40), None);
subs.push((20, Data::Raw(vec![40; 1].try_into().unwrap())));
assert_noop!(Identity::set_subs(Origin::signed(10), subs.clone()), Error::<Test>::TooManySubAccounts);
assert_noop!(
Identity::set_subs(Origin::signed(10), subs.clone()),
Error::<Test>::TooManySubAccounts
);
});
}
@@ -378,7 +375,10 @@ fn setting_subaccounts_should_work() {
fn clearing_account_should_remove_subaccounts_and_refund() {
new_test_ext().execute_with(|| {
assert_ok!(Identity::set_identity(Origin::signed(10), ten()));
assert_ok!(Identity::set_subs(Origin::signed(10), vec![(20, Data::Raw(vec![40; 1].try_into().unwrap()))]));
assert_ok!(Identity::set_subs(
Origin::signed(10),
vec![(20, Data::Raw(vec![40; 1].try_into().unwrap()))]
));
assert_ok!(Identity::clear_identity(Origin::signed(10)));
assert_eq!(Balances::free_balance(10), 100);
assert!(Identity::super_of(20).is_none());
@@ -389,7 +389,10 @@ fn clearing_account_should_remove_subaccounts_and_refund() {
fn killing_account_should_remove_subaccounts_and_not_refund() {
new_test_ext().execute_with(|| {
assert_ok!(Identity::set_identity(Origin::signed(10), ten()));
assert_ok!(Identity::set_subs(Origin::signed(10), vec![(20, Data::Raw(vec![40; 1].try_into().unwrap()))]));
assert_ok!(Identity::set_subs(
Origin::signed(10),
vec![(20, Data::Raw(vec![40; 1].try_into().unwrap()))]
));
assert_ok!(Identity::kill_identity(Origin::signed(2), 10));
assert_eq!(Balances::free_balance(10), 80);
assert!(Identity::super_of(20).is_none());
@@ -409,7 +412,10 @@ fn cancelling_requested_judgement_should_work() {
assert_noop!(Identity::cancel_request(Origin::signed(10), 0), Error::<Test>::NotFound);
assert_ok!(Identity::provide_judgement(Origin::signed(3), 0, 10, Judgement::Reasonable));
assert_noop!(Identity::cancel_request(Origin::signed(10), 0), Error::<Test>::JudgementGiven);
assert_noop!(
Identity::cancel_request(Origin::signed(10), 0),
Error::<Test>::JudgementGiven
);
});
}
@@ -419,19 +425,28 @@ fn requesting_judgement_should_work() {
assert_ok!(Identity::add_registrar(Origin::signed(1), 3));
assert_ok!(Identity::set_fee(Origin::signed(3), 0, 10));
assert_ok!(Identity::set_identity(Origin::signed(10), ten()));
assert_noop!(Identity::request_judgement(Origin::signed(10), 0, 9), Error::<Test>::FeeChanged);
assert_noop!(
Identity::request_judgement(Origin::signed(10), 0, 9),
Error::<Test>::FeeChanged
);
assert_ok!(Identity::request_judgement(Origin::signed(10), 0, 10));
// 10 for the judgement request, 10 for the identity.
assert_eq!(Balances::free_balance(10), 80);
// Re-requesting won't work as we already paid.
assert_noop!(Identity::request_judgement(Origin::signed(10), 0, 10), Error::<Test>::StickyJudgement);
assert_noop!(
Identity::request_judgement(Origin::signed(10), 0, 10),
Error::<Test>::StickyJudgement
);
assert_ok!(Identity::provide_judgement(Origin::signed(3), 0, 10, Judgement::Erroneous));
// Registrar got their payment now.
assert_eq!(Balances::free_balance(3), 20);
// Re-requesting still won't work as it's erroneous.
assert_noop!(Identity::request_judgement(Origin::signed(10), 0, 10), Error::<Test>::StickyJudgement);
assert_noop!(
Identity::request_judgement(Origin::signed(10), 0, 10),
Error::<Test>::StickyJudgement
);
// Requesting from a second registrar still works.
assert_ok!(Identity::add_registrar(Origin::signed(1), 4));
@@ -448,14 +463,24 @@ fn field_deposit_should_work() {
new_test_ext().execute_with(|| {
assert_ok!(Identity::add_registrar(Origin::signed(1), 3));
assert_ok!(Identity::set_fee(Origin::signed(3), 0, 10));
assert_ok!(Identity::set_identity(Origin::signed(10), IdentityInfo {
additional: vec![
(Data::Raw(b"number".to_vec().try_into().unwrap()), Data::Raw(10u32.encode().try_into().unwrap())),
(Data::Raw(b"text".to_vec().try_into().unwrap()), Data::Raw(b"10".to_vec().try_into().unwrap())),
]
.try_into()
.unwrap(), .. Default::default()
}));
assert_ok!(Identity::set_identity(
Origin::signed(10),
IdentityInfo {
additional: vec![
(
Data::Raw(b"number".to_vec().try_into().unwrap()),
Data::Raw(10u32.encode().try_into().unwrap())
),
(
Data::Raw(b"text".to_vec().try_into().unwrap()),
Data::Raw(b"10".to_vec().try_into().unwrap())
),
]
.try_into()
.unwrap(),
..Default::default()
}
));
assert_eq!(Balances::free_balance(10), 70);
});
}
@@ -465,7 +490,10 @@ fn setting_account_id_should_work() {
new_test_ext().execute_with(|| {
assert_ok!(Identity::add_registrar(Origin::signed(1), 3));
// account 4 cannot change the first registrar's identity since it's owned by 3.
assert_noop!(Identity::set_account_id(Origin::signed(4), 0, 3), Error::<Test>::InvalidIndex);
assert_noop!(
Identity::set_account_id(Origin::signed(4), 0, 3),
Error::<Test>::InvalidIndex
);
// account 3 can, because that's the registrar's current account.
assert_ok!(Identity::set_account_id(Origin::signed(3), 0, 4));
// account 4 can now, because that's their new ID.
+41 -40
View File
@@ -15,19 +15,15 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use codec::{Encode, Decode, MaxEncodedLen};
use super::*;
use codec::{Decode, Encode, MaxEncodedLen};
use enumflags2::BitFlags;
use frame_support::{
traits::{ConstU32, Get},
BoundedVec, CloneNoBound, PartialEqNoBound, RuntimeDebugNoBound,
traits::{ConstU32, Get},
BoundedVec, CloneNoBound, PartialEqNoBound, RuntimeDebugNoBound,
};
use sp_std::prelude::*;
use sp_std::{fmt::Debug, iter::once, ops::Add};
use sp_runtime::{
traits::Zero,
RuntimeDebug,
};
use super::*;
use sp_runtime::{traits::Zero, RuntimeDebug};
use sp_std::{fmt::Debug, iter::once, ops::Add, prelude::*};
/// 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.
@@ -58,13 +54,13 @@ impl Decode for Data {
let b = input.read_byte()?;
Ok(match b {
0 => Data::None,
n @ 1 ..= 33 => {
n @ 1..=33 => {
let mut r: BoundedVec<_, _> = vec![0u8; n as usize - 1]
.try_into()
.expect("bound checked in match arm condition; qed");
input.read(&mut r[..])?;
Data::Raw(r)
}
},
34 => Data::BlakeTwo256(<[u8; 32]>::decode(input)?),
35 => Data::Sha256(<[u8; 32]>::decode(input)?),
36 => Data::Keccak256(<[u8; 32]>::decode(input)?),
@@ -83,7 +79,7 @@ impl Encode for Data {
let mut r = vec![l as u8 + 1; l + 1];
r[1..].copy_from_slice(&x[..l as usize]);
r
}
},
Data::BlakeTwo256(ref h) => once(34u8).chain(h.iter().cloned()).collect(),
Data::Sha256(ref h) => once(35u8).chain(h.iter().cloned()).collect(),
Data::Keccak256(ref h) => once(36u8).chain(h.iter().cloned()).collect(),
@@ -107,9 +103,8 @@ pub type RegistrarIndex = u32;
/// NOTE: Registrars may pay little attention to some fields. Registrars may want to make clear
/// which fields their attestation is relevant for by off-chain means.
#[derive(Copy, Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, MaxEncodedLen)]
pub enum Judgement<
Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq
> {
pub enum Judgement<Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq>
{
/// The default value; no opinion is held.
Unknown,
/// No judgement is yet in place, but a deposit is reserved as payment for providing one.
@@ -131,9 +126,9 @@ pub enum Judgement<
Erroneous,
}
impl<
Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq
> Judgement<Balance> {
impl<Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq>
Judgement<Balance>
{
/// Returns `true` if this judgement is indicative of a deposit being currently held. This means
/// it should not be cleared or replaced except by an operation which utilizes the deposit.
pub(crate) fn has_deposit(&self) -> bool {
@@ -159,14 +154,14 @@ impl<
#[repr(u64)]
#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, BitFlags, RuntimeDebug)]
pub enum IdentityField {
Display = 0b0000000000000000000000000000000000000000000000000000000000000001,
Legal = 0b0000000000000000000000000000000000000000000000000000000000000010,
Web = 0b0000000000000000000000000000000000000000000000000000000000000100,
Riot = 0b0000000000000000000000000000000000000000000000000000000000001000,
Email = 0b0000000000000000000000000000000000000000000000000000000000010000,
Display = 0b0000000000000000000000000000000000000000000000000000000000000001,
Legal = 0b0000000000000000000000000000000000000000000000000000000000000010,
Web = 0b0000000000000000000000000000000000000000000000000000000000000100,
Riot = 0b0000000000000000000000000000000000000000000000000000000000001000,
Email = 0b0000000000000000000000000000000000000000000000000000000000010000,
PgpFingerprint = 0b0000000000000000000000000000000000000000000000000000000000100000,
Image = 0b0000000000000000000000000000000000000000000000000000000001000000,
Twitter = 0b0000000000000000000000000000000000000000000000000000000010000000,
Image = 0b0000000000000000000000000000000000000000000000000000000001000000,
Twitter = 0b0000000000000000000000000000000000000000000000000000000010000000,
}
impl MaxEncodedLen for IdentityField {
@@ -202,7 +197,9 @@ impl Decode for IdentityFields {
///
/// 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)]
#[derive(
CloneNoBound, Encode, Decode, Eq, MaxEncodedLen, PartialEqNoBound, RuntimeDebugNoBound,
)]
#[codec(mel_bound(FieldLimit: Get<u32>))]
#[cfg_attr(test, derive(frame_support::DefaultNoBound))]
pub struct IdentityInfo<FieldLimit: Get<u32>> {
@@ -277,23 +274,27 @@ pub struct Registration<
pub info: IdentityInfo<MaxAdditionalFields>,
}
impl <
Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq + Zero + Add,
MaxJudgements: Get<u32>,
MaxAdditionalFields: Get<u32>,
> Registration<Balance, MaxJudgements, MaxAdditionalFields> {
impl<
Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq + Zero + Add,
MaxJudgements: Get<u32>,
MaxAdditionalFields: Get<u32>,
> Registration<Balance, MaxJudgements, MaxAdditionalFields>
{
pub(crate) fn total_deposit(&self) -> Balance {
self.deposit + self.judgements.iter()
.map(|(_, ref j)| if let Judgement::FeePaid(fee) = j { *fee } else { Zero::zero() })
.fold(Zero::zero(), |a, i| a + i)
self.deposit +
self.judgements
.iter()
.map(|(_, ref j)| if let Judgement::FeePaid(fee) = j { *fee } else { Zero::zero() })
.fold(Zero::zero(), |a, i| a + i)
}
}
impl<
Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq,
MaxJudgements: Get<u32>,
MaxAdditionalFields: Get<u32>,
> Decode for Registration<Balance, MaxJudgements, MaxAdditionalFields> {
Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq,
MaxJudgements: Get<u32>,
MaxAdditionalFields: Get<u32>,
> Decode for Registration<Balance, MaxJudgements, MaxAdditionalFields>
{
fn decode<I: codec::Input>(input: &mut I) -> sp_std::result::Result<Self, codec::Error> {
let (judgements, deposit, info) = Decode::decode(&mut AppendZerosInput::new(input))?;
Ok(Self { judgements, deposit, info })
@@ -304,7 +305,7 @@ impl<
#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, MaxEncodedLen)]
pub struct RegistrarInfo<
Balance: Encode + Decode + Clone + Debug + Eq + PartialEq,
AccountId: Encode + Decode + Clone + Debug + Eq + PartialEq
AccountId: Encode + Decode + Clone + Debug + Eq + PartialEq,
> {
/// The account of the registrar.
pub account: AccountId,
+1
View File
@@ -36,6 +36,7 @@
// --template=./.maintain/frame-weight-template.hbs
#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(unused_parens)]
#![allow(unused_imports)]