diff --git a/pallets/core/src/common/policy.rs b/pallets/core/src/common/policy.rs index 58c76e429..57cae0543 100644 --- a/pallets/core/src/common/policy.rs +++ b/pallets/core/src/common/policy.rs @@ -210,7 +210,7 @@ pub trait HasPolicy: Sized { /// /// Returns a mutable reference to the underlying data wrapped into an option if the command is authorized, /// otherwise returns Err. - fn execute_readonly( + fn execute_view( self, f: F, action: A, diff --git a/pallets/core/src/common/signed_action.rs b/pallets/core/src/common/signed_action.rs index c898e57a1..37106e578 100644 --- a/pallets/core/src/common/signed_action.rs +++ b/pallets/core/src/common/signed_action.rs @@ -15,7 +15,7 @@ where /// Verifies signer's signature and nonce, then executes given action providing a reference to the /// value associated with the target. /// In case of a successful result, increases the signer's nonce. - pub fn execute_readonly(self, f: F) -> Result + pub fn execute_view(self, f: F) -> Result where F: FnOnce(A, >::Value, Sig::Signer) -> Result, E: From + From + From>, @@ -32,7 +32,7 @@ where ActionWrapper::::new(action.nonce(), (*signer).clone(), action) .execute_and_increase_nonce(|ActionWrapper { action, .. }, _| { - action.execute_readonly(|action, target_data| f(action, target_data, signer)) + action.execute_view(|action, target_data| f(action, target_data, signer)) }) .map_err(Into::into) } diff --git a/pallets/core/src/modules/accumulator/mod.rs b/pallets/core/src/modules/accumulator/mod.rs index 784af5bdc..25e3b1517 100644 --- a/pallets/core/src/modules/accumulator/mod.rs +++ b/pallets/core/src/modules/accumulator/mod.rs @@ -179,9 +179,7 @@ pub mod pallet { ) -> DispatchResult { ensure_signed(origin)?; - remove - .signed(signature) - .execute_readonly(Self::remove_params_) + remove.signed(signature).execute_view(Self::remove_params_) } #[pallet::weight(SubstrateWeight::::remove_public(remove, signature))] @@ -194,7 +192,7 @@ pub mod pallet { remove .signed(signature) - .execute_readonly(Self::remove_public_key_) + .execute_view(Self::remove_public_key_) } /// Add a new accumulator with the initial accumulated value. Each accumulator has a unique id and it diff --git a/pallets/core/src/modules/offchain_signatures/mod.rs b/pallets/core/src/modules/offchain_signatures/mod.rs index 039a8beb0..89fbabf9c 100644 --- a/pallets/core/src/modules/offchain_signatures/mod.rs +++ b/pallets/core/src/modules/offchain_signatures/mod.rs @@ -159,9 +159,7 @@ pub mod pallet { ) -> DispatchResult { ensure_signed(origin)?; - remove - .signed(signature) - .execute_readonly(Self::remove_params_) + remove.signed(signature).execute_view(Self::remove_params_) } /// Remove existing offchain signature public key. Only the DID controller can remove key and it should use the nonce from the DID module. diff --git a/pallets/core/src/modules/revoke/mod.rs b/pallets/core/src/modules/revoke/mod.rs index 5468a68a8..b44f39ffa 100644 --- a/pallets/core/src/modules/revoke/mod.rs +++ b/pallets/core/src/modules/revoke/mod.rs @@ -226,8 +226,8 @@ pub mod pallet { ) -> DispatchResult { ensure_signed(origin)?; - revoke.execute_readonly(|action, registry: RevocationRegistry| { - registry.execute_readonly(Self::revoke_, action, proof) + revoke.execute_view(|action, registry: RevocationRegistry| { + registry.execute_view(Self::revoke_, action, proof) }) } @@ -248,8 +248,8 @@ pub mod pallet { ) -> DispatchResult { ensure_signed(origin)?; - unrevoke.execute_readonly(|action, registry: RevocationRegistry| { - registry.execute_readonly(Self::unrevoke_, action, proof) + unrevoke.execute_view(|action, registry: RevocationRegistry| { + registry.execute_view(Self::unrevoke_, action, proof) }) } diff --git a/pallets/core/src/modules/revoke/tests.rs b/pallets/core/src/modules/revoke/tests.rs index 024d4b286..6eda5bfb4 100644 --- a/pallets/core/src/modules/revoke/tests.rs +++ b/pallets/core/src/modules/revoke/tests.rs @@ -757,12 +757,11 @@ mod test { let command = &rev; let proof = get_pauth(command, signers); - let res = - command - .clone() - .execute_readonly(|action, registry: RevocationRegistry| { - registry.execute_readonly(|_, _| Ok::<_, DispatchError>(()), action, proof) - }); + let res = command + .clone() + .execute_view(|action, registry: RevocationRegistry| { + registry.execute_view(|_, _| Ok::<_, DispatchError>(()), action, proof) + }); assert_eq!(res.is_ok(), *expect_success); if *expect_success { diff --git a/pallets/core/src/modules/trust_registry/actions.rs b/pallets/core/src/modules/trust_registry/actions.rs index 6c09e62d1..e6d971b26 100644 --- a/pallets/core/src/modules/trust_registry/actions.rs +++ b/pallets/core/src/modules/trust_registry/actions.rs @@ -1,7 +1,7 @@ use super::*; use crate::{ impl_action_with_nonce, - util::{Bytes, KeyedUpdate, Types}, + util::{Bytes, Types}, }; use alloc::{collections::BTreeSet, string::String}; use frame_support::{CloneNoBound, DebugNoBound, EqNoBound, PartialEqNoBound}; @@ -93,7 +93,7 @@ pub struct UpdateDelegatedIssuers { impl_action_with_nonce!( for (): InitOrUpdateTrustRegistry with 1 as len, () as target, - UpdateDelegatedIssuers with delegated.size() as len, () as target + UpdateDelegatedIssuers with 1 as len, () as target ); impl_action_with_nonce!( diff --git a/pallets/core/src/modules/trust_registry/benchmarks.rs b/pallets/core/src/modules/trust_registry/benchmarks.rs index f63aea50f..202d30d62 100644 --- a/pallets/core/src/modules/trust_registry/benchmarks.rs +++ b/pallets/core/src/modules/trust_registry/benchmarks.rs @@ -124,7 +124,7 @@ crate::bench_with_all_pairs! { registry_id: TrustRegistryId(id), schemas: SetOrModify::Modify(schemas.clone().into_iter().map(|(id, schema)| (id, SetOrAddOrRemoveOrModify::Set(schema))).collect()), nonce: 2u32.into() - }.execute_readonly(|action, set| Pallet::::set_schemas_metadata_(action, set, ConvenerOrIssuerOrVerifier(did.into()))).unwrap(); + }.execute_view(|action, set| Pallet::::set_schemas_metadata_(action, set, ConvenerOrIssuerOrVerifier(did.into()))).unwrap(); let update_issuers = schemas.keys().map( |schema_id| { @@ -208,7 +208,7 @@ crate::bench_with_all_pairs! { }; ActionWrapper::::new(1u32.into(), Convener(did.into()), init_or_update_trust_registry.clone()).execute::(|action, set| Pallet::::init_or_update_trust_registry_(action.action, set, Convener(did.into()))).unwrap(); - let delegated = UnboundedDelegatedIssuers((0..i).map(|idx| Issuer(Did([idx as u8; 32]).into())).collect()); + let delegated = UnboundedDelegatedIssuers((0..i).map(|idx| Issuer(Did([idx as u8 + 90; 32]).into())).collect()); for issuer in delegated.iter() { TrustRegistryIssuerSchemas::::insert(init_or_update_trust_registry.registry_id, Issuer(did.into()), IssuerSchemas(Default::default())); @@ -323,7 +323,7 @@ crate::bench_with_all_pairs! { registry_id: TrustRegistryId(id), issuers: issuers.clone().into_iter().collect(), nonce: 1u32.into() - }.execute_readonly::(|action, reg_info| Pallet::::suspend_issuers_(action, reg_info, Convener(did.into()))).unwrap(); + }.execute_view::(|action, reg_info| Pallet::::suspend_issuers_(action, reg_info, Convener(did.into()))).unwrap(); let unsuspend_issuers = UnsuspendIssuers { registry_id: TrustRegistryId(id), diff --git a/pallets/core/src/modules/trust_registry/impl.rs b/pallets/core/src/modules/trust_registry/impl.rs index 7bebf98f5..05b2acb8f 100644 --- a/pallets/core/src/modules/trust_registry/impl.rs +++ b/pallets/core/src/modules/trust_registry/impl.rs @@ -1,5 +1,11 @@ +use core::iter::repeat; +use itertools::Itertools; + use super::{types::*, *}; -use crate::util::{ActionExecutionError, ApplyUpdate, NonceError, TranslateUpdate, ValidateUpdate}; +use crate::util::{ + ActionExecutionError, ApplyUpdate, IncOrDec, MultiTargetUpdate, NonceError, TranslateUpdate, + ValidateUpdate, +}; use alloc::collections::BTreeSet; impl Pallet { @@ -14,15 +20,19 @@ impl Pallet { convener: Convener, ) -> DispatchResult { TrustRegistriesInfo::::try_mutate(registry_id, |info| { - if let Some(existing) = info.replace(TrustRegistryInfo { + let name = name + .try_into() + .map_err(|_| Error::::TrustRegistryNameSizeExceeded)?; + let gov_framework = gov_framework + .try_into() + .map_err(|_| Error::::GovFrameworkSizeExceeded)?; + let new_info = TrustRegistryInfo { convener, - name: name - .try_into() - .map_err(|_| Error::::TrustRegistryNameSizeExceeded)?, - gov_framework: gov_framework - .try_into() - .map_err(|_| Error::::GovFrameworkSizeExceeded)?, - }) { + name, + gov_framework, + }; + + if let Some(existing) = info.replace(new_info) { if existing.convener != convener { Err(Error::::NotTheConvener)? } @@ -56,7 +66,7 @@ impl Pallet { let mut validation = StorageAccesses::default(); schemas .validate_and_record_diff(actor, registry_id, ®istry_info, &mut validation) - .map_err(|error| StepError::Validation(error, validation.clone())) + .map_err(|error| StepError::Validation(error.into(), validation.clone())) .map(|validated_update| StepStorageAccesses { validation, execution: validated_update.execute(registry_id), @@ -82,8 +92,38 @@ impl Pallet { TrustRegistryIssuerConfigurations::::try_mutate(registry_id, issuer, |config| { delegated.ensure_valid(&issuer, &config.delegated)?; - delegated.apply_update(&mut config.delegated); + let issuer_schema_ids = TrustRegistryIssuerSchemas::::get(registry_id, issuer); + let issuers_diff = delegated.keys_diff(&config.delegated); + + for (issuer, update) in issuers_diff.iter() { + let schema_ids_update: MultiTargetUpdate<_, IncOrDec> = issuer_schema_ids + .iter() + .copied() + .zip(repeat(update.translate_update().unwrap())) + .collect(); + let schema_ids = TrustRegistryDelegatedIssuerSchemas::::get(registry_id, issuer); + + schema_ids_update.ensure_valid(issuer, &schema_ids)?; + } + + for (issuer, update) in issuers_diff { + let schema_ids_update: MultiTargetUpdate<_, IncOrDec> = issuer_schema_ids + .iter() + .copied() + .zip(repeat(update.translate_update().unwrap())) + .collect(); + + TrustRegistryDelegatedIssuerSchemas::::mutate( + registry_id, + issuer, + |schema_ids| { + schema_ids_update.apply_update(schema_ids); + }, + ); + } + + delegated.apply_update(&mut config.delegated); Self::deposit_event(Event::DelegatedIssuersUpdated(registry_id, issuer)); Ok(()) @@ -172,13 +212,32 @@ impl Pallet { reg_id: TrustRegistryId, issuer_or_verifier: IssuerOrVerifier, ) -> BTreeSet { - let issuer_schemas = Self::registry_issuer_schemas(reg_id, Issuer(*issuer_or_verifier)); + let issuer_schemas = + Self::registry_issuer_or_delegated_issuer_schemas(reg_id, Issuer(*issuer_or_verifier)); let verifier_schemas = Self::registry_verifier_schemas(reg_id, Verifier(*issuer_or_verifier)); issuer_schemas.union(&verifier_schemas).copied().collect() } + pub fn registry_issuer_or_delegated_issuer_schemas( + reg_id: TrustRegistryId, + issuer_or_delegated_issuer: Issuer, + ) -> BTreeSet { + let IssuerSchemas(issuer_schemas) = + Self::registry_issuer_schemas(reg_id, issuer_or_delegated_issuer); + let DelegatedIssuerSchemas(delegated_issuer_schemas) = + Self::registry_delegated_issuer_schemas(reg_id, issuer_or_delegated_issuer); + + delegated_issuer_schemas + .into_iter() + .map(|(key, _)| key) + .into_iter() + .merge(issuer_schemas) + .dedup() + .collect() + } + pub fn aggregate_schema_metadata( (reg_id, schema_id): (TrustRegistryId, TrustRegistrySchemaId), ) -> Option> { diff --git a/pallets/core/src/modules/trust_registry/mod.rs b/pallets/core/src/modules/trust_registry/mod.rs index 86d3771a7..33948e4e4 100644 --- a/pallets/core/src/modules/trust_registry/mod.rs +++ b/pallets/core/src/modules/trust_registry/mod.rs @@ -9,7 +9,7 @@ use crate::{ OnlyExistent, SetOrAddOrRemoveOrModify, SetOrModify, UpdateTranslationError, }, }; -use core::convert::Infallible; +use core::{convert::Infallible, iter::repeat}; use frame_support::{ dispatch::DispatchErrorWithPostInfo, pallet_prelude::*, @@ -42,6 +42,8 @@ use weights::*; #[frame_support::pallet] pub mod pallet { + use crate::util::{DuplicateKey, IncOrDec, MultiTargetUpdate, UpdateError}; + use super::*; use frame_system::pallet_prelude::*; use utils::BoundedStringConversionError; @@ -81,6 +83,25 @@ pub mod pallet { } } + impl From for Error { + fn from(update_error: UpdateError) -> Self { + match update_error { + UpdateError::DoesntExist => Error::::EntityDoesntExist, + UpdateError::AlreadyExists => Error::::EntityAlreadyExists, + UpdateError::InvalidActor => Error::::SenderCantApplyThisUpdate, + UpdateError::Overflow => Error::::TooManySchemasPerDelegatedIssuer, + UpdateError::CapacityOverflow => Error::::TooManyEntities, + UpdateError::ValidationFailed => Error::::UpdateValidationFailed, + } + } + } + + impl From for Error { + fn from(DuplicateKey: DuplicateKey) -> Self { + Error::::DuplicateKey + } + } + /// Error for the TrustRegistry module. #[pallet::error] pub enum Error { @@ -109,6 +130,22 @@ pub mod pallet { PriceCurrencySymbolSizeExceeded, /// Too many schemas per a single Trust Registry. SchemasPerRegistrySizeExceeded, + /// `Issuer` attempts to set himself as a delegated `Issuer`. + IssuerCantDelegateToHimself, + /// Attempt to remove/update non-existing entity failed. + EntityDoesntExist, + /// Attempt to add an existing entity failed. + EntityAlreadyExists, + /// This update can't be executed by the provided sender. + SenderCantApplyThisUpdate, + /// Delegated `Issuer`'s schemas amount exceeded. + TooManySchemasPerDelegatedIssuer, + /// Can't add more entities. + TooManyEntities, + /// Failed to validate provided update. + UpdateValidationFailed, + /// Some of the keys were found twice in the update. + DuplicateKey, } #[pallet::event] @@ -126,7 +163,7 @@ pub mod pallet { IssuerSuspended(TrustRegistryId, Issuer), /// `TrustRegistry`'s `Issuer` was unsuspended. IssuerUnsuspended(TrustRegistryId, Issuer), - /// Delegated `Issuer`s were updated in the `TrustRegistry` with the given id.. + /// Delegated `Issuer`s were updated in the `TrustRegistry` with the given id. DelegatedIssuersUpdated(TrustRegistryId, Issuer), } @@ -197,6 +234,19 @@ pub mod pallet { ValueQuery, >; + /// Stores `Trust Registry`'s delegated `Issuer`s schemas. + #[pallet::storage] + #[pallet::getter(fn registry_delegated_issuer_schemas)] + pub type TrustRegistryDelegatedIssuerSchemas = StorageDoubleMap< + _, + Blake2_128Concat, + TrustRegistryId, + Blake2_128Concat, + Issuer, + DelegatedIssuerSchemas, + ValueQuery, + >; + /// Stores a set of `Verifier`s Trust Registries. #[pallet::storage] #[pallet::getter(fn verifier_registries)] @@ -263,7 +313,7 @@ pub mod pallet { match set_schemas_metadata .signed(signature) - .execute_readonly(Self::set_schemas_metadata_) + .execute_view(Self::set_schemas_metadata_) { Ok(StepStorageAccesses { validation, @@ -304,7 +354,7 @@ pub mod pallet { update_delegated_issuers .signed(signature) - .execute_readonly(Self::update_delegated_issuers_) + .execute_view(Self::update_delegated_issuers_) } /// Suspends given `Issuer`s. @@ -318,7 +368,7 @@ pub mod pallet { suspend_issuers .signed(signature) - .execute_readonly(Self::suspend_issuers_) + .execute_view(Self::suspend_issuers_) } /// Unsuspends given `Issuer`s. @@ -332,7 +382,37 @@ pub mod pallet { unsuspend_issuers .signed(signature) - .execute_readonly(Self::unsuspend_issuers_) + .execute_view(Self::unsuspend_issuers_) + } + } + + #[pallet::hooks] + impl Hooks> for Pallet { + fn on_runtime_upgrade() -> Weight { + use crate::util::batch_update::ApplyUpdate; + + let mut reads = 0; + let mut writes = 0; + + for (registry_id, issuer, config) in TrustRegistryIssuerConfigurations::::iter() { + let schema_ids = TrustRegistryIssuerSchemas::::get(registry_id, issuer); + reads += 2; + + let schema_ids_update: MultiTargetUpdate<_, _> = + schema_ids.into_iter().zip(repeat(IncOrDec::Inc)).collect(); + + for delegated_issuer in config.delegated.iter() { + TrustRegistryDelegatedIssuerSchemas::::mutate( + registry_id, + delegated_issuer, + |schema_ids| schema_ids_update.clone().apply_update(schema_ids), + ); + + writes += 1; + } + } + + T::DbWeight::get().reads_writes(reads, writes) } } } diff --git a/pallets/core/src/modules/trust_registry/query.rs b/pallets/core/src/modules/trust_registry/query.rs index f1e480c69..034460036 100644 --- a/pallets/core/src/modules/trust_registry/query.rs +++ b/pallets/core/src/modules/trust_registry/query.rs @@ -106,7 +106,7 @@ impl QueryTrustRegistryBy { let issuer_schema_ids = issuers.map(|issuers| { issuers.transform_by_applying_rule(|issuer| { - Pallet::::registry_issuer_schemas(reg_id, issuer) + Pallet::::registry_issuer_or_delegated_issuer_schemas(reg_id, issuer) }) }); let verifier_schema_ids = verifiers.map(|verifiers| { diff --git a/pallets/core/src/modules/trust_registry/tests.rs b/pallets/core/src/modules/trust_registry/tests.rs index 7fd0cd324..5f5055bda 100644 --- a/pallets/core/src/modules/trust_registry/tests.rs +++ b/pallets/core/src/modules/trust_registry/tests.rs @@ -10,6 +10,7 @@ use crate::{ }, }; use alloc::collections::{BTreeMap, BTreeSet}; +use core::num::NonZeroU32; use frame_support::{assert_noop, assert_ok}; use rand::{distributions::Alphanumeric, Rng}; @@ -203,7 +204,7 @@ crate::did_or_did_method_key! { }; add_schema_metadata - .execute_readonly(|action, reg| { + .execute_view(|action, reg| { Mod::set_schemas_metadata_(action, reg, ConvenerOrIssuerOrVerifier(convener.into())) }) .unwrap(); @@ -284,6 +285,13 @@ crate::did_or_did_method_key! { let (convener, _convener_kp) = newdid(); let (other, other_kp) = newdid(); + let (other_1, other_kp_1) = newdid(); + let other_schemas = (0..5) + .map(|_| TrustRegistrySchemaId(rand::random())) + .collect::>(); + let other_1_schemas = (0..5) + .map(|_| TrustRegistrySchemaId(rand::random())) + .collect::>(); let init_or_update_trust_registry = InitOrUpdateTrustRegistry:: { registry_id: TrustRegistryId(rand::random()), @@ -319,14 +327,9 @@ crate::did_or_did_method_key! { }; let sig = did_sig(&update_delegated, &other_kp, other, 1u32); - assert_eq!( - TrustRegistryIssuerConfigurations::::get( - init_or_update_trust_registry.registry_id, - Issuer(other.into()) - ) - .delegated, - Default::default() - ); + let shared_schemas = (0..5) + .map(|_| TrustRegistrySchemaId(rand::random())) + .collect::>(); assert_noop!( Pallet::::update_delegated_issuers( @@ -340,7 +343,37 @@ crate::did_or_did_method_key! { TrustRegistryIssuerSchemas::::insert( init_or_update_trust_registry.registry_id, Issuer(other.into()), - IssuerSchemas(Default::default()), + IssuerSchemas( + shared_schemas.clone().into_iter().chain( + other_schemas.clone() + ).collect::>().try_into().unwrap() + ) + ); + TrustRegistryIssuerSchemas::::insert( + init_or_update_trust_registry.registry_id, + Issuer(other_1.into()), + IssuerSchemas( + shared_schemas.clone().into_iter().chain( + other_1_schemas.clone() + ).collect::>().try_into().unwrap() + ) + ); + + assert_eq!( + TrustRegistryIssuerConfigurations::::get( + init_or_update_trust_registry.registry_id, + Issuer(other.into()) + ) + .delegated, + Default::default() + ); + + assert_eq!( + TrustRegistryDelegatedIssuerSchemas::::get( + init_or_update_trust_registry.registry_id, + Issuer(other.into()) + ), + DelegatedIssuerSchemas(Default::default()) ); assert_ok!(Pallet::::update_delegated_issuers( @@ -349,13 +382,119 @@ crate::did_or_did_method_key! { sig ),); + for delegated_issuer in delegated.iter().cloned() { + assert_eq!( + TrustRegistryDelegatedIssuerSchemas::::get( + init_or_update_trust_registry.registry_id, + Issuer(delegated_issuer.into()) + ), + DelegatedIssuerSchemas( + shared_schemas + .clone() + .into_iter() + .chain(other_schemas.clone()) + .map(|id| (id, NonZeroU32::new(1).unwrap().into())) + .collect::>().try_into().unwrap() + ) + ); + } + + let update_delegated = UpdateDelegatedIssuers { + delegated: SetOrModify::Set(delegated.clone()), + registry_id: init_or_update_trust_registry.registry_id, + nonce: 2u32.into(), + }; + let sig = did_sig(&update_delegated, &other_kp_1, other_1, 1u32); + + assert_ok!( + Pallet::::update_delegated_issuers( + Origin::signed(alice), + update_delegated.clone(), + sig.clone() + ) + ); + + for delegated_issuer in delegated.iter().cloned() { + assert_eq!( + TrustRegistryDelegatedIssuerSchemas::::get( + init_or_update_trust_registry.registry_id, + Issuer(delegated_issuer.into()) + ), + DelegatedIssuerSchemas( + shared_schemas + .clone() + .into_iter() + .map(|id| (id, NonZeroU32::new(2).unwrap().into()) + ).chain( + other_schemas.clone() + .into_iter() + .chain(other_1_schemas.clone()) + .map(|id| (id, NonZeroU32::new(1).unwrap().into())) + ).collect::>().try_into().unwrap() + ) + ); + } + + let update_delegated = UpdateDelegatedIssuers:: { + delegated: SetOrModify::Set(Default::default()), + registry_id: init_or_update_trust_registry.registry_id, + nonce: 3u32.into(), + }; + let sig = did_sig(&update_delegated, &other_kp, other, 1u32); + + assert_eq!( + TrustRegistryIssuerConfigurations::::get( + init_or_update_trust_registry.registry_id, + Issuer(other.into()) + ) + .delegated, + delegated.clone().try_into().unwrap() + ); + + assert_ok!( + Pallet::::update_delegated_issuers( + Origin::signed(alice), + update_delegated.clone(), + sig.clone() + ) + ); + + for delegated_issuer in delegated.iter().cloned() { + assert_eq!( + TrustRegistryDelegatedIssuerSchemas::::get( + init_or_update_trust_registry.registry_id, + Issuer(delegated_issuer.into()) + ), + DelegatedIssuerSchemas( + shared_schemas + .clone() + .into_iter() + .map(|id| (id, NonZeroU32::new(1).unwrap().into())) + .chain( + other_1_schemas + .clone() + .into_iter() + .map(|id| (id, NonZeroU32::new(1).unwrap().into())) + ).collect::>().try_into().unwrap() + ) + ); + } + assert_eq!( TrustRegistryIssuerConfigurations::::get( init_or_update_trust_registry.registry_id, Issuer(other.into()) ) .delegated, - delegated.try_into().unwrap() + Default::default() + ); + assert_eq!( + TrustRegistryIssuerConfigurations::::get( + init_or_update_trust_registry.registry_id, + Issuer(other_1.into()) + ) + .delegated, + delegated.clone().try_into().unwrap() ); }) } @@ -476,7 +615,7 @@ crate::did_or_did_method_key! { assert_noop!( Mod::set_schemas_metadata(Origin::signed(alice), add_other_schema_metadata, other_sig).map_err(|e| e.error), - UpdateError::InvalidActor + Error::::SenderCantApplyThisUpdate ); let add_other_schema_metadata = SetSchemasMetadata { @@ -494,7 +633,7 @@ crate::did_or_did_method_key! { assert_noop!( Mod::set_schemas_metadata(Origin::signed(alice), add_other_schema_metadata, sig).map_err(|e| e.error), - UpdateError::AlreadyExists + Error::::EntityAlreadyExists ); }) } @@ -661,17 +800,17 @@ crate::did_or_did_method_key! { UnboundedTrustRegistrySchemaMetadata, >| { assert_noop!( - update.clone().execute_readonly(|action, reg| { + update.clone().execute_view(|action, reg| { Mod::set_schemas_metadata_( action, reg, ConvenerOrIssuerOrVerifier(verifier.into()), ) }).map_err(DispatchError::from), - UpdateError::InvalidActor + Error::::SenderCantApplyThisUpdate ); - assert_ok!(update.execute_readonly(|action, reg| { + assert_ok!(update.execute_view(|action, reg| { Mod::set_schemas_metadata_( action, reg, @@ -724,22 +863,22 @@ crate::did_or_did_method_key! { UnboundedTrustRegistrySchemaMetadata, >| { assert_noop!( - update.clone().execute_readonly(|action, reg| { + update.clone().execute_view(|action, reg| { Mod::set_schemas_metadata_( action, reg, ConvenerOrIssuerOrVerifier(issuer.into()), ) }).map_err(DispatchError::from), - UpdateError::InvalidActor + Error::::SenderCantApplyThisUpdate ); assert_noop!( - update.execute_readonly(|action, reg| Mod::set_schemas_metadata_( + update.execute_view(|action, reg| Mod::set_schemas_metadata_( action, reg, ConvenerOrIssuerOrVerifier(verifier.into()) )).map_err(DispatchError::from), - UpdateError::InvalidActor + Error::::SenderCantApplyThisUpdate ); }, ) as _, @@ -774,22 +913,22 @@ crate::did_or_did_method_key! { UnboundedTrustRegistrySchemaMetadata, >| { assert_noop!( - update.clone().execute_readonly(|action, reg| { + update.clone().execute_view(|action, reg| { Mod::set_schemas_metadata_( action, reg, ConvenerOrIssuerOrVerifier(issuer.into()), ) }).map_err(DispatchError::from), - UpdateError::InvalidActor + Error::::SenderCantApplyThisUpdate ); assert_noop!( - update.execute_readonly(|action, reg| Mod::set_schemas_metadata_( + update.execute_view(|action, reg| Mod::set_schemas_metadata_( action, reg, ConvenerOrIssuerOrVerifier(verifier.into()) )).map_err(DispatchError::from), - UpdateError::InvalidActor + Error::::SenderCantApplyThisUpdate ); }, ) @@ -836,7 +975,7 @@ crate::did_or_did_method_key! { TrustRegistrySchemaId, UnboundedTrustRegistrySchemaMetadata, >| { - assert_ok!(update.execute_readonly(|action, reg| { + assert_ok!(update.execute_view(|action, reg| { Mod::set_schemas_metadata_( action, reg, @@ -881,22 +1020,22 @@ crate::did_or_did_method_key! { UnboundedTrustRegistrySchemaMetadata, >| { assert_noop!( - update.clone().execute_readonly(|action, reg| { + update.clone().execute_view(|action, reg| { Mod::set_schemas_metadata_( action, reg, ConvenerOrIssuerOrVerifier(random_did.into()), ) }).map_err(DispatchError::from), - UpdateError::InvalidActor + Error::::SenderCantApplyThisUpdate ); assert_noop!( - update.execute_readonly(|action, reg| Mod::set_schemas_metadata_( + update.execute_view(|action, reg| Mod::set_schemas_metadata_( action, reg, ConvenerOrIssuerOrVerifier(convener.into()) )).map_err(DispatchError::from), - UpdateError::DoesntExist + Error::::EntityDoesntExist ); }, ) as _, @@ -962,30 +1101,30 @@ crate::did_or_did_method_key! { UnboundedTrustRegistrySchemaMetadata, >| { assert_noop!( - update.clone().execute_readonly(|action, reg| { + update.clone().execute_view(|action, reg| { Mod::set_schemas_metadata_( action, reg, ConvenerOrIssuerOrVerifier(issuer.into()), ) }).map_err(DispatchError::from), - UpdateError::InvalidActor + Error::::SenderCantApplyThisUpdate ); let schema_1 = schemas.get_mut(&schema_ids[1]).unwrap(); let issuer_3 = (*schema_1.issuers.keys().nth(3).unwrap()).into(); assert_noop!( - update.clone().execute_readonly(|action, reg| { + update.clone().execute_view(|action, reg| { Mod::set_schemas_metadata_( action, reg, ConvenerOrIssuerOrVerifier(issuer_3), ) }).map_err(DispatchError::from), - UpdateError::InvalidActor + Error::::SenderCantApplyThisUpdate ); - assert_ok!(update.execute_readonly(|action, reg| { + assert_ok!(update.execute_view(|action, reg| { Mod::set_schemas_metadata_( action, reg, @@ -1040,22 +1179,22 @@ crate::did_or_did_method_key! { UnboundedTrustRegistrySchemaMetadata, >| { assert_noop!( - update.clone().execute_readonly(|action, reg| { + update.clone().execute_view(|action, reg| { Mod::set_schemas_metadata_( action, reg, ConvenerOrIssuerOrVerifier(issuer.into()), ) }).map_err(DispatchError::from), - UpdateError::InvalidActor + Error::::SenderCantApplyThisUpdate ); assert_noop!( - update.execute_readonly(|action, reg| Mod::set_schemas_metadata_( + update.execute_view(|action, reg| Mod::set_schemas_metadata_( action, reg, ConvenerOrIssuerOrVerifier(verifier.into()) )).map_err(DispatchError::from), - UpdateError::InvalidActor + Error::::SenderCantApplyThisUpdate ); }, ) as _, @@ -1090,12 +1229,12 @@ crate::did_or_did_method_key! { UnboundedTrustRegistrySchemaMetadata, >| { assert_noop!( - update.execute_readonly(|action, reg| Mod::set_schemas_metadata_( + update.execute_view(|action, reg| Mod::set_schemas_metadata_( action, reg, ConvenerOrIssuerOrVerifier(issuer.into()) )).map_err(DispatchError::from), - UpdateError::CapacityOverflow + Error::::TooManyEntities ); }, ) as _, @@ -1142,12 +1281,12 @@ crate::did_or_did_method_key! { UnboundedTrustRegistrySchemaMetadata, >| { assert_noop!( - update.execute_readonly(|action, reg| Mod::set_schemas_metadata_( + update.execute_view(|action, reg| Mod::set_schemas_metadata_( action, reg, ConvenerOrIssuerOrVerifier(convener.into()) )).map_err(DispatchError::from), - UpdateError::CapacityOverflow + Error::::TooManyEntities ); }, ) as _, @@ -1181,7 +1320,7 @@ crate::did_or_did_method_key! { TrustRegistrySchemaId, UnboundedTrustRegistrySchemaMetadata, >| { - assert_ok!(update.execute_readonly(|action, registry| { + assert_ok!(update.execute_view(|action, registry| { Mod::set_schemas_metadata_( action, registry, @@ -1225,16 +1364,16 @@ crate::did_or_did_method_key! { UnboundedTrustRegistrySchemaMetadata, >| { assert_noop!( - update.clone().execute_readonly(|action, reg| { + update.clone().execute_view(|action, reg| { Mod::set_schemas_metadata_( action, reg, ConvenerOrIssuerOrVerifier(issuer.into()), ) }).map_err(DispatchError::from), - UpdateError::InvalidActor + Error::::SenderCantApplyThisUpdate ); - assert_ok!(update.execute_readonly(|action, reg| { + assert_ok!(update.execute_view(|action, reg| { Mod::set_schemas_metadata_( action, reg, @@ -1271,16 +1410,16 @@ crate::did_or_did_method_key! { UnboundedTrustRegistrySchemaMetadata, >| { assert_noop!( - update.clone().execute_readonly(|action, reg| { + update.clone().execute_view(|action, reg| { Mod::set_schemas_metadata_( action, reg, ConvenerOrIssuerOrVerifier(verifier.into()), ) }).map_err(DispatchError::from), - UpdateError::InvalidActor + Error::::SenderCantApplyThisUpdate ); - assert_ok!(update.execute_readonly(|action, reg| { + assert_ok!(update.execute_view(|action, reg| { Mod::set_schemas_metadata_( action, reg, @@ -1317,16 +1456,16 @@ crate::did_or_did_method_key! { UnboundedTrustRegistrySchemaMetadata, >| { assert_noop!( - update.clone().execute_readonly(|action, reg| { + update.clone().execute_view(|action, reg| { Mod::set_schemas_metadata_( action, reg, ConvenerOrIssuerOrVerifier(issuer.into()), ) }).map_err(DispatchError::from), - UpdateError::InvalidActor + Error::::SenderCantApplyThisUpdate ); - assert_ok!(update.execute_readonly(|action, reg| { + assert_ok!(update.execute_view(|action, reg| { Mod::set_schemas_metadata_( action, reg, @@ -1355,14 +1494,14 @@ crate::did_or_did_method_key! { UnboundedTrustRegistrySchemaMetadata, >| { assert_noop!( - update.clone().execute_readonly(|action, reg| { + update.clone().execute_view(|action, reg| { Mod::set_schemas_metadata_( action, reg, ConvenerOrIssuerOrVerifier(convener.into()), ) }).map_err(DispatchError::from), - UpdateError::AlreadyExists + Error::::EntityAlreadyExists ); }, ) as _, @@ -1384,7 +1523,7 @@ crate::did_or_did_method_key! { TrustRegistrySchemaId, UnboundedTrustRegistrySchemaMetadata, >| { - assert_ok!(update.execute_readonly(|action, reg| { + assert_ok!(update.execute_view(|action, reg| { Mod::set_schemas_metadata_( action, reg, @@ -1409,17 +1548,17 @@ crate::did_or_did_method_key! { UnboundedTrustRegistrySchemaMetadata, >| { assert_noop!( - update.clone().execute_readonly(|action, reg| { + update.clone().execute_view(|action, reg| { Mod::set_schemas_metadata_( action, reg, ConvenerOrIssuerOrVerifier(issuer.into()), ) }).map_err(DispatchError::from), - UpdateError::InvalidActor + Error::::SenderCantApplyThisUpdate ); - assert_ok!(update.clone().execute_readonly(|action, reg| { + assert_ok!(update.clone().execute_view(|action, reg| { Mod::set_schemas_metadata_( action, reg, @@ -1444,17 +1583,17 @@ crate::did_or_did_method_key! { UnboundedTrustRegistrySchemaMetadata, >| { assert_noop!( - update.clone().execute_readonly(|action, reg| { + update.clone().execute_view(|action, reg| { Mod::set_schemas_metadata_( action, reg, ConvenerOrIssuerOrVerifier(issuer.into()), ) }).map_err(DispatchError::from), - UpdateError::InvalidActor + Error::::SenderCantApplyThisUpdate ); - assert_ok!(update.execute_readonly(|action, reg| { + assert_ok!(update.execute_view(|action, reg| { Mod::set_schemas_metadata_( action, reg, @@ -1478,17 +1617,17 @@ crate::did_or_did_method_key! { UnboundedTrustRegistrySchemaMetadata, >| { assert_noop!( - update.clone().execute_readonly(|action, reg| { + update.clone().execute_view(|action, reg| { Mod::set_schemas_metadata_( action, reg, ConvenerOrIssuerOrVerifier(issuer.into()), ) }).map_err(DispatchError::from), - UpdateError::InvalidActor + Error::::SenderCantApplyThisUpdate ); - assert_ok!(update.execute_readonly(|action, reg| { + assert_ok!(update.execute_view(|action, reg| { Mod::set_schemas_metadata_( action, reg, @@ -1510,17 +1649,17 @@ crate::did_or_did_method_key! { UnboundedTrustRegistrySchemaMetadata, >| { assert_noop!( - update.clone().execute_readonly(|action, reg| { + update.clone().execute_view(|action, reg| { Mod::set_schemas_metadata_( action, reg, ConvenerOrIssuerOrVerifier(issuer.into()), ) }).map_err(DispatchError::from), - UpdateError::InvalidActor + Error::::SenderCantApplyThisUpdate ); - assert_ok!(update.execute_readonly(|action, reg| { + assert_ok!(update.execute_view(|action, reg| { Mod::set_schemas_metadata_( action, reg, @@ -1542,17 +1681,17 @@ crate::did_or_did_method_key! { UnboundedTrustRegistrySchemaMetadata, >| { assert_noop!( - update.clone().execute_readonly(|action, reg| { + update.clone().execute_view(|action, reg| { Mod::set_schemas_metadata_( action, reg, ConvenerOrIssuerOrVerifier(issuer.into()), ) }).map_err(DispatchError::from), - UpdateError::InvalidActor + Error::::SenderCantApplyThisUpdate ); - assert_ok!(update.execute_readonly(|action, reg| { + assert_ok!(update.execute_view(|action, reg| { Mod::set_schemas_metadata_( action, reg, @@ -1574,7 +1713,7 @@ crate::did_or_did_method_key! { UnboundedTrustRegistrySchemaMetadata, >| { assert_noop!( - update.clone().execute_readonly(|action, reg| { + update.clone().execute_view(|action, reg| { Mod::set_schemas_metadata_( action, reg, @@ -1596,7 +1735,7 @@ crate::did_or_did_method_key! { UnboundedTrustRegistrySchemaMetadata, >| { assert_noop!( - update.clone().execute_readonly(|action, reg| { + update.clone().execute_view(|action, reg| { Mod::set_schemas_metadata_( action, reg, @@ -1618,7 +1757,7 @@ crate::did_or_did_method_key! { UnboundedTrustRegistrySchemaMetadata, >| { assert_noop!( - update.clone().execute_readonly(|action, reg| { + update.clone().execute_view(|action, reg| { Mod::set_schemas_metadata_( action, reg, @@ -1640,7 +1779,7 @@ crate::did_or_did_method_key! { UnboundedTrustRegistrySchemaMetadata, >| { assert_noop!( - update.clone().execute_readonly(|action, reg| { + update.clone().execute_view(|action, reg| { Mod::set_schemas_metadata_( action, reg, diff --git a/pallets/core/src/modules/trust_registry/types.rs b/pallets/core/src/modules/trust_registry/types.rs index dc04e4792..46bc75a0f 100644 --- a/pallets/core/src/modules/trust_registry/types.rs +++ b/pallets/core/src/modules/trust_registry/types.rs @@ -7,7 +7,7 @@ use crate::{ }; use alloc::collections::BTreeMap; use codec::{Decode, Encode, MaxEncodedLen}; -use core::fmt::Debug; +use core::{fmt::Debug, num::NonZeroU32}; use frame_support::{traits::Get, weights::Weight, *}; use scale_info::prelude::string::String; use sp_std::{collections::btree_set::BTreeSet, prelude::*}; @@ -61,6 +61,15 @@ pub struct IssuerOrVerifier(pub DidOrDidMethodKey); impl_wrapper!(IssuerOrVerifier(DidOrDidMethodKey)); +#[derive(Encode, Decode, Clone, Debug, Copy, PartialEq, Eq, Ord, PartialOrd, MaxEncodedLen)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))] +#[derive(scale_info_derive::TypeInfo)] +#[scale_info(omit_prefix)] +pub struct DelegatedSchemaCounter(pub NonZeroU32); + +impl_wrapper!(DelegatedSchemaCounter(NonZeroU32)); + /// Both an `Issuer` and a `Verifier`. #[derive(Encode, Decode, Clone, Debug, Copy, PartialEq, Eq, Ord, PartialOrd, MaxEncodedLen)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] @@ -695,7 +704,7 @@ pub struct TrustRegistryStoredSchemas( impl_wrapper!(TrustRegistryStoredSchemas where T: Limits => (BoundedBTreeSet)); -/// Set of schemas corresponding to a issuer +/// Set of schemas corresponding to an `Issuer`. #[derive( Encode, Decode, @@ -731,6 +740,33 @@ impl IntoIterator for IssuerSchemas { } } +/// Set of schemas corresponding to a delegated `Issuer` +#[derive( + Encode, + Decode, + CloneNoBound, + PartialEqNoBound, + EqNoBound, + DebugNoBound, + MaxEncodedLen, + DefaultNoBound, +)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))] +#[cfg_attr( + feature = "serde", + serde(bound(serialize = "T: Sized", deserialize = "T: Sized")) +)] +#[derive(scale_info_derive::TypeInfo)] +#[scale_info(skip_type_params(T))] +#[scale_info(omit_prefix)] +pub struct DelegatedIssuerSchemas( + #[cfg_attr(feature = "serde", serde(with = "btree_map"))] + pub BoundedBTreeMap, +); + +impl_wrapper!(DelegatedIssuerSchemas where T: Limits => (BoundedBTreeMap)); + /// Set of trust registries corresponding to a issuer #[derive( Encode, diff --git a/pallets/core/src/modules/trust_registry/update.rs b/pallets/core/src/modules/trust_registry/update.rs index e80f52630..3355dee33 100644 --- a/pallets/core/src/modules/trust_registry/update.rs +++ b/pallets/core/src/modules/trust_registry/update.rs @@ -60,7 +60,7 @@ impl TryFrom for Schemas { let schemas: BTreeMap<_, _> = schemas .into_iter() .map(|(schema_id, schema_metadata)| Ok((schema_id, schema_metadata.try_into()?))) - .collect::>()?; + .collect::>>()?; schemas .try_into() @@ -327,7 +327,7 @@ pub trait ValidateTrustRegistryUpdate { registry_id: TrustRegistryId, registry_info: &TrustRegistryInfo, context: &mut Self::Context<'_>, - ) -> Result, DispatchError> + ) -> Result, Error> where Validated: ExecuteTrustRegistryUpdate; } @@ -371,7 +371,7 @@ where registry_id: TrustRegistryId, registry_info: &TrustRegistryInfo, (ref mut schemas, ref mut regs): &mut Self::Context<'_>, - ) -> Result, DispatchError> { + ) -> Result, Error> { self.into_iter() .inspect(|_| **schemas += 1) .filter_map(|(target, update)| { @@ -400,7 +400,7 @@ where Some(Ok((target, update))) }) - .collect::>() + .collect::>() .map(Validated) } } @@ -418,7 +418,7 @@ impl ValidateTrustRegistryUpdate for Schemas { registry_id: TrustRegistryId, registry_info: &TrustRegistryInfo, ctx: &mut Self::Context<'_>, - ) -> Result, DispatchError> { + ) -> Result, Error> { let Self(updates) = self; let to_set = updates @@ -449,7 +449,7 @@ impl ValidateTrustRegistryUpdate for SchemaIdUpdate, (ref mut issuers_verifiers_schemas, ref mut storage_accesses): &mut Self::Context<'_>, - ) -> Result, DispatchError> { + ) -> Result, Error> { self.into_iter() .inspect(|_| storage_accesses.schemas += 1) .filter_map(|(schema_id, update)| { @@ -485,7 +485,7 @@ impl ValidateTrustRegistryUpdate for SchemaIdUpdate { registry_id: TrustRegistryId, registry_info: &TrustRegistryInfo, read_storage: &mut Self::Context<'_>, - ) -> Result, DispatchError> { + ) -> Result, Error> { if !self.is_empty() { let existing_schema_ids = super::TrustRegistriesStoredSchemas::::get(registry_id); *read_storage = true; @@ -510,7 +510,7 @@ impl ValidateTrustRegistryUpdate for SchemasUpdate { registry_id: TrustRegistryId, registry_info: &TrustRegistryInfo, storage_accesses: &mut Self::Context<'_>, - ) -> Result, DispatchError> { + ) -> Result, Error> { let mut issuers_verifiers_schemas = Default::default(); let Validated(update) = match self { Self::Set(schemas) => schemas.validate_and_record_diff( diff --git a/pallets/core/src/modules/trust_registry/update_rules.rs b/pallets/core/src/modules/trust_registry/update_rules.rs index 2b81b3af0..c12784e2e 100644 --- a/pallets/core/src/modules/trust_registry/update_rules.rs +++ b/pallets/core/src/modules/trust_registry/update_rules.rs @@ -29,6 +29,16 @@ impl CanUpdate for IssuerOrVerifier { } } +impl CanUpdate for Issuer { + fn can_add(&self, _entity: &DelegatedSchemaCounter) -> bool { + true + } + + fn can_remove(&self, _entity: &DelegatedSchemaCounter) -> bool { + true + } +} + impl CanUpdate> for IssuerOrVerifier {} impl CanUpdate> for IssuerOrVerifier {} @@ -112,6 +122,16 @@ impl CanUpdateKeyed> for IssuerOrVerifier { } } +impl CanUpdateKeyed> for Issuer { + fn can_update_keyed>>( + &self, + _entity: &DelegatedIssuerSchemas, + _update: &U, + ) -> bool { + true + } +} + impl CanUpdateKeyed> for Verifier { fn can_update_keyed>>( &self, @@ -145,16 +165,16 @@ impl CanUpdateKeyed> for IssuerOrVerifier { impl CanUpdateKeyed> for Issuer { fn can_update_keyed>>( &self, - _entity: &DelegatedIssuers, - _update: &U, + entity: &DelegatedIssuers, + update: &U, ) -> bool { - true + update.targets(entity).all(|delegated| delegated != self) } } impl CanUpdate> for Issuer { - fn can_replace(&self, _new: &DelegatedIssuers, _existing: &DelegatedIssuers) -> bool { - true + fn can_replace(&self, new: &DelegatedIssuers, _existing: &DelegatedIssuers) -> bool { + !new.contains(self) } } diff --git a/pallets/core/src/modules/trust_registry/weights.rs b/pallets/core/src/modules/trust_registry/weights.rs index adb065039..5911e8b1a 100644 --- a/pallets/core/src/modules/trust_registry/weights.rs +++ b/pallets/core/src/modules/trust_registry/weights.rs @@ -1,7 +1,7 @@ //! Autogenerated weights for trust_registry //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2024-02-21, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-03-11, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` //! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: None, DB CACHE: 1024 // Executed Command: @@ -48,129 +48,134 @@ pub trait WeightInfo { /// Weights for trust_registry using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl> WeightInfo for SubstrateWeight { - fn init_or_update_trust_registry_sr25519(_n: u32, g: u32) -> Weight { - Weight::from_ref_time(59_726_000) // Standard Error: 0 - .saturating_add(Weight::from_ref_time(5_000).saturating_mul(g as u64)) + fn init_or_update_trust_registry_sr25519(_n: u32, _g: u32) -> Weight { + Weight::from_ref_time(60_159_000) .saturating_add(W::get().reads(5)) .saturating_add(W::get().writes(4)) } fn init_or_update_trust_registry_ed25519(n: u32, g: u32) -> Weight { - Weight::from_ref_time(58_259_000) // Standard Error: 2_000 - .saturating_add(Weight::from_ref_time(3_000).saturating_mul(n as u64)) // Standard Error: 0 - .saturating_add(Weight::from_ref_time(1_000).saturating_mul(g as u64)) + Weight::from_ref_time(57_097_000) // Standard Error: 6_000 + .saturating_add(Weight::from_ref_time(50_000).saturating_mul(n as u64)) // Standard Error: 2_000 + .saturating_add(Weight::from_ref_time(6_000).saturating_mul(g as u64)) .saturating_add(W::get().reads(5)) .saturating_add(W::get().writes(4)) } fn init_or_update_trust_registry_secp256k1(n: u32, g: u32) -> Weight { - Weight::from_ref_time(150_405_000) // Standard Error: 6_000 - .saturating_add(Weight::from_ref_time(24_000).saturating_mul(n as u64)) // Standard Error: 1_000 - .saturating_add(Weight::from_ref_time(8_000).saturating_mul(g as u64)) + Weight::from_ref_time(146_444_000) // Standard Error: 14_000 + .saturating_add(Weight::from_ref_time(139_000).saturating_mul(n as u64)) // Standard Error: 4_000 + .saturating_add(Weight::from_ref_time(26_000).saturating_mul(g as u64)) .saturating_add(W::get().reads(5)) .saturating_add(W::get().writes(4)) } fn set_schemas_metadata_sr25519(i: u32, v: u32, s: u32) -> Weight { - Weight::from_ref_time(0) // Standard Error: 72_000 - .saturating_add(Weight::from_ref_time(5_518_000).saturating_mul(i as u64)) // Standard Error: 72_000 - .saturating_add(Weight::from_ref_time(6_718_000).saturating_mul(v as u64)) // Standard Error: 380_000 - .saturating_add(Weight::from_ref_time(281_303_000).saturating_mul(s as u64)) - .saturating_add(W::get().reads(4)) + Weight::from_ref_time(0) // Standard Error: 140_000 + .saturating_add(Weight::from_ref_time(5_575_000).saturating_mul(i as u64)) // Standard Error: 140_000 + .saturating_add(Weight::from_ref_time(7_136_000).saturating_mul(v as u64)) // Standard Error: 735_000 + .saturating_add(Weight::from_ref_time(278_953_000).saturating_mul(s as u64)) + .saturating_add(W::get().reads(3)) .saturating_add(W::get().reads((2 as u64).saturating_mul(i as u64))) .saturating_add(W::get().reads((2 as u64).saturating_mul(v as u64))) .saturating_add(W::get().reads((1 as u64).saturating_mul(s as u64))) - .saturating_add(W::get().writes(2)) + .saturating_add(W::get().writes(1)) .saturating_add(W::get().writes((2 as u64).saturating_mul(i as u64))) .saturating_add(W::get().writes((2 as u64).saturating_mul(v as u64))) .saturating_add(W::get().writes((1 as u64).saturating_mul(s as u64))) } fn set_schemas_metadata_ed25519(i: u32, v: u32, s: u32) -> Weight { - Weight::from_ref_time(44_729_000) // Standard Error: 59_000 - .saturating_add(Weight::from_ref_time(764_000).saturating_mul(i as u64)) // Standard Error: 59_000 - .saturating_add(Weight::from_ref_time(6_745_000).saturating_mul(v as u64)) // Standard Error: 310_000 - .saturating_add(Weight::from_ref_time(255_084_000).saturating_mul(s as u64)) - .saturating_add(W::get().reads(4)) + Weight::from_ref_time(50_379_000) // Standard Error: 113_000 + .saturating_add(Weight::from_ref_time(455_000).saturating_mul(i as u64)) // Standard Error: 113_000 + .saturating_add(Weight::from_ref_time(6_782_000).saturating_mul(v as u64)) // Standard Error: 597_000 + .saturating_add(Weight::from_ref_time(252_016_000).saturating_mul(s as u64)) + .saturating_add(W::get().reads(3)) .saturating_add(W::get().reads((2 as u64).saturating_mul(i as u64))) .saturating_add(W::get().reads((2 as u64).saturating_mul(v as u64))) .saturating_add(W::get().reads((1 as u64).saturating_mul(s as u64))) - .saturating_add(W::get().writes(2)) + .saturating_add(W::get().writes(1)) .saturating_add(W::get().writes((2 as u64).saturating_mul(i as u64))) .saturating_add(W::get().writes((2 as u64).saturating_mul(v as u64))) .saturating_add(W::get().writes((1 as u64).saturating_mul(s as u64))) } fn set_schemas_metadata_secp256k1(i: u32, v: u32, s: u32) -> Weight { - Weight::from_ref_time(0) // Standard Error: 57_000 - .saturating_add(Weight::from_ref_time(4_212_000).saturating_mul(i as u64)) // Standard Error: 57_000 - .saturating_add(Weight::from_ref_time(7_039_000).saturating_mul(v as u64)) // Standard Error: 299_000 - .saturating_add(Weight::from_ref_time(273_037_000).saturating_mul(s as u64)) - .saturating_add(W::get().reads(4)) + Weight::from_ref_time(0) // Standard Error: 128_000 + .saturating_add(Weight::from_ref_time(5_650_000).saturating_mul(i as u64)) // Standard Error: 128_000 + .saturating_add(Weight::from_ref_time(7_839_000).saturating_mul(v as u64)) // Standard Error: 672_000 + .saturating_add(Weight::from_ref_time(268_238_000).saturating_mul(s as u64)) + .saturating_add(W::get().reads(3)) .saturating_add(W::get().reads((2 as u64).saturating_mul(i as u64))) .saturating_add(W::get().reads((2 as u64).saturating_mul(v as u64))) .saturating_add(W::get().reads((1 as u64).saturating_mul(s as u64))) - .saturating_add(W::get().writes(2)) + .saturating_add(W::get().writes(1)) .saturating_add(W::get().writes((2 as u64).saturating_mul(i as u64))) .saturating_add(W::get().writes((2 as u64).saturating_mul(v as u64))) .saturating_add(W::get().writes((1 as u64).saturating_mul(s as u64))) } fn update_delegated_issuers_sr25519(i: u32) -> Weight { - Weight::from_ref_time(59_438_000) // Standard Error: 9_000 - .saturating_add(Weight::from_ref_time(163_000).saturating_mul(i as u64)) + Weight::from_ref_time(59_046_000) // Standard Error: 15_000 + .saturating_add(Weight::from_ref_time(2_343_000).saturating_mul(i as u64)) .saturating_add(W::get().reads(4)) + .saturating_add(W::get().reads((1 as u64).saturating_mul(i as u64))) .saturating_add(W::get().writes(2)) + .saturating_add(W::get().writes((1 as u64).saturating_mul(i as u64))) } fn update_delegated_issuers_ed25519(i: u32) -> Weight { - Weight::from_ref_time(58_327_000) // Standard Error: 10_000 - .saturating_add(Weight::from_ref_time(139_000).saturating_mul(i as u64)) + Weight::from_ref_time(62_602_000) // Standard Error: 25_000 + .saturating_add(Weight::from_ref_time(1_719_000).saturating_mul(i as u64)) .saturating_add(W::get().reads(4)) + .saturating_add(W::get().reads((1 as u64).saturating_mul(i as u64))) .saturating_add(W::get().writes(2)) + .saturating_add(W::get().writes((1 as u64).saturating_mul(i as u64))) } fn update_delegated_issuers_secp256k1(i: u32) -> Weight { - Weight::from_ref_time(150_628_000) // Standard Error: 15_000 - .saturating_add(Weight::from_ref_time(154_000).saturating_mul(i as u64)) + Weight::from_ref_time(152_670_000) // Standard Error: 45_000 + .saturating_add(Weight::from_ref_time(2_504_000).saturating_mul(i as u64)) .saturating_add(W::get().reads(4)) + .saturating_add(W::get().reads((1 as u64).saturating_mul(i as u64))) .saturating_add(W::get().writes(2)) + .saturating_add(W::get().writes((1 as u64).saturating_mul(i as u64))) } fn suspend_issuers_sr25519(i: u32) -> Weight { - Weight::from_ref_time(57_175_000) // Standard Error: 5_000 - .saturating_add(Weight::from_ref_time(4_949_000).saturating_mul(i as u64)) + Weight::from_ref_time(59_922_000) // Standard Error: 11_000 + .saturating_add(Weight::from_ref_time(4_919_000).saturating_mul(i as u64)) .saturating_add(W::get().reads(3)) .saturating_add(W::get().reads((2 as u64).saturating_mul(i as u64))) .saturating_add(W::get().writes(1)) .saturating_add(W::get().writes((1 as u64).saturating_mul(i as u64))) } fn suspend_issuers_ed25519(i: u32) -> Weight { - Weight::from_ref_time(56_066_000) // Standard Error: 4_000 - .saturating_add(Weight::from_ref_time(4_895_000).saturating_mul(i as u64)) + Weight::from_ref_time(58_670_000) // Standard Error: 16_000 + .saturating_add(Weight::from_ref_time(4_886_000).saturating_mul(i as u64)) .saturating_add(W::get().reads(3)) .saturating_add(W::get().reads((2 as u64).saturating_mul(i as u64))) .saturating_add(W::get().writes(1)) .saturating_add(W::get().writes((1 as u64).saturating_mul(i as u64))) } fn suspend_issuers_secp256k1(i: u32) -> Weight { - Weight::from_ref_time(149_812_000) // Standard Error: 8_000 - .saturating_add(Weight::from_ref_time(4_839_000).saturating_mul(i as u64)) + Weight::from_ref_time(153_174_000) // Standard Error: 22_000 + .saturating_add(Weight::from_ref_time(4_823_000).saturating_mul(i as u64)) .saturating_add(W::get().reads(3)) .saturating_add(W::get().reads((2 as u64).saturating_mul(i as u64))) .saturating_add(W::get().writes(1)) .saturating_add(W::get().writes((1 as u64).saturating_mul(i as u64))) } fn unsuspend_issuers_sr25519(i: u32) -> Weight { - Weight::from_ref_time(56_872_000) // Standard Error: 7_000 - .saturating_add(Weight::from_ref_time(6_219_000).saturating_mul(i as u64)) + Weight::from_ref_time(57_694_000) // Standard Error: 46_000 + .saturating_add(Weight::from_ref_time(6_469_000).saturating_mul(i as u64)) .saturating_add(W::get().reads(3)) .saturating_add(W::get().reads((2 as u64).saturating_mul(i as u64))) .saturating_add(W::get().writes(1)) .saturating_add(W::get().writes((1 as u64).saturating_mul(i as u64))) } fn unsuspend_issuers_ed25519(i: u32) -> Weight { - Weight::from_ref_time(55_920_000) // Standard Error: 7_000 - .saturating_add(Weight::from_ref_time(6_169_000).saturating_mul(i as u64)) + Weight::from_ref_time(52_800_000) // Standard Error: 23_000 + .saturating_add(Weight::from_ref_time(6_371_000).saturating_mul(i as u64)) .saturating_add(W::get().reads(3)) .saturating_add(W::get().reads((2 as u64).saturating_mul(i as u64))) .saturating_add(W::get().writes(1)) .saturating_add(W::get().writes((1 as u64).saturating_mul(i as u64))) } fn unsuspend_issuers_secp256k1(i: u32) -> Weight { - Weight::from_ref_time(148_525_000) // Standard Error: 7_000 - .saturating_add(Weight::from_ref_time(6_199_000).saturating_mul(i as u64)) + Weight::from_ref_time(145_569_000) // Standard Error: 32_000 + .saturating_add(Weight::from_ref_time(6_415_000).saturating_mul(i as u64)) .saturating_add(W::get().reads(3)) .saturating_add(W::get().reads((2 as u64).saturating_mul(i as u64))) .saturating_add(W::get().writes(1)) @@ -180,129 +185,134 @@ impl> WeightInfo for SubstrateWeight { // For backwards compatibility and tests impl WeightInfo for () { - fn init_or_update_trust_registry_sr25519(_n: u32, g: u32) -> Weight { - Weight::from_ref_time(59_726_000) // Standard Error: 0 - .saturating_add(Weight::from_ref_time(5_000).saturating_mul(g as u64)) + fn init_or_update_trust_registry_sr25519(_n: u32, _g: u32) -> Weight { + Weight::from_ref_time(60_159_000) .saturating_add(RocksDbWeight::get().reads(5)) .saturating_add(RocksDbWeight::get().writes(4)) } fn init_or_update_trust_registry_ed25519(n: u32, g: u32) -> Weight { - Weight::from_ref_time(58_259_000) // Standard Error: 2_000 - .saturating_add(Weight::from_ref_time(3_000).saturating_mul(n as u64)) // Standard Error: 0 - .saturating_add(Weight::from_ref_time(1_000).saturating_mul(g as u64)) + Weight::from_ref_time(57_097_000) // Standard Error: 6_000 + .saturating_add(Weight::from_ref_time(50_000).saturating_mul(n as u64)) // Standard Error: 2_000 + .saturating_add(Weight::from_ref_time(6_000).saturating_mul(g as u64)) .saturating_add(RocksDbWeight::get().reads(5)) .saturating_add(RocksDbWeight::get().writes(4)) } fn init_or_update_trust_registry_secp256k1(n: u32, g: u32) -> Weight { - Weight::from_ref_time(150_405_000) // Standard Error: 6_000 - .saturating_add(Weight::from_ref_time(24_000).saturating_mul(n as u64)) // Standard Error: 1_000 - .saturating_add(Weight::from_ref_time(8_000).saturating_mul(g as u64)) + Weight::from_ref_time(146_444_000) // Standard Error: 14_000 + .saturating_add(Weight::from_ref_time(139_000).saturating_mul(n as u64)) // Standard Error: 4_000 + .saturating_add(Weight::from_ref_time(26_000).saturating_mul(g as u64)) .saturating_add(RocksDbWeight::get().reads(5)) .saturating_add(RocksDbWeight::get().writes(4)) } fn set_schemas_metadata_sr25519(i: u32, v: u32, s: u32) -> Weight { - Weight::from_ref_time(0) // Standard Error: 72_000 - .saturating_add(Weight::from_ref_time(5_518_000).saturating_mul(i as u64)) // Standard Error: 72_000 - .saturating_add(Weight::from_ref_time(6_718_000).saturating_mul(v as u64)) // Standard Error: 380_000 - .saturating_add(Weight::from_ref_time(281_303_000).saturating_mul(s as u64)) - .saturating_add(RocksDbWeight::get().reads(4)) + Weight::from_ref_time(0) // Standard Error: 140_000 + .saturating_add(Weight::from_ref_time(5_575_000).saturating_mul(i as u64)) // Standard Error: 140_000 + .saturating_add(Weight::from_ref_time(7_136_000).saturating_mul(v as u64)) // Standard Error: 735_000 + .saturating_add(Weight::from_ref_time(278_953_000).saturating_mul(s as u64)) + .saturating_add(RocksDbWeight::get().reads(3)) .saturating_add(RocksDbWeight::get().reads((2 as u64).saturating_mul(i as u64))) .saturating_add(RocksDbWeight::get().reads((2 as u64).saturating_mul(v as u64))) .saturating_add(RocksDbWeight::get().reads((1 as u64).saturating_mul(s as u64))) - .saturating_add(RocksDbWeight::get().writes(2)) + .saturating_add(RocksDbWeight::get().writes(1)) .saturating_add(RocksDbWeight::get().writes((2 as u64).saturating_mul(i as u64))) .saturating_add(RocksDbWeight::get().writes((2 as u64).saturating_mul(v as u64))) .saturating_add(RocksDbWeight::get().writes((1 as u64).saturating_mul(s as u64))) } fn set_schemas_metadata_ed25519(i: u32, v: u32, s: u32) -> Weight { - Weight::from_ref_time(44_729_000) // Standard Error: 59_000 - .saturating_add(Weight::from_ref_time(764_000).saturating_mul(i as u64)) // Standard Error: 59_000 - .saturating_add(Weight::from_ref_time(6_745_000).saturating_mul(v as u64)) // Standard Error: 310_000 - .saturating_add(Weight::from_ref_time(255_084_000).saturating_mul(s as u64)) - .saturating_add(RocksDbWeight::get().reads(4)) + Weight::from_ref_time(50_379_000) // Standard Error: 113_000 + .saturating_add(Weight::from_ref_time(455_000).saturating_mul(i as u64)) // Standard Error: 113_000 + .saturating_add(Weight::from_ref_time(6_782_000).saturating_mul(v as u64)) // Standard Error: 597_000 + .saturating_add(Weight::from_ref_time(252_016_000).saturating_mul(s as u64)) + .saturating_add(RocksDbWeight::get().reads(3)) .saturating_add(RocksDbWeight::get().reads((2 as u64).saturating_mul(i as u64))) .saturating_add(RocksDbWeight::get().reads((2 as u64).saturating_mul(v as u64))) .saturating_add(RocksDbWeight::get().reads((1 as u64).saturating_mul(s as u64))) - .saturating_add(RocksDbWeight::get().writes(2)) + .saturating_add(RocksDbWeight::get().writes(1)) .saturating_add(RocksDbWeight::get().writes((2 as u64).saturating_mul(i as u64))) .saturating_add(RocksDbWeight::get().writes((2 as u64).saturating_mul(v as u64))) .saturating_add(RocksDbWeight::get().writes((1 as u64).saturating_mul(s as u64))) } fn set_schemas_metadata_secp256k1(i: u32, v: u32, s: u32) -> Weight { - Weight::from_ref_time(0) // Standard Error: 57_000 - .saturating_add(Weight::from_ref_time(4_212_000).saturating_mul(i as u64)) // Standard Error: 57_000 - .saturating_add(Weight::from_ref_time(7_039_000).saturating_mul(v as u64)) // Standard Error: 299_000 - .saturating_add(Weight::from_ref_time(273_037_000).saturating_mul(s as u64)) - .saturating_add(RocksDbWeight::get().reads(4)) + Weight::from_ref_time(0) // Standard Error: 128_000 + .saturating_add(Weight::from_ref_time(5_650_000).saturating_mul(i as u64)) // Standard Error: 128_000 + .saturating_add(Weight::from_ref_time(7_839_000).saturating_mul(v as u64)) // Standard Error: 672_000 + .saturating_add(Weight::from_ref_time(268_238_000).saturating_mul(s as u64)) + .saturating_add(RocksDbWeight::get().reads(3)) .saturating_add(RocksDbWeight::get().reads((2 as u64).saturating_mul(i as u64))) .saturating_add(RocksDbWeight::get().reads((2 as u64).saturating_mul(v as u64))) .saturating_add(RocksDbWeight::get().reads((1 as u64).saturating_mul(s as u64))) - .saturating_add(RocksDbWeight::get().writes(2)) + .saturating_add(RocksDbWeight::get().writes(1)) .saturating_add(RocksDbWeight::get().writes((2 as u64).saturating_mul(i as u64))) .saturating_add(RocksDbWeight::get().writes((2 as u64).saturating_mul(v as u64))) .saturating_add(RocksDbWeight::get().writes((1 as u64).saturating_mul(s as u64))) } fn update_delegated_issuers_sr25519(i: u32) -> Weight { - Weight::from_ref_time(59_438_000) // Standard Error: 9_000 - .saturating_add(Weight::from_ref_time(163_000).saturating_mul(i as u64)) + Weight::from_ref_time(59_046_000) // Standard Error: 15_000 + .saturating_add(Weight::from_ref_time(2_343_000).saturating_mul(i as u64)) .saturating_add(RocksDbWeight::get().reads(4)) + .saturating_add(RocksDbWeight::get().reads((1 as u64).saturating_mul(i as u64))) .saturating_add(RocksDbWeight::get().writes(2)) + .saturating_add(RocksDbWeight::get().writes((1 as u64).saturating_mul(i as u64))) } fn update_delegated_issuers_ed25519(i: u32) -> Weight { - Weight::from_ref_time(58_327_000) // Standard Error: 10_000 - .saturating_add(Weight::from_ref_time(139_000).saturating_mul(i as u64)) + Weight::from_ref_time(62_602_000) // Standard Error: 25_000 + .saturating_add(Weight::from_ref_time(1_719_000).saturating_mul(i as u64)) .saturating_add(RocksDbWeight::get().reads(4)) + .saturating_add(RocksDbWeight::get().reads((1 as u64).saturating_mul(i as u64))) .saturating_add(RocksDbWeight::get().writes(2)) + .saturating_add(RocksDbWeight::get().writes((1 as u64).saturating_mul(i as u64))) } fn update_delegated_issuers_secp256k1(i: u32) -> Weight { - Weight::from_ref_time(150_628_000) // Standard Error: 15_000 - .saturating_add(Weight::from_ref_time(154_000).saturating_mul(i as u64)) + Weight::from_ref_time(152_670_000) // Standard Error: 45_000 + .saturating_add(Weight::from_ref_time(2_504_000).saturating_mul(i as u64)) .saturating_add(RocksDbWeight::get().reads(4)) + .saturating_add(RocksDbWeight::get().reads((1 as u64).saturating_mul(i as u64))) .saturating_add(RocksDbWeight::get().writes(2)) + .saturating_add(RocksDbWeight::get().writes((1 as u64).saturating_mul(i as u64))) } fn suspend_issuers_sr25519(i: u32) -> Weight { - Weight::from_ref_time(57_175_000) // Standard Error: 5_000 - .saturating_add(Weight::from_ref_time(4_949_000).saturating_mul(i as u64)) + Weight::from_ref_time(59_922_000) // Standard Error: 11_000 + .saturating_add(Weight::from_ref_time(4_919_000).saturating_mul(i as u64)) .saturating_add(RocksDbWeight::get().reads(3)) .saturating_add(RocksDbWeight::get().reads((2 as u64).saturating_mul(i as u64))) .saturating_add(RocksDbWeight::get().writes(1)) .saturating_add(RocksDbWeight::get().writes((1 as u64).saturating_mul(i as u64))) } fn suspend_issuers_ed25519(i: u32) -> Weight { - Weight::from_ref_time(56_066_000) // Standard Error: 4_000 - .saturating_add(Weight::from_ref_time(4_895_000).saturating_mul(i as u64)) + Weight::from_ref_time(58_670_000) // Standard Error: 16_000 + .saturating_add(Weight::from_ref_time(4_886_000).saturating_mul(i as u64)) .saturating_add(RocksDbWeight::get().reads(3)) .saturating_add(RocksDbWeight::get().reads((2 as u64).saturating_mul(i as u64))) .saturating_add(RocksDbWeight::get().writes(1)) .saturating_add(RocksDbWeight::get().writes((1 as u64).saturating_mul(i as u64))) } fn suspend_issuers_secp256k1(i: u32) -> Weight { - Weight::from_ref_time(149_812_000) // Standard Error: 8_000 - .saturating_add(Weight::from_ref_time(4_839_000).saturating_mul(i as u64)) + Weight::from_ref_time(153_174_000) // Standard Error: 22_000 + .saturating_add(Weight::from_ref_time(4_823_000).saturating_mul(i as u64)) .saturating_add(RocksDbWeight::get().reads(3)) .saturating_add(RocksDbWeight::get().reads((2 as u64).saturating_mul(i as u64))) .saturating_add(RocksDbWeight::get().writes(1)) .saturating_add(RocksDbWeight::get().writes((1 as u64).saturating_mul(i as u64))) } fn unsuspend_issuers_sr25519(i: u32) -> Weight { - Weight::from_ref_time(56_872_000) // Standard Error: 7_000 - .saturating_add(Weight::from_ref_time(6_219_000).saturating_mul(i as u64)) + Weight::from_ref_time(57_694_000) // Standard Error: 46_000 + .saturating_add(Weight::from_ref_time(6_469_000).saturating_mul(i as u64)) .saturating_add(RocksDbWeight::get().reads(3)) .saturating_add(RocksDbWeight::get().reads((2 as u64).saturating_mul(i as u64))) .saturating_add(RocksDbWeight::get().writes(1)) .saturating_add(RocksDbWeight::get().writes((1 as u64).saturating_mul(i as u64))) } fn unsuspend_issuers_ed25519(i: u32) -> Weight { - Weight::from_ref_time(55_920_000) // Standard Error: 7_000 - .saturating_add(Weight::from_ref_time(6_169_000).saturating_mul(i as u64)) + Weight::from_ref_time(52_800_000) // Standard Error: 23_000 + .saturating_add(Weight::from_ref_time(6_371_000).saturating_mul(i as u64)) .saturating_add(RocksDbWeight::get().reads(3)) .saturating_add(RocksDbWeight::get().reads((2 as u64).saturating_mul(i as u64))) .saturating_add(RocksDbWeight::get().writes(1)) .saturating_add(RocksDbWeight::get().writes((1 as u64).saturating_mul(i as u64))) } fn unsuspend_issuers_secp256k1(i: u32) -> Weight { - Weight::from_ref_time(148_525_000) // Standard Error: 7_000 - .saturating_add(Weight::from_ref_time(6_199_000).saturating_mul(i as u64)) + Weight::from_ref_time(145_569_000) // Standard Error: 32_000 + .saturating_add(Weight::from_ref_time(6_415_000).saturating_mul(i as u64)) .saturating_add(RocksDbWeight::get().reads(3)) .saturating_add(RocksDbWeight::get().reads((2 as u64).saturating_mul(i as u64))) .saturating_add(RocksDbWeight::get().writes(1)) diff --git a/pallets/core/src/util/action.rs b/pallets/core/src/util/action.rs index 732bb04b7..0e0b5adad 100644 --- a/pallets/core/src/util/action.rs +++ b/pallets/core/src/util/action.rs @@ -45,7 +45,7 @@ pub trait Action: Sized { } /// Executes an action providing a value associated with the target. - fn execute_readonly(self, f: F) -> Result + fn execute_view(self, f: F) -> Result where F: FnOnce(Self, S) -> Result, >::Value: TryInto, diff --git a/pallets/core/src/util/batch_update.rs b/pallets/core/src/util/batch_update.rs index aefd9615a..385dc4c81 100644 --- a/pallets/core/src/util/batch_update.rs +++ b/pallets/core/src/util/batch_update.rs @@ -3,6 +3,7 @@ use alloc::collections::{btree_map, BTreeMap, BTreeSet}; use codec::{Decode, Encode, MaxEncodedLen}; use core::{ convert::Infallible, + num::NonZeroU32, ops::{Deref, DerefMut}, }; use frame_support::*; @@ -66,6 +67,14 @@ pub trait ApplyUpdate { fn kind(&self, entity: &Entity) -> UpdateKind; } +impl ApplyUpdate for () { + fn apply_update(self, _: &mut V) {} + + fn kind(&self, _: &V) -> UpdateKind { + UpdateKind::None + } +} + /// Attempts to translate underlying update to the `ToUpdate`. pub trait TranslateUpdate: Sized { /// Update translation error. @@ -75,6 +84,14 @@ pub trait TranslateUpdate: Sized { fn translate_update(self) -> Result; } +impl TranslateUpdate<()> for () { + type Error = Infallible; + + fn translate_update(self) -> Result<(), Self::Error> { + Ok(()) + } +} + /// An error that occured during update translation. pub enum UpdateTranslationError { Value(V), @@ -87,6 +104,12 @@ pub trait ValidateUpdate: ApplyUpdate { fn ensure_valid(&self, actor: &Actor, entity: &Entity) -> Result<(), UpdateError>; } +impl ValidateUpdate for () { + fn ensure_valid(&self, _: &A, _: &V) -> Result<(), UpdateError> { + Ok(()) + } +} + /// Describes what will happen when the update will be applied. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum UpdateKind { @@ -268,7 +291,7 @@ where crate::impl_wrapper!(MultiTargetUpdate where K: Ord => (BTreeMap)); /// Set/add/remove a value or apply a nested update. -#[derive(Encode, Decode, Clone, PartialEq, Eq, Debug, MaxEncodedLen)] +#[derive(Encode, Decode, Clone, PartialEq, Eq, Debug, Copy, MaxEncodedLen)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(scale_info_derive::TypeInfo)] #[scale_info(omit_prefix)] @@ -279,172 +302,6 @@ pub enum SetOrAddOrRemoveOrModify { Modify(U), } -impl TranslateUpdate> - for SetOrAddOrRemoveOrModify -where - V: TryInto, - U: TranslateUpdate, -{ - type Error = UpdateTranslationError; - - fn translate_update(self) -> Result, Self::Error> { - match self { - Self::Set(value) => value - .try_into() - .map_err(UpdateTranslationError::Value) - .map(SetOrAddOrRemoveOrModify::Set), - Self::Add(value) => value - .try_into() - .map_err(UpdateTranslationError::Value) - .map(SetOrAddOrRemoveOrModify::Add), - Self::Remove => Ok(SetOrAddOrRemoveOrModify::Remove), - Self::Modify(update) => update - .translate_update() - .map_err(UpdateTranslationError::Update) - .map(SetOrAddOrRemoveOrModify::Modify), - } - } -} - -/// Add/remove a value or apply a nested update. -#[derive(Encode, Decode, Clone, PartialEq, Eq, Debug, MaxEncodedLen)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(scale_info_derive::TypeInfo)] -#[scale_info(omit_prefix)] -pub enum AddOrRemoveOrModify { - Add(V), - Remove, - Modify(U), -} - -impl TranslateUpdate> for AddOrRemoveOrModify -where - V: TryInto, - U: TranslateUpdate, -{ - type Error = UpdateTranslationError; - - fn translate_update(self) -> Result, Self::Error> { - match self { - Self::Add(value) => value - .try_into() - .map_err(UpdateTranslationError::Value) - .map(AddOrRemoveOrModify::Add), - Self::Remove => Ok(AddOrRemoveOrModify::Remove), - Self::Modify(update) => update - .translate_update() - .map_err(UpdateTranslationError::Update) - .map(AddOrRemoveOrModify::Modify), - } - } -} - -/// Set a value or apply a nested update. -#[derive(Encode, Decode, Clone, PartialEq, Eq, Debug, MaxEncodedLen)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(scale_info_derive::TypeInfo)] -#[scale_info(omit_prefix)] -pub enum SetOrModify { - Set(V), - Modify(U), -} - -impl SetOrModify { - pub fn unwrap_modify(self) -> U { - match self { - Self::Modify(update) => update, - Self::Set(_) => panic!("Panic on `SetOrModify::Set`"), - } - } -} - -impl TranslateUpdate> for SetOrModify -where - V: TryInto, - U: TranslateUpdate, -{ - type Error = UpdateTranslationError; - - fn translate_update(self) -> Result, Self::Error> { - match self { - SetOrModify::Set(value) => value - .try_into() - .map_err(UpdateTranslationError::Value) - .map(SetOrModify::Set), - SetOrModify::Modify(update) => update - .translate_update() - .map_err(UpdateTranslationError::Update) - .map(SetOrModify::Modify), - } - } -} - -/// Apply an update to the existing entity. -#[derive(Encode, Decode, Clone, PartialEq, Eq, Debug, MaxEncodedLen, Default)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(scale_info_derive::TypeInfo)] -#[scale_info(omit_prefix)] -pub struct OnlyExistent(pub U); - -impl TranslateUpdate> for OnlyExistent -where - U: TranslateUpdate, -{ - type Error = U::Error; - - fn translate_update(self) -> Result, Self::Error> { - match self { - OnlyExistent(update) => update.translate_update().map(OnlyExistent), - } - } -} - -impl TranslateUpdate<()> for () { - type Error = Infallible; - - fn translate_update(self) -> Result<(), Self::Error> { - Ok(()) - } -} - -impl ApplyUpdate for () { - fn apply_update(self, _: &mut V) {} - - fn kind(&self, _: &V) -> UpdateKind { - UpdateKind::None - } -} - -impl ValidateUpdate for () { - fn ensure_valid(&self, _: &A, _: &V) -> Result<(), UpdateError> { - Ok(()) - } -} - -impl ApplyUpdate> for OnlyExistent -where - U: ApplyUpdate, -{ - fn apply_update(self, entity: &mut Option) { - self.0 - .apply_update(entity.as_mut().expect("`OnlyExistent` update failed")) - } - - fn kind(&self, entity: &Option) -> UpdateKind { - entity - .as_ref() - .map_or(UpdateKind::None, |entity| self.0.kind(entity)) - } -} - -impl, V, U: ValidateUpdate> ValidateUpdate> for OnlyExistent { - fn ensure_valid(&self, actor: &A, entity: &Option) -> Result<(), UpdateError> { - let target = entity.as_ref().ok_or(UpdateError::DoesntExist)?; - - self.0.ensure_valid(actor, target) - } -} - impl>> ApplyUpdate> for SetOrAddOrRemoveOrModify { @@ -526,6 +383,43 @@ impl, V: PartialEq, U: ValidateUpdate>> ValidateUpd } } +impl TranslateUpdate> + for SetOrAddOrRemoveOrModify +where + V: TryInto, + U: TranslateUpdate, +{ + type Error = UpdateTranslationError; + + fn translate_update(self) -> Result, Self::Error> { + match self { + Self::Set(value) => value + .try_into() + .map_err(UpdateTranslationError::Value) + .map(SetOrAddOrRemoveOrModify::Set), + Self::Add(value) => value + .try_into() + .map_err(UpdateTranslationError::Value) + .map(SetOrAddOrRemoveOrModify::Add), + Self::Remove => Ok(SetOrAddOrRemoveOrModify::Remove), + Self::Modify(update) => update + .translate_update() + .map_err(UpdateTranslationError::Update) + .map(SetOrAddOrRemoveOrModify::Modify), + } + } +} +/// Add/remove a value or apply a nested update. +#[derive(Encode, Decode, Clone, PartialEq, Eq, Debug, Copy, MaxEncodedLen)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(scale_info_derive::TypeInfo)] +#[scale_info(omit_prefix)] +pub enum AddOrRemoveOrModify { + Add(V), + Remove, + Modify(U), +} + impl, V, U: ValidateUpdate>> ValidateUpdate> for AddOrRemoveOrModify { @@ -585,6 +479,47 @@ impl>> ApplyUpdate> for AddOrRemoveOrModif } } +impl TranslateUpdate> for AddOrRemoveOrModify +where + V: TryInto, + U: TranslateUpdate, +{ + type Error = UpdateTranslationError; + + fn translate_update(self) -> Result, Self::Error> { + match self { + Self::Add(value) => value + .try_into() + .map_err(UpdateTranslationError::Value) + .map(AddOrRemoveOrModify::Add), + Self::Remove => Ok(AddOrRemoveOrModify::Remove), + Self::Modify(update) => update + .translate_update() + .map_err(UpdateTranslationError::Update) + .map(AddOrRemoveOrModify::Modify), + } + } +} + +/// Set a value or apply a nested update. +#[derive(Encode, Decode, Clone, PartialEq, Eq, Debug, Copy, MaxEncodedLen)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(scale_info_derive::TypeInfo)] +#[scale_info(omit_prefix)] +pub enum SetOrModify { + Set(V), + Modify(U), +} + +impl SetOrModify { + pub fn unwrap_modify(self) -> U { + match self { + Self::Modify(update) => update, + Self::Set(_) => panic!("Panic on `SetOrModify::Set`"), + } + } +} + impl> ApplyUpdate for SetOrModify { fn apply_update(self, entity: &mut V) { match self { @@ -624,11 +559,234 @@ impl, V: PartialEq, U: ValidateUpdate> ValidateUpdate TranslateUpdate> for SetOrModify +where + V: TryInto, + U: TranslateUpdate, +{ + type Error = UpdateTranslationError; + + fn translate_update(self) -> Result, Self::Error> { + match self { + SetOrModify::Set(value) => value + .try_into() + .map_err(UpdateTranslationError::Value) + .map(SetOrModify::Set), + SetOrModify::Modify(update) => update + .translate_update() + .map_err(UpdateTranslationError::Update) + .map(SetOrModify::Modify), + } + } +} + +impl KeyedUpdate for SetOrModify +where + C: DerefMut, + C::Target: KeyValue, + U: KeyedUpdate, +{ + type Targets<'a> = Either< + core::iter::Chain< + ::Keys<'a>, + ::Keys<'a>, + >, + U::Targets<'a> + > where + Self: 'a, + ::Key: 'a, + C: 'a; + + fn targets<'targets>(&'targets self, entity: &'targets C) -> Self::Targets<'targets> { + match self { + Self::Set(item) => Either::Left(item.keys().chain(entity.keys())), + Self::Modify(update) => Either::Right(update.targets(entity)), + } + } + + fn keys_diff( + &self, + entity: &C, + ) -> MultiTargetUpdate<::Key, AddOrRemoveOrModify<()>> { + match self { + Self::Set(item) => { + let after: BTreeSet<_> = item.keys().collect(); + let before: BTreeSet<_> = entity.keys().collect(); + + after + .difference(&before) + .map(|key| ((*key).clone(), AddOrRemoveOrModify::Add(()))) + .chain( + before + .difference(&after) + .map(|key| ((*key).clone(), AddOrRemoveOrModify::Remove)), + ) + .collect() + } + Self::Modify(update) => update.keys_diff(entity), + } + } + + fn size(&self) -> u32 { + match self { + Self::Set(item) => item.len(), + Self::Modify(update) => update.size(), + } + } +} + +/// Apply an update to the existing entity. +#[derive(Encode, Decode, Clone, PartialEq, Eq, Debug, Copy, MaxEncodedLen, Default)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(scale_info_derive::TypeInfo)] +#[scale_info(omit_prefix)] +pub struct OnlyExistent(pub U); + +impl ApplyUpdate> for OnlyExistent +where + U: ApplyUpdate, +{ + fn apply_update(self, entity: &mut Option) { + self.0 + .apply_update(entity.as_mut().expect("`OnlyExistent` update failed")) + } + + fn kind(&self, entity: &Option) -> UpdateKind { + entity + .as_ref() + .map_or(UpdateKind::None, |entity| self.0.kind(entity)) + } +} + +impl, V, U: ValidateUpdate> ValidateUpdate> for OnlyExistent { + fn ensure_valid(&self, actor: &A, entity: &Option) -> Result<(), UpdateError> { + let target = entity.as_ref().ok_or(UpdateError::DoesntExist)?; + + self.0.ensure_valid(actor, target) + } +} + +impl TranslateUpdate> for OnlyExistent +where + U: TranslateUpdate, +{ + type Error = U::Error; + + fn translate_update(self) -> Result, Self::Error> { + match self { + OnlyExistent(update) => update.translate_update().map(OnlyExistent), + } + } +} + +/// Increase or decrease a counter. +#[derive(Encode, Decode, Clone, PartialEq, Eq, Debug, Copy, MaxEncodedLen)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(scale_info_derive::TypeInfo)] +#[scale_info(omit_prefix)] +pub enum IncOrDec { + Inc, + Dec, +} + +impl IncOrDec { + pub const ONE: NonZeroU32 = unsafe { NonZeroU32::new_unchecked(1) }; +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CantTransformToIncOrDec; + +impl TranslateUpdate for AddOrRemoveOrModify<()> { + type Error = CantTransformToIncOrDec; + + fn translate_update(self) -> Result { + match self { + Self::Add(()) => Ok(IncOrDec::Inc), + Self::Remove => Ok(IncOrDec::Dec), + _ => Err(CantTransformToIncOrDec), + } + } +} + +impl ApplyUpdate> for IncOrDec +where + V: Deref + From, +{ + fn apply_update(self, entity: &mut Option) { + match self { + IncOrDec::Dec => { + if entity.is_none() { + panic!("Attempt to decrement an absent counter") + } + *entity = entity + .take() + .and_then(|value| value.get().checked_sub(1)) + .and_then(NonZeroU32::new) + .map(V::from); + } + IncOrDec::Inc => match entity { + Some(value) => *value = value.checked_add(1).map(Into::into).expect("Overflow"), + None => { + entity.replace(Self::ONE.into()); + } + }, + } + } + + fn kind(&self, entity: &Option) -> UpdateKind { + match self { + IncOrDec::Inc => UpdateKind::Replace, + IncOrDec::Dec => match entity.as_ref().map(Deref::deref) { + Some(&Self::ONE) => UpdateKind::Remove, + _ => UpdateKind::Replace, + }, + } + } +} + +impl TranslateUpdate for IncOrDec { + type Error = Infallible; + + fn translate_update(self) -> Result { + Ok(self) + } +} + +impl ValidateUpdate> for IncOrDec +where + V: Deref + From, + A: CanUpdate, +{ + fn ensure_valid(&self, actor: &A, entity: &Option) -> Result<(), UpdateError> { + match self { + Self::Inc => { + let Some(new) = entity + .as_ref() + .map_or(Self::ONE.into(), |value| value.checked_add(1)) + .map(V::from) + else { + Err(UpdateError::Overflow)? + }; + ensure!(actor.can_add(&new), UpdateError::InvalidActor); + } + Self::Dec => { + let Some(value) = entity else { + Err(UpdateError::DoesntExist)? + }; + ensure!(actor.can_remove(&value), UpdateError::InvalidActor); + } + } + + Ok(()) + } +} + #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub enum UpdateError { DoesntExist, AlreadyExists, InvalidActor, + Overflow, CapacityOverflow, ValidationFailed, } @@ -636,6 +794,7 @@ pub enum UpdateError { impl From for DispatchError { fn from(error: UpdateError) -> Self { Self::Other(match error { + UpdateError::Overflow => "An overflowed happened", UpdateError::DoesntExist => "Entity doesn't exist", UpdateError::AlreadyExists => "Entity already exists", UpdateError::InvalidActor => "Provided actor can't perform this action", @@ -755,61 +914,6 @@ where } } -impl KeyedUpdate for SetOrModify -where - C: DerefMut, - C::Target: KeyValue, - U: KeyedUpdate, -{ - type Targets<'a> = Either< - core::iter::Chain< - ::Keys<'a>, - ::Keys<'a>, - >, - U::Targets<'a> - > where - Self: 'a, - ::Key: 'a, - C: 'a; - - fn targets<'targets>(&'targets self, entity: &'targets C) -> Self::Targets<'targets> { - match self { - Self::Set(item) => Either::Left(item.keys().chain(entity.keys())), - Self::Modify(update) => Either::Right(update.targets(entity)), - } - } - - fn keys_diff( - &self, - entity: &C, - ) -> MultiTargetUpdate<::Key, AddOrRemoveOrModify<()>> { - match self { - Self::Set(item) => { - let after: BTreeSet<_> = item.keys().collect(); - let before: BTreeSet<_> = entity.keys().collect(); - - after - .difference(&before) - .map(|key| ((*key).clone(), AddOrRemoveOrModify::Add(()))) - .chain( - before - .difference(&after) - .map(|key| ((*key).clone(), AddOrRemoveOrModify::Remove)), - ) - .collect() - } - Self::Modify(update) => update.keys_diff(entity), - } - } - - fn size(&self) -> u32 { - match self { - Self::Set(item) => item.len(), - Self::Modify(update) => update.size(), - } - } -} - #[cfg(test)] mod tests { use sp_runtime::{traits::ConstU32, BoundedBTreeMap};