From bc3590a6c25d5f2afe84a7795ba7504d50f67e22 Mon Sep 17 00:00:00 2001 From: Oleg Nosov Date: Wed, 7 Feb 2024 09:49:02 +0400 Subject: [PATCH] Combine adding/updating schema operations in the `Trust registry` together (#151) --- pallets/core/src/common/state_change.rs | 3 +- .../src/modules/trust_registry/actions.rs | 31 +- .../src/modules/trust_registry/benchmarks.rs | 118 +-- .../core/src/modules/trust_registry/impl.rs | 147 +-- .../core/src/modules/trust_registry/mod.rs | 130 +-- .../core/src/modules/trust_registry/tests.rs | 949 ++++++++++++------ .../core/src/modules/trust_registry/types.rs | 156 ++- .../modules/trust_registry/update_rules.rs | 42 +- .../src/modules/trust_registry/weights.rs | 441 ++++---- pallets/core/src/util/action.rs | 7 +- pallets/core/src/util/batch_update.rs | 475 +++++++-- runtime/src/lib.rs | 2 +- 12 files changed, 1575 insertions(+), 926 deletions(-) diff --git a/pallets/core/src/common/state_change.rs b/pallets/core/src/common/state_change.rs index 0aee711e0..f548e1e98 100644 --- a/pallets/core/src/common/state_change.rs +++ b/pallets/core/src/common/state_change.rs @@ -37,8 +37,7 @@ crate::def_state_change! { status_list_credential::UpdateStatusListCredential, status_list_credential::RemoveStatusListCredential, trust_registry::InitOrUpdateTrustRegistry, - trust_registry::AddSchemaMetadata, - trust_registry::UpdateSchemaMetadata, + trust_registry::SetSchemasMetadata, trust_registry::UpdateDelegatedIssuers, trust_registry::SuspendIssuers, trust_registry::UnsuspendIssuers diff --git a/pallets/core/src/modules/trust_registry/actions.rs b/pallets/core/src/modules/trust_registry/actions.rs index 7bbe98c24..8e6115fd6 100644 --- a/pallets/core/src/modules/trust_registry/actions.rs +++ b/pallets/core/src/modules/trust_registry/actions.rs @@ -1,6 +1,10 @@ use super::*; -use crate::{common::TypesAndLimits, impl_action_with_nonce, util::BoundedBytes}; -use alloc::collections::{BTreeMap, BTreeSet}; +use crate::{ + common::TypesAndLimits, + impl_action_with_nonce, + util::{BoundedBytes, MultiTargetUpdate}, +}; +use alloc::collections::BTreeSet; use frame_support::{CloneNoBound, DebugNoBound, EqNoBound, PartialEqNoBound}; use utils::BoundedString; @@ -37,24 +41,10 @@ pub struct InitOrUpdateTrustRegistry { #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))] #[scale_info(skip_type_params(T))] #[scale_info(omit_prefix)] -pub struct AddSchemaMetadata { +pub struct SetSchemasMetadata { pub registry_id: TrustRegistryId, - pub schemas: BTreeMap>, - pub nonce: T::BlockNumber, -} - -#[derive(Encode, Decode, scale_info_derive::TypeInfo, DebugNoBound, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr( - feature = "serde", - serde(bound(serialize = "T: Sized", deserialize = "T: Sized")) -)] -#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))] -#[scale_info(skip_type_params(T))] -#[scale_info(omit_prefix)] -pub struct UpdateSchemaMetadata { - pub registry_id: TrustRegistryId, - pub schemas: BTreeMap>, + pub schemas: + MultiTargetUpdate>, pub nonce: T::BlockNumber, } @@ -111,8 +101,7 @@ impl_action_with_nonce!( impl_action_with_nonce!( for TrustRegistryId: - AddSchemaMetadata with schemas.len() as len, registry_id as target, - UpdateSchemaMetadata with schemas.len() as len, registry_id as target, + SetSchemasMetadata with schemas.len() as len, registry_id as target, SuspendIssuers with issuers.len() as len, registry_id as target, UnsuspendIssuers with issuers.len() as len, registry_id as target ); diff --git a/pallets/core/src/modules/trust_registry/benchmarks.rs b/pallets/core/src/modules/trust_registry/benchmarks.rs index bd6081249..5c32d7483 100644 --- a/pallets/core/src/modules/trust_registry/benchmarks.rs +++ b/pallets/core/src/modules/trust_registry/benchmarks.rs @@ -13,6 +13,7 @@ use sp_runtime::traits::TryCollect; use sp_std::prelude::*; const TRUST_REGISTRY_MAX_NAME: u32 = 30; +const TRUST_REGISTRY_GOV_FRAMEWORK: u32 = 100; const SCHEMA_ISSUERS: u32 = 50; const SCHEMA_VERIFIERS: u32 = 50; const SCHEMA_ISSUER_PRICES: u32 = 20; @@ -25,6 +26,7 @@ crate::bench_with_all_pairs! { init_or_update_trust_registry_sr25519 for sr25519, init_or_update_trust_registry_ed25519 for ed25519, init_or_update_trust_registry_secp256k1 for secp256k1 { { let n in 1 .. TRUST_REGISTRY_MAX_NAME as u32; + let g in 1 .. TRUST_REGISTRY_GOV_FRAMEWORK as u32; } let pair as Pair; let caller = whitelisted_caller(); @@ -41,7 +43,7 @@ crate::bench_with_all_pairs! { let init_or_update_trust_registry = InitOrUpdateTrustRegistry { registry_id: TrustRegistryId(id), nonce: 1u32.into(), - gov_framework: Bytes(vec![1; 100]).try_into().unwrap(), + gov_framework: Bytes(vec![1; g as usize]).try_into().unwrap(), name: (0..n).map(|idx| (98 + idx) as u8 as char).collect::().try_into().unwrap() }; let sig = pair.sign(&init_or_update_trust_registry.to_state_change().encode()); @@ -55,65 +57,7 @@ crate::bench_with_all_pairs! { }); } - add_schema_metadata_sr25519 for sr25519, add_schema_metadata_ed25519 for ed25519, add_schema_metadata_secp256k1 for secp256k1 { - { - let i in 0 .. SCHEMA_ISSUERS as u32; - let v in 0 .. SCHEMA_VERIFIERS as u32; - let s in 1 .. SCHEMAS_COUNT as u32; - } - let pair as Pair; - let caller = whitelisted_caller(); - let did = Did([0; Did::BYTE_SIZE]); - let public = pair.public(); - - crate::did::Pallet::::new_onchain_( - did, - vec![UncheckedDidKey::new_with_all_relationships(public)], - Default::default(), - ).unwrap(); - - let id = [1u8; 32].into(); - ActionWrapper::::new(1u32.into(), Convener(did.into()), InitOrUpdateTrustRegistry { - registry_id: TrustRegistryId(id), - nonce: 1u32.into(), - gov_framework: Bytes(vec![1; 100]).try_into().unwrap(), - name: (0..10).map(|idx| (98 + idx) as u8 as char).collect::().try_into().unwrap() - }).execute::(|action, set| Pallet::::init_or_update_trust_registry_(action.action, set, Convener(did.into()))).unwrap(); - - let schemas: BTreeMap<_, _> = (0..s) - .map(|idx| - ( - TrustRegistrySchemaId([idx as u8; 32]), - TrustRegistrySchemaMetadata { - issuers: IssuersWith((0..i).map(|idx| - ( - Issuer(Did([idx as u8; 32]).into()), - VerificationPrices( - (0..SCHEMA_ISSUER_PRICES) - .map(|p_idx| ((0..SCHEMA_ISSUER_PRICE_SYMBOL).map(|idx| (98 + idx + p_idx) as u8 as char).collect::().try_into().unwrap(), Price(1000))) - .collect::>() - .try_into() - .unwrap()) - ) - ).try_collect().unwrap()), - verifiers: SchemaVerifiers((0..v).map(|idx| Verifier(Did([idx as u8; 32]).into())).try_collect().unwrap()) - } - ) - ).collect(); - - let add_schema_metadata = AddSchemaMetadata { - registry_id: TrustRegistryId(id), - schemas: schemas.clone(), - nonce: 1u32.into() - }; - let sig = pair.sign(&add_schema_metadata.to_state_change().encode()); - let signature = DidSignature::new(did, 1u32, sig).into(); - }: add_schema_metadata(RawOrigin::Signed(caller), add_schema_metadata.clone(), signature) - verify { - assert_eq!(schemas, TrustRegistrySchemasMetadata::::iter().map(|(schema_id, _, metadata)| (schema_id, metadata)).collect::>()); - } - - update_schema_metadata_sr25519 for sr25519, update_schema_metadata_ed25519 for ed25519, update_schema_metadata_secp256k1 for secp256k1 { + set_schemas_metadata_sr25519 for sr25519, set_schemas_metadata_ed25519 for ed25519, set_schemas_metadata_secp256k1 for secp256k1 { { let i in 0 .. SCHEMA_ISSUERS as u32; let v in 0 .. SCHEMA_VERIFIERS as u32; @@ -149,10 +93,17 @@ crate::bench_with_all_pairs! { Issuer(Did([255 - idx as u8; 32]).into()), VerificationPrices( (0..SCHEMA_ISSUER_PRICES) - .map(|p_idx| ((0..SCHEMA_ISSUER_PRICE_SYMBOL).map(|idx| (98 + idx + p_idx) as u8 as char).collect::().try_into().unwrap(), Price(1000))) + .map(|p_idx| ( + (0..SCHEMA_ISSUER_PRICE_SYMBOL) + .map(|idx| (98 + idx + p_idx) as u8 as char) + .collect::() + .try_into().unwrap(), + VerificationPrice(1000) + )) .collect::>() .try_into() - .unwrap()) + .unwrap() + ) ) ).try_collect().unwrap()), verifiers: SchemaVerifiers((0..SCHEMA_VERIFIERS - v).map(|idx| Verifier(Did([255 - idx as u8; 32]).into())).try_collect().unwrap()) @@ -160,19 +111,26 @@ crate::bench_with_all_pairs! { ) ).collect(); - AddSchemaMetadata { + SetSchemasMetadata { registry_id: TrustRegistryId(id), - schemas: schemas.clone(), + schemas: schemas.clone().into_iter().map(|(id, schema)| (id, SetOrAddOrRemoveOrModify::Set(schema))).collect(), nonce: 2u32.into() - }.execute_readonly(|action, set| Pallet::::add_schema_metadata_(action, set, Convener(did.into()))).unwrap(); + }.execute_readonly(|action, set| Pallet::::set_schemas_metadata_(action, set, ConvenerOrIssuerOrVerifier(did.into()))).unwrap(); let update_issuers = schemas.keys().map( |schema_id| { IssuersUpdate::::Modify( - MultiTargetUpdate::from_iter((0..i).map(|idx| (Issuer(Did([idx as u8; 32]).into()), SetOrModify::Set( + MultiTargetUpdate::from_iter((0..i).map(|idx| (Issuer(Did([idx as u8; 32]).into()), SetOrAddOrRemoveOrModify::Set( VerificationPrices( (0..SCHEMA_ISSUER_PRICES) - .map(|p_idx| ((0..SCHEMA_ISSUER_PRICE_SYMBOL).map(|idx| (98 + idx + p_idx) as u8 as char).collect::().try_into().unwrap(), Price(1000))) + .map(|p_idx| ( + (0..SCHEMA_ISSUER_PRICE_SYMBOL) + .map(|idx| (98 + idx + p_idx) as u8 as char) + .collect::() + .try_into() + .unwrap(), + VerificationPrice(1000) + )) .collect::>() .try_into() .unwrap() @@ -189,29 +147,34 @@ crate::bench_with_all_pairs! { } ); - let schemas_updates: BTreeMap<_, _> = + let schemas_updates: MultiTargetUpdate<_, _> = update_issuers .zip(update_verifiers) .zip(schemas.keys()) - .map(|((issuers, verifiers), id)| (id.clone(), TrustRegistrySchemaMetadataUpdate { + .map(|((issuers, verifiers), id)| (id.clone(), SetOrAddOrRemoveOrModify::Modify(OnlyExistent(TrustRegistrySchemaMetadataUpdate { verifiers: Some(verifiers), issuers: Some(issuers) - })) + })))) .collect(); - let update_schema_metadata = UpdateSchemaMetadata { + let set_schemas_metadata = SetSchemasMetadata { registry_id: TrustRegistryId(id), schemas: schemas_updates.clone(), nonce: 1u32.into() }; for (key, update) in schemas_updates { - update.apply_update(schemas.get_mut(&key).unwrap()); + let mut opt = schemas.remove(&key); + update.apply_update(&mut opt); + + if let Some(schema) = opt { + schemas.insert(key, schema); + } } - let sig = pair.sign(&update_schema_metadata.to_state_change().encode()); + let sig = pair.sign(&set_schemas_metadata.to_state_change().encode()); let signature = DidSignature::new(did, 1u32, sig).into(); - }: update_schema_metadata(RawOrigin::Signed(caller), update_schema_metadata, signature) + }: set_schemas_metadata(RawOrigin::Signed(caller), set_schemas_metadata, signature) verify { assert_eq!(schemas, TrustRegistrySchemasMetadata::::iter().map(|(schema_id, _, metadata)| (schema_id, metadata)).collect::>()); } @@ -341,11 +304,18 @@ crate::bench_with_all_pairs! { TrustRegistryIssuerSchemas::::insert(init_or_update_trust_registry.registry_id, issuer, IssuerSchemas(Default::default())); } + SuspendIssuers { + 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(); + let unsuspend_issuers = UnsuspendIssuers { registry_id: TrustRegistryId(id), issuers: issuers.into_iter().collect(), nonce: 1u32.into() }; + let sig = pair.sign(&unsuspend_issuers.to_state_change().encode()); let signature = DidSignature::new(did, 1u32, sig).into(); }: unsuspend_issuers(RawOrigin::Signed(caller), unsuspend_issuers.clone(), signature) diff --git a/pallets/core/src/modules/trust_registry/impl.rs b/pallets/core/src/modules/trust_registry/impl.rs index 3b875e9b6..878411edd 100644 --- a/pallets/core/src/modules/trust_registry/impl.rs +++ b/pallets/core/src/modules/trust_registry/impl.rs @@ -1,13 +1,7 @@ -use crate::util::{ - AddOrRemoveOrModify, ApplyUpdate, BoundedKeyValue, KeyedUpdate, MultiTargetUpdate, - ValidateUpdate, -}; +use crate::util::{ApplyUpdate, UpdateKind, ValidateUpdate}; use super::*; -type MultiSchemaUpdate = - MultiTargetUpdate>>; - impl Pallet { pub(super) fn init_or_update_trust_registry_( InitOrUpdateTrustRegistry { @@ -40,91 +34,35 @@ impl Pallet { Ok(()) } - pub(super) fn add_schema_metadata_( - AddSchemaMetadata { + pub(super) fn set_schemas_metadata_( + SetSchemasMetadata { registry_id, schemas, .. - }: AddSchemaMetadata, - registry_info: TrustRegistryInfo, - convener: Convener, - ) -> DispatchResult { - convener.ensure_controls::(®istry_info)?; - - for schema_id in schemas.keys() { - ensure!( - !TrustRegistrySchemasMetadata::::contains_key(schema_id, registry_id), - Error::::SchemaMetadataAlreadyExists - ); - } - - Self::try_update_verifiers_and_issuers_with(registry_id, |verifiers, issuers| { - for (schema_id, schema_metadata) in &schemas { - // `issuers` would be a map as `issuer_id` -> `schema_id`s - for issuer in schema_metadata.issuers.keys() { - issuers - .entry(*issuer) - .or_default() - .insert(*schema_id, AddOrRemoveOrModify::Add(())); - } - // `verifiers` would be a map as `verifier_id` -> `schema_id`s - for verifier in schema_metadata.verifiers.iter() { - verifiers - .entry(*verifier) - .or_default() - .insert(*schema_id, AddOrRemoveOrModify::Add(())); - } - } - Ok(()) - })?; - - for (schema_id, schema_metadata) in schemas { - Self::deposit_event(Event::SchemaMetadataAdded(registry_id, schema_id)); - - TrustRegistrySchemasMetadata::::insert(schema_id, registry_id, schema_metadata); - TrustRegistryStoredSchemas::::insert(registry_id, schema_id, ()); - } - - Ok(()) - } - - pub(super) fn update_schema_metadata_( - UpdateSchemaMetadata { - registry_id, - schemas, - .. - }: UpdateSchemaMetadata, + }: SetSchemasMetadata, registry_info: TrustRegistryInfo, actor: ConvenerOrIssuerOrVerifier, ) -> Result<(u32, u32, u32), DispatchError> { let (verifiers_len, issuers_len) = - Self::try_update_verifiers_and_issuers_with(registry_id, |verifiers, issuers| { - for (schema_id, update) in &schemas { + Self::try_update_issuers_and_verifiers_with(registry_id, |issuers, verifiers| { + let is_convener = Convener(*actor).ensure_controls(®istry_info).is_ok(); + + for (schema_id, update) in schemas.iter() { let schema_metadata = - TrustRegistrySchemasMetadata::::get(schema_id, registry_id) - .ok_or(Error::::SchemaMetadataDoesntExist)?; + TrustRegistrySchemasMetadata::::get(schema_id, registry_id); - if let Ok(_) = Convener(*actor).ensure_controls(®istry_info) { + if is_convener { update.ensure_valid(&Convener(*actor), &schema_metadata)?; } else { update.ensure_valid(&IssuerOrVerifier(*actor), &schema_metadata)?; } - if let Some(verifiers_update) = update.verifiers.as_ref() { - verifiers_update.record_inner_keys_diff( - &schema_metadata.verifiers, - *schema_id, - verifiers, - ) - } - - if let Some(issuers_update) = update.issuers.as_ref() { - issuers_update.record_inner_keys_diff( - &schema_metadata.issuers, - *schema_id, - issuers, - ) - } + update.record_inner_issuers_and_verifiers_diff( + &schema_metadata, + *schema_id, + issuers, + verifiers, + )?; } Ok((verifiers.len(), issuers.len())) @@ -133,11 +71,22 @@ impl Pallet { let schemas_len = schemas.len(); for (schema_id, update) in schemas { - Self::deposit_event(Event::SchemaMetadataUpdated(registry_id, schema_id)); - - TrustRegistrySchemasMetadata::::mutate(schema_id, registry_id, |schema_metadata| { - update.apply_update(schema_metadata.as_mut().unwrap()) - }); + TrustRegistrySchemasMetadata::::mutate_exists( + schema_id, + registry_id, + |schema_metadata| { + let event = match update.kind(&*schema_metadata) { + UpdateKind::Add => Event::SchemaMetadataAdded(registry_id, schema_id), + UpdateKind::Remove => Event::SchemaMetadataRemoved(registry_id, schema_id), + UpdateKind::Replace => Event::SchemaMetadataUpdated(registry_id, schema_id), + UpdateKind::None => return, + }; + + Self::deposit_event(event); + + update.apply_update(schema_metadata); + }, + ); } Ok((verifiers_len as u32, issuers_len as u32, schemas_len as u32)) @@ -242,48 +191,48 @@ impl Pallet { pub fn schema_metadata_by_registry_id( registry_id: TrustRegistryId, ) -> impl Iterator)> { - TrustRegistryStoredSchemas::::iter_prefix(registry_id).map(move |(schema_id, ())| { - ( - schema_id, - TrustRegistrySchemasMetadata::::get(schema_id, registry_id).unwrap(), - ) - }) + TrustRegistryStoredSchemas::::iter_prefix(registry_id).filter_map( + move |(schema_id, ())| { + TrustRegistrySchemasMetadata::::get(schema_id, registry_id) + .map(|schema_metadata| (schema_id, schema_metadata)) + }, + ) } /// Set `schema_id`s corresponding to each issuer and verifier of trust registry with given id. /// Will check that updates are valid and then update storage in `TrustRegistryVerifierSchemas` and `TrustRegistryIssuerSchemas` - fn try_update_verifiers_and_issuers_with( + fn try_update_issuers_and_verifiers_with( registry_id: TrustRegistryId, f: F, ) -> Result where F: FnOnce( - &mut MultiSchemaUpdate, &mut MultiSchemaUpdate, + &mut MultiSchemaUpdate, ) -> Result, { - let (mut verifiers, mut issuers) = Default::default(); + let (mut issuers, mut verifiers) = Default::default(); - let res = f(&mut verifiers, &mut issuers)?; + let res = f(&mut issuers, &mut verifiers)?; - for (issuer, update) in &issuers.0 { + for (issuer, update) in issuers.iter() { let schemas = TrustRegistryIssuerSchemas::::get(registry_id, issuer); update.ensure_valid(issuer, &schemas)?; } - for (verifier, update) in &verifiers.0 { + for (verifier, update) in verifiers.iter() { let schemas = TrustRegistryVerifierSchemas::::get(registry_id, verifier); update.ensure_valid(verifier, &schemas)?; } - for (verifier, update) in verifiers.0 { - TrustRegistryVerifierSchemas::::mutate(registry_id, verifier, |schemas| { + for (issuer, update) in issuers { + TrustRegistryIssuerSchemas::::mutate(registry_id, issuer, |schemas| { update.apply_update(schemas) }) } - for (issuer, update) in issuers.0 { - TrustRegistryIssuerSchemas::::mutate(registry_id, issuer, |schemas| { + for (verifier, update) in verifiers { + TrustRegistryVerifierSchemas::::mutate(registry_id, verifier, |schemas| { update.apply_update(schemas) }) } diff --git a/pallets/core/src/modules/trust_registry/mod.rs b/pallets/core/src/modules/trust_registry/mod.rs index ee710c47b..bc2a05038 100644 --- a/pallets/core/src/modules/trust_registry/mod.rs +++ b/pallets/core/src/modules/trust_registry/mod.rs @@ -4,7 +4,10 @@ use crate::{ common::ForSigType, deposit_indexed_event, did::{self, DidOrDidMethodKeySignature}, - util::{ActionWithNonce, ActionWrapper, BoundedKeyValue, SetOrModify}, + util::{ + ActionWithNonce, ActionWrapper, BoundedKeyValue, OnlyExistent, SetOrAddOrRemoveOrModify, + SetOrModify, + }, }; use frame_support::{pallet_prelude::*, weights::PostDispatchInfo}; @@ -40,7 +43,6 @@ pub mod pallet { /// Not the `TrustRegistry`'s `Convener`. NotTheConvener, NoSuchIssuer, - SchemaMetadataAlreadyExists, SchemaMetadataDoesntExist, AlreadySuspended, NotSuspended, @@ -55,6 +57,8 @@ pub mod pallet { SchemaMetadataAdded(TrustRegistryId, TrustRegistrySchemaId), /// Schema metadata was updated in the `TrustRegistry` with the given id. SchemaMetadataUpdated(TrustRegistryId, TrustRegistrySchemaId), + /// Schema metadata was removed from the `TrustRegistry` with the given id. + SchemaMetadataRemoved(TrustRegistryId, TrustRegistrySchemaId), /// `TrustRegistry`'s `Issuer` was suspended. IssuerSuspended(TrustRegistryId, Issuer), /// `TrustRegistry`'s `Issuer` was unsuspended. @@ -145,7 +149,7 @@ pub mod pallet { TrustRegistryId, Blake2_128Concat, Issuer, - TrustRegistryIssuerConfig, + TrustRegistryIssuerConfiguration, ValueQuery, >; @@ -166,41 +170,29 @@ pub mod pallet { .execute(ActionWrapper::wrap_fn(Self::init_or_update_trust_registry_)) } - /// Adds a new schema metadata entry (entries). - /// The DID signature signer must be the `Convener` owning this Trust Registry. - #[pallet::weight(SubstrateWeight::::add_schema_metadata(add_schema_metadata, signature))] - pub fn add_schema_metadata( - origin: OriginFor, - add_schema_metadata: AddSchemaMetadata, - signature: DidOrDidMethodKeySignature, - ) -> DispatchResult { - ensure_signed(origin)?; - - add_schema_metadata - .signed(signature) - .execute_readonly(Self::add_schema_metadata_) - } - - /// Updates the schema metadata entry (entries) with the supplied identifier(s). + /// Sets the schema metadata entry (entries) with the supplied identifier(s). + /// /// - `Convener` DID owning registry with the provided identifier can make any modifications. + /// /// - `Issuer` DID can only modify his verification prices and remove himself from the `issuers` map. + /// /// - `Verifier` DID can only remove himself from the `verifiers` set. - #[pallet::weight(SubstrateWeight::::update_schema_metadata(update_schema_metadata, signature))] - pub fn update_schema_metadata( + #[pallet::weight(SubstrateWeight::::set_schemas_metadata(set_schemas_metadata, signature))] + pub fn set_schemas_metadata( origin: OriginFor, - update_schema_metadata: UpdateSchemaMetadata, + set_schemas_metadata: SetSchemasMetadata, signature: DidOrDidMethodKeySignature, ) -> DispatchResultWithPostInfo { ensure_signed(origin)?; - let (ver, iss, schem) = update_schema_metadata + let (ver, iss, schem) = set_schemas_metadata .signed(signature.clone()) - .execute_readonly(Self::update_schema_metadata_)?; + .execute_readonly(Self::set_schemas_metadata_)?; let actual_weight = signature.weight_for_sig_type::( - || SubstrateWeight::::update_schema_metadata_sr25519(iss, ver, schem), - || SubstrateWeight::::update_schema_metadata_ed25519(iss, ver, schem), - || SubstrateWeight::::update_schema_metadata_secp256k1(iss, ver, schem), + || SubstrateWeight::::set_schemas_metadata_sr25519(iss, ver, schem), + || SubstrateWeight::::set_schemas_metadata_ed25519(iss, ver, schem), + || SubstrateWeight::::set_schemas_metadata_secp256k1(iss, ver, schem), ); Ok(PostDispatchInfo { @@ -255,59 +247,75 @@ pub mod pallet { impl SubstrateWeight { fn init_or_update_trust_registry( - InitOrUpdateTrustRegistry { name, .. }: &InitOrUpdateTrustRegistry, + InitOrUpdateTrustRegistry { + name, + gov_framework, + .. + }: &InitOrUpdateTrustRegistry, signed: &DidOrDidMethodKeySignature, ) -> Weight { signed.weight_for_sig_type::( - || Self::init_or_update_trust_registry_sr25519(name.len() as u32), - || Self::init_or_update_trust_registry_ed25519(name.len() as u32), - || Self::init_or_update_trust_registry_secp256k1(name.len() as u32), - ) - } - - fn add_schema_metadata( - AddSchemaMetadata { schemas, .. }: &AddSchemaMetadata, - signed: &DidOrDidMethodKeySignature, - ) -> Weight { - let issuers_len = schemas.values().map(|schema| schema.issuers.len()).sum(); - let verifiers_len = schemas.values().map(|schema| schema.verifiers.len()).sum(); - let schemas_len = schemas.len() as u32; - - signed.weight_for_sig_type::( - || Self::add_schema_metadata_sr25519(issuers_len, verifiers_len, schemas_len), - || Self::add_schema_metadata_ed25519(issuers_len, verifiers_len, schemas_len), - || Self::add_schema_metadata_secp256k1(issuers_len, verifiers_len, schemas_len), + || { + Self::init_or_update_trust_registry_sr25519( + name.len() as u32, + gov_framework.len() as u32, + ) + }, + || { + Self::init_or_update_trust_registry_ed25519( + name.len() as u32, + gov_framework.len() as u32, + ) + }, + || { + Self::init_or_update_trust_registry_secp256k1( + name.len() as u32, + gov_framework.len() as u32, + ) + }, ) } - fn update_schema_metadata( - UpdateSchemaMetadata { schemas, .. }: &UpdateSchemaMetadata, + fn set_schemas_metadata( + SetSchemasMetadata { schemas, .. }: &SetSchemasMetadata, signed: &DidOrDidMethodKeySignature, ) -> Weight { let issuers_len = schemas .values() - .map(|schema| { - schema.issuers.as_ref().map_or(0, |v| match v { - SetOrModify::Set(v) => v.capacity(), - SetOrModify::Modify(map) => map.len() as u32, - }) + .map(|schema_update| match schema_update { + SetOrAddOrRemoveOrModify::Add(schema) | SetOrAddOrRemoveOrModify::Set(schema) => { + schema.issuers.len() as u32 + } + SetOrAddOrRemoveOrModify::Modify(OnlyExistent(update)) => { + update.issuers.as_ref().map_or(0, |v| match v { + SetOrModify::Set(issuers) => issuers.capacity(), + SetOrModify::Modify(map) => map.len() as u32, + }) + } + SetOrAddOrRemoveOrModify::Remove => Default::default(), }) .sum(); let verifiers_len = schemas .values() - .map(|schema| { - schema.verifiers.as_ref().map_or(0, |v| match v { - SetOrModify::Set(v) => v.capacity(), - SetOrModify::Modify(map) => map.len() as u32, - }) + .map(|schema_update| match schema_update { + SetOrAddOrRemoveOrModify::Add(schema) | SetOrAddOrRemoveOrModify::Set(schema) => { + schema.verifiers.len() as u32 + } + SetOrAddOrRemoveOrModify::Modify(OnlyExistent(update)) => { + update.verifiers.as_ref().map_or(0, |v| match v { + SetOrModify::Set(verifiers) => verifiers.capacity(), + SetOrModify::Modify(map) => map.len() as u32, + }) + } + SetOrAddOrRemoveOrModify::Remove => Default::default(), }) .sum(); let schemas_len = schemas.len() as u32; signed.weight_for_sig_type::( - || Self::update_schema_metadata_sr25519(issuers_len, verifiers_len, schemas_len), - || Self::update_schema_metadata_ed25519(issuers_len, verifiers_len, schemas_len), - || Self::update_schema_metadata_secp256k1(issuers_len, verifiers_len, schemas_len), + || Self::set_schemas_metadata_sr25519(issuers_len, verifiers_len, schemas_len), + || Self::set_schemas_metadata_ed25519(issuers_len, verifiers_len, schemas_len), + || Self::set_schemas_metadata_secp256k1(issuers_len, verifiers_len, schemas_len), ) } diff --git a/pallets/core/src/modules/trust_registry/tests.rs b/pallets/core/src/modules/trust_registry/tests.rs index 07b5a73e4..6a395490d 100644 --- a/pallets/core/src/modules/trust_registry/tests.rs +++ b/pallets/core/src/modules/trust_registry/tests.rs @@ -18,7 +18,7 @@ use utils::BoundedString; type Mod = super::Pallet; crate::did_or_did_method_key! { - newdid => +newdid => #[test] fn init_or_update_trust_registry() { @@ -75,7 +75,12 @@ crate::did_or_did_method_key! { ), did::Error::::InvalidSignature ); - Mod::init_or_update_trust_registry(Origin::signed(alice), init_or_update_trust_registry.clone(), sig).unwrap(); + Mod::init_or_update_trust_registry( + Origin::signed(alice), + init_or_update_trust_registry.clone(), + sig, + ) + .unwrap(); let init_or_update_trust_registry_already_exists = InitOrUpdateTrustRegistry:: { registry_id: init_or_update_trust_registry.registry_id, @@ -146,7 +151,15 @@ crate::did_or_did_method_key! { }; let alice = 1u64; - ActionWrapper::::new(2, Convener(convener.into()), init_or_update_trust_registry.clone()).execute::(|action, set| Mod::init_or_update_trust_registry_(action.action, set, Convener(convener.into()))).unwrap(); + ActionWrapper::::new( + 2, + Convener(convener.into()), + init_or_update_trust_registry.clone(), + ) + .execute::(|action, set| { + Mod::init_or_update_trust_registry_(action.action, set, Convener(convener.into())) + }) + .unwrap(); let schemas: BTreeMap<_, _> = [( TrustRegistrySchemaId(rand::random()), @@ -161,7 +174,7 @@ crate::did_or_did_method_key! { .map(|_| rng.sample(Alphanumeric) as char) .collect::(); - (s.try_into().unwrap(), Price(random())) + (s.try_into().unwrap(), VerificationPrice(random())) }) .try_collect() .unwrap(), @@ -182,13 +195,23 @@ crate::did_or_did_method_key! { .into_iter() .collect(); - let add_schema_metadata = AddSchemaMetadata { + let add_schema_metadata = SetSchemasMetadata { registry_id: init_or_update_trust_registry.registry_id, - schemas: schemas.clone(), + schemas: schemas + .clone() + .into_iter() + .map(|(schema_id, schema_metadata)| { + (schema_id, SetOrAddOrRemoveOrModify::Add(schema_metadata)) + }) + .collect(), nonce: 3, }; - add_schema_metadata.execute_readonly(|action, reg| Mod::add_schema_metadata_(action, reg, Convener(convener.into()))).unwrap(); + add_schema_metadata + .execute_readonly(|action, reg| { + Mod::set_schemas_metadata_(action, reg, ConvenerOrIssuerOrVerifier(convener.into())) + }) + .unwrap(); let suspend_issuers = SuspendIssuers { issuers: schemas @@ -283,7 +306,11 @@ crate::did_or_did_method_key! { init_or_update_trust_registry.nonce(), Convener(convener.into()), init_or_update_trust_registry.clone(), - ).execute::(|action, reg| Mod::init_or_update_trust_registry_(action.action, reg, Convener(convener.into()))).unwrap(); + ) + .execute::(|action, reg| { + Mod::init_or_update_trust_registry_(action.action, reg, Convener(convener.into())) + }) + .unwrap(); let delegated = DelegatedIssuers( (0..10) @@ -308,7 +335,11 @@ crate::did_or_did_method_key! { ); assert_noop!( - Pallet::::update_delegated_issuers(Origin::signed(alice), update_delegated.clone(), sig.clone()), + Pallet::::update_delegated_issuers( + Origin::signed(alice), + update_delegated.clone(), + sig.clone() + ), Error::::NoSuchIssuer ); @@ -361,9 +392,14 @@ crate::did_or_did_method_key! { ); let alice = 1u64; - Mod::init_or_update_trust_registry(Origin::signed(alice), init_or_update_trust_registry.clone(), sig).unwrap(); + Mod::init_or_update_trust_registry( + Origin::signed(alice), + init_or_update_trust_registry.clone(), + sig, + ) + .unwrap(); - let schemas = [( + let schemas: BTreeMap<_, _> = [( TrustRegistrySchemaId(rand::random()), TrustRegistrySchemaMetadata { issuers: IssuersWith( @@ -376,7 +412,7 @@ crate::did_or_did_method_key! { .map(|_| rng.sample(Alphanumeric) as char) .collect::(); - (s.try_into().unwrap(), Price(random())) + (s.try_into().unwrap(), VerificationPrice(random())) }) .try_collect() .unwrap(), @@ -397,9 +433,15 @@ crate::did_or_did_method_key! { .into_iter() .collect(); - let add_schema_metadata = AddSchemaMetadata { + let add_schema_metadata = SetSchemasMetadata { registry_id: init_or_update_trust_registry.registry_id, - schemas, + schemas: schemas + .clone() + .into_iter() + .map(|(schema_id, schema_metadata)| { + (schema_id, SetOrAddOrRemoveOrModify::Add(schema_metadata)) + }) + .collect(), nonce: 3, }; let sig = did_sig( @@ -409,17 +451,25 @@ crate::did_or_did_method_key! { 1, ); - Mod::add_schema_metadata(Origin::signed(alice), add_schema_metadata.clone(), sig).unwrap(); + Mod::set_schemas_metadata(Origin::signed(alice), add_schema_metadata.clone(), sig).unwrap(); assert_eq!( TrustRegistrySchemasMetadata::get( add_schema_metadata.schemas.keys().next().unwrap(), init_or_update_trust_registry.registry_id ), - add_schema_metadata.schemas.values().next().cloned() + add_schema_metadata + .schemas + .values() + .map(|value| match value { + SetOrAddOrRemoveOrModify::Add(value) => value, + _ => unreachable!(), + }) + .next() + .cloned() ); - let add_other_schema_metadata = AddSchemaMetadata { + let add_other_schema_metadata = SetSchemasMetadata { registry_id: init_or_update_trust_registry.registry_id, schemas: add_schema_metadata.schemas.clone(), nonce: 2, @@ -433,17 +483,13 @@ crate::did_or_did_method_key! { ); assert_noop!( - Mod::add_schema_metadata( - Origin::signed(alice), - add_other_schema_metadata, - other_sig - ), - Error::::NotTheConvener + Mod::set_schemas_metadata(Origin::signed(alice), add_other_schema_metadata, other_sig), + UpdateError::InvalidActor ); - let add_other_schema_metadata = AddSchemaMetadata { + let add_other_schema_metadata = SetSchemasMetadata { registry_id: init_or_update_trust_registry.registry_id, - schemas: add_schema_metadata.schemas, + schemas: add_schema_metadata.schemas.clone(), nonce: 4, }; @@ -455,12 +501,8 @@ crate::did_or_did_method_key! { ); assert_noop!( - Mod::add_schema_metadata( - Origin::signed(alice), - add_other_schema_metadata, - sig - ), - Error::::SchemaMetadataAlreadyExists + Mod::set_schemas_metadata(Origin::signed(alice), add_other_schema_metadata, sig), + UpdateError::AlreadyExists ); }) } @@ -492,14 +534,19 @@ crate::did_or_did_method_key! { ); let alice = 1u64; - Mod::init_or_update_trust_registry(Origin::signed(alice), init_or_update_trust_registry.clone(), sig).unwrap(); + Mod::init_or_update_trust_registry( + Origin::signed(alice), + init_or_update_trust_registry.clone(), + sig, + ) + .unwrap(); let build_initial_prices = || { VerificationPrices( (0..5) .map(|_| (0..5).map(|_| random::() as char).collect::()) .chain(vec!["A", "B", "C", "D"].into_iter().map(|v| v.to_string())) - .map(|symbol| (symbol.try_into().unwrap(), Price(random()))) + .map(|symbol| (symbol.try_into().unwrap(), VerificationPrice(random()))) .collect::>() .try_into() .unwrap(), @@ -537,10 +584,17 @@ crate::did_or_did_method_key! { (id, TrustRegistrySchemaMetadata { issuers, verifiers }) }) .collect(); + let new_schema_id = TrustRegistrySchemaId([123; 32]); - let add_schema_metadata = AddSchemaMetadata { + let add_schema_metadata = SetSchemasMetadata { registry_id: init_or_update_trust_registry.registry_id, - schemas: schemas.clone(), + schemas: schemas + .clone() + .into_iter() + .map(|(schema_id, schema_metadata)| { + (schema_id, SetOrAddOrRemoveOrModify::Add(schema_metadata)) + }) + .collect(), nonce: 3, }; let sig = did_sig( @@ -551,71 +605,82 @@ crate::did_or_did_method_key! { ); let random_did = Did(rand::random()); - Mod::add_schema_metadata(Origin::signed(alice), add_schema_metadata, sig).unwrap(); + Mod::set_schemas_metadata(Origin::signed(alice), add_schema_metadata, sig).unwrap(); let cases = [ ( line!(), vec![( schema_ids[0], - Some(IssuersUpdate::::Modify(MultiTargetUpdate::from_iter( - [( - Issuer(issuer.into()), - SetOrModify::Modify(AddOrRemoveOrModify::Modify(OnlyExistent( - MultiTargetUpdate::from_iter([ - ( - BoundedString::new("W".to_string()).unwrap(), - SetOrModify::Modify(AddOrRemoveOrModify::Add(Price(100))), - ), - ( - BoundedString::new("A".to_string()).unwrap(), - SetOrModify::Modify(AddOrRemoveOrModify::Remove), - ), - ( - BoundedString::new("C".to_string()).unwrap(), - SetOrModify::Set(Price(400)), - ), - ( - BoundedString::new("EF".to_string()).unwrap(), - SetOrModify::Set(Price(500)), - ), - ]), - ))), - )], - ))), - None, + TrustRegistrySchemaMetadataModification::Modify(OnlyExistent( + TrustRegistrySchemaMetadataUpdate { + issuers: Some(IssuersUpdate::::Modify( + MultiTargetUpdate::from_iter([( + Issuer(issuer.into()), + SetOrAddOrRemoveOrModify::Modify(OnlyExistent( + MultiTargetUpdate::from_iter([ + ( + BoundedString::new("W".to_string()).unwrap(), + SetOrAddOrRemoveOrModify::Add(VerificationPrice(100)), + ), + ( + BoundedString::new("A".to_string()).unwrap(), + SetOrAddOrRemoveOrModify::Remove, + ), + ( + BoundedString::new("C".to_string()).unwrap(), + SetOrAddOrRemoveOrModify::Set(VerificationPrice(400)), + ), + ( + BoundedString::new("EF".to_string()).unwrap(), + SetOrAddOrRemoveOrModify::Set(VerificationPrice(500)), + ), + ]), + )), + )]), + )), + verifiers: None, + }, + )), )], Box::new( - |update: UpdateSchemaMetadata, + |update: SetSchemasMetadata, schemas: &mut BTreeMap< TrustRegistrySchemaId, TrustRegistrySchemaMetadata, >| { assert_noop!( - update.clone().execute_readonly(|action, reg| Mod::update_schema_metadata_(action, reg, - ConvenerOrIssuerOrVerifier(verifier.into()) - )), + update.clone().execute_readonly(|action, reg| { + Mod::set_schemas_metadata_( + action, + reg, + ConvenerOrIssuerOrVerifier(verifier.into()), + ) + }), UpdateError::InvalidActor ); - assert_ok!(update.execute_readonly(|action, reg| Mod::update_schema_metadata_(action, reg, - - ConvenerOrIssuerOrVerifier(issuer.into()) - ))); + assert_ok!(update.execute_readonly(|action, reg| { + Mod::set_schemas_metadata_( + action, + reg, + ConvenerOrIssuerOrVerifier(issuer.into()), + ) + })); let schema = schemas.get_mut(&schema_ids[0]).unwrap(); let issuer = schema.issuers.get_mut(&Issuer(issuer.into())).unwrap(); issuer - .try_insert(BoundedString::new("W".to_string()).unwrap(), Price(100)) + .try_insert(BoundedString::new("W".to_string()).unwrap(), VerificationPrice(100)) .unwrap(); issuer .remove(&BoundedString::new("A".to_string()).unwrap()) .unwrap(); issuer - .try_insert(BoundedString::new("C".to_string()).unwrap(), Price(400)) + .try_insert(BoundedString::new("C".to_string()).unwrap(), VerificationPrice(400)) .unwrap(); issuer - .try_insert(BoundedString::new("EF".to_string()).unwrap(), Price(500)) + .try_insert(BoundedString::new("EF".to_string()).unwrap(), VerificationPrice(500)) .unwrap(); }, ) as _, @@ -624,33 +689,43 @@ crate::did_or_did_method_key! { line!(), vec![( schema_ids[0], - Some(IssuersUpdate::::Modify(MultiTargetUpdate::from_iter( - [( - Issuer(Did(rand::random()).into()), - SetOrModify::Modify(AddOrRemoveOrModify::Modify(OnlyExistent( + SetOrAddOrRemoveOrModify::Modify(OnlyExistent( + TrustRegistrySchemaMetadataUpdate { + issuers: Some(IssuersUpdate::::Modify( MultiTargetUpdate::from_iter([( - BoundedString::new("W".to_string()).unwrap(), - SetOrModify::Modify(AddOrRemoveOrModify::Add(Price(100))), + Issuer(Did(rand::random()).into()), + SetOrAddOrRemoveOrModify::Modify(OnlyExistent( + MultiTargetUpdate::from_iter([( + BoundedString::new("W".to_string()).unwrap(), + SetOrAddOrRemoveOrModify::Add(VerificationPrice(100)), + )]), + )), )]), - ))), - )], - ))), - None, + )), + verifiers: None, + }, + )), )], Box::new( - |update: UpdateSchemaMetadata, + |update: SetSchemasMetadata, _schemas: &mut BTreeMap< TrustRegistrySchemaId, TrustRegistrySchemaMetadata, >| { assert_noop!( - update.clone().execute_readonly(|action, reg| Mod::update_schema_metadata_(action, reg, - ConvenerOrIssuerOrVerifier(issuer.into()) - )), + update.clone().execute_readonly(|action, reg| { + Mod::set_schemas_metadata_( + action, + reg, + ConvenerOrIssuerOrVerifier(issuer.into()), + ) + }), UpdateError::InvalidActor ); assert_noop!( - update.execute_readonly(|action, reg| Mod::update_schema_metadata_(action, reg, + update.execute_readonly(|action, reg| Mod::set_schemas_metadata_( + action, + reg, ConvenerOrIssuerOrVerifier(verifier.into()) )), UpdateError::InvalidActor @@ -662,33 +737,46 @@ crate::did_or_did_method_key! { line!(), vec![( schema_ids[0], - Some(IssuersUpdate::::Modify(MultiTargetUpdate::from_iter( - [( - Issuer(Did(rand::random()).into()), - SetOrModify::Set(VerificationPrices( - [(BoundedString::new("W".to_string()).unwrap(), Price(100))] - .into_iter() - .try_collect() - .unwrap(), + SetOrAddOrRemoveOrModify::Modify(OnlyExistent( + TrustRegistrySchemaMetadataUpdate { + issuers: Some(IssuersUpdate::::Modify( + MultiTargetUpdate::from_iter([( + Issuer(Did(rand::random()).into()), + SetOrAddOrRemoveOrModify::Set(VerificationPrices( + [( + BoundedString::new("W".to_string()).unwrap(), + VerificationPrice(100), + )] + .into_iter() + .try_collect() + .unwrap(), + )), + )]), )), - )], - ))), - None, + verifiers: None, + }, + )), )], Box::new( - |update: UpdateSchemaMetadata, + |update: SetSchemasMetadata, _schemas: &mut BTreeMap< TrustRegistrySchemaId, TrustRegistrySchemaMetadata, >| { assert_noop!( - update.clone().execute_readonly(|action, reg| Mod::update_schema_metadata_(action, reg, - ConvenerOrIssuerOrVerifier(issuer.into()) - )), + update.clone().execute_readonly(|action, reg| { + Mod::set_schemas_metadata_( + action, + reg, + ConvenerOrIssuerOrVerifier(issuer.into()), + ) + }), UpdateError::InvalidActor ); assert_noop!( - update.execute_readonly(|action, reg| Mod::update_schema_metadata_(action, reg, + update.execute_readonly(|action, reg| Mod::set_schemas_metadata_( + action, + reg, ConvenerOrIssuerOrVerifier(verifier.into()) )), UpdateError::InvalidActor @@ -697,7 +785,7 @@ crate::did_or_did_method_key! { ) as Box< dyn FnMut( - UpdateSchemaMetadata, + SetSchemasMetadata, &mut BTreeMap>, ), >, @@ -706,43 +794,51 @@ crate::did_or_did_method_key! { line!(), vec![( schema_ids[0], - Some(IssuersUpdate::::Modify(MultiTargetUpdate::from_iter( - [( - Issuer( - (*schemas - .get(&schema_ids[0]) - .unwrap() - .issuers - .keys().nth(2) - .unwrap()) - .into(), - ), - SetOrModify::Modify(AddOrRemoveOrModify::Modify(OnlyExistent( + SetOrAddOrRemoveOrModify::Modify(OnlyExistent( + TrustRegistrySchemaMetadataUpdate { + issuers: Some(IssuersUpdate::::Modify( MultiTargetUpdate::from_iter([( - BoundedString::new("EC".to_string()).unwrap(), - SetOrModify::Modify(AddOrRemoveOrModify::Add(Price(600))), + Issuer( + (*schemas + .get(&schema_ids[0]) + .unwrap() + .issuers + .keys() + .nth(2) + .unwrap()) + .into(), + ), + SetOrAddOrRemoveOrModify::Modify(OnlyExistent( + MultiTargetUpdate::from_iter([( + BoundedString::new("EC".to_string()).unwrap(), + SetOrAddOrRemoveOrModify::Add(VerificationPrice(600)), + )]), + )), )]), - ))), - )], - ))), - None, + )), + verifiers: None, + }, + )), )], Box::new( - |update: UpdateSchemaMetadata, + |update: SetSchemasMetadata, schemas: &mut BTreeMap< TrustRegistrySchemaId, TrustRegistrySchemaMetadata, >| { - assert_ok!(update.execute_readonly(|action, reg| Mod::update_schema_metadata_(action, reg, - - ConvenerOrIssuerOrVerifier(convener.into()) - )),); + assert_ok!(update.execute_readonly(|action, reg| { + Mod::set_schemas_metadata_( + action, + reg, + ConvenerOrIssuerOrVerifier(convener.into()), + ) + }),); let schema = schemas.get_mut(&schema_ids[0]).unwrap(); let key = *schema.issuers.keys().nth(2).unwrap(); let issuer = schema.issuers.get_mut(&key).unwrap(); issuer - .try_insert(BoundedString::new("EC".to_string()).unwrap(), Price(600)) + .try_insert(BoundedString::new("EC".to_string()).unwrap(), VerificationPrice(600)) .unwrap(); }, ) as _, @@ -751,33 +847,43 @@ crate::did_or_did_method_key! { line!(), vec![( schema_ids[0], - Some(IssuersUpdate::::Modify(MultiTargetUpdate::from_iter( - [( - Issuer(random_did.into()), - SetOrModify::Modify(AddOrRemoveOrModify::Modify(OnlyExistent( + SetOrAddOrRemoveOrModify::Modify(OnlyExistent( + TrustRegistrySchemaMetadataUpdate { + issuers: Some(IssuersUpdate::::Modify( MultiTargetUpdate::from_iter([( - BoundedString::new("W".to_string()).unwrap(), - SetOrModify::Modify(AddOrRemoveOrModify::Add(Price(100))), + Issuer(random_did.into()), + SetOrAddOrRemoveOrModify::Modify(OnlyExistent( + MultiTargetUpdate::from_iter([( + BoundedString::new("W".to_string()).unwrap(), + SetOrAddOrRemoveOrModify::Add(VerificationPrice(100)), + )]), + )), )]), - ))), - )], - ))), - None, + )), + verifiers: None, + }, + )), )], Box::new( - |update: UpdateSchemaMetadata, + |update: SetSchemasMetadata, _schemas: &mut BTreeMap< TrustRegistrySchemaId, TrustRegistrySchemaMetadata, >| { assert_noop!( - update.clone().execute_readonly(|action, reg| Mod::update_schema_metadata_(action, reg, - ConvenerOrIssuerOrVerifier(random_did.into()) - )), + update.clone().execute_readonly(|action, reg| { + Mod::set_schemas_metadata_( + action, + reg, + ConvenerOrIssuerOrVerifier(random_did.into()), + ) + }), UpdateError::InvalidActor ); assert_noop!( - update.execute_readonly(|action, reg| Mod::update_schema_metadata_(action, reg, + update.execute_readonly(|action, reg| Mod::set_schemas_metadata_( + action, + reg, ConvenerOrIssuerOrVerifier(convener.into()) )), UpdateError::DoesntExist @@ -790,79 +896,98 @@ crate::did_or_did_method_key! { vec![ ( schema_ids[0], - Some(IssuersUpdate::::Modify(MultiTargetUpdate::from_iter( - [( - Issuer(issuer.into()), - SetOrModify::Set(VerificationPrices( - [(BoundedString::new("A".to_string()).unwrap(), Price(800))] - .into_iter() - .try_collect() - .unwrap(), + SetOrAddOrRemoveOrModify::Modify(OnlyExistent( + TrustRegistrySchemaMetadataUpdate { + issuers: Some(IssuersUpdate::::Modify( + MultiTargetUpdate::from_iter([( + Issuer(issuer.into()), + SetOrAddOrRemoveOrModify::Set(VerificationPrices( + [( + BoundedString::new("A".to_string()).unwrap(), + VerificationPrice(800), + )] + .into_iter() + .try_collect() + .unwrap(), + )), + )]), )), - )], - ))), - None, + verifiers: None, + }, + )), ), ( schema_ids[1], - Some(IssuersUpdate::::Modify(MultiTargetUpdate::from_iter( - [( - Issuer( - (*schemas - .get(&schema_ids[1]) - .unwrap() - .issuers - .keys().nth(3) - .unwrap()) - .into(), - ), - SetOrModify::Modify(AddOrRemoveOrModify::Modify(OnlyExistent( + SetOrAddOrRemoveOrModify::Modify(OnlyExistent( + TrustRegistrySchemaMetadataUpdate { + issuers: Some(IssuersUpdate::::Modify( MultiTargetUpdate::from_iter([( - BoundedString::new("W".to_string()).unwrap(), - SetOrModify::Modify(AddOrRemoveOrModify::Add(Price(100))), + Issuer( + (*schemas + .get(&schema_ids[1]) + .unwrap() + .issuers + .keys() + .nth(3) + .unwrap()) + .into(), + ), + SetOrAddOrRemoveOrModify::Modify(OnlyExistent( + MultiTargetUpdate::from_iter([( + BoundedString::new("W".to_string()).unwrap(), + SetOrAddOrRemoveOrModify::Add(VerificationPrice(100)), + )]), + )), )]), - ))), - )], - ))), - None, + )), + verifiers: None, + }, + )), ), ], Box::new( - |update: UpdateSchemaMetadata, + |update: SetSchemasMetadata, schemas: &mut BTreeMap< TrustRegistrySchemaId, TrustRegistrySchemaMetadata, >| { assert_noop!( - update.clone().execute_readonly(|action, reg| Mod::update_schema_metadata_(action, reg, - ConvenerOrIssuerOrVerifier(issuer.into()) - )), + update.clone().execute_readonly(|action, reg| { + Mod::set_schemas_metadata_( + action, + reg, + ConvenerOrIssuerOrVerifier(issuer.into()), + ) + }), UpdateError::InvalidActor ); let schema_1 = schemas.get_mut(&schema_ids[1]).unwrap(); - let issuer_3 = (*schema_1 - .issuers - .keys().nth(3) - .unwrap()) - .into(); + let issuer_3 = (*schema_1.issuers.keys().nth(3).unwrap()).into(); assert_noop!( - update.clone().execute_readonly(|action, reg| Mod::update_schema_metadata_(action, reg, - ConvenerOrIssuerOrVerifier(issuer_3) - )), + update.clone().execute_readonly(|action, reg| { + Mod::set_schemas_metadata_( + action, + reg, + ConvenerOrIssuerOrVerifier(issuer_3), + ) + }), UpdateError::InvalidActor ); - assert_ok!(update.execute_readonly(|action, reg| Mod::update_schema_metadata_(action, reg, - - ConvenerOrIssuerOrVerifier(convener.into()) - )),); + assert_ok!(update.execute_readonly(|action, reg| { + Mod::set_schemas_metadata_( + action, + reg, + ConvenerOrIssuerOrVerifier(convener.into()), + ) + }),); schema_1 .issuers .get_mut(&Issuer(issuer_3)) .unwrap() - .try_insert(BoundedString::new("W".to_string()).unwrap(), Price(100)) + .try_insert(BoundedString::new("W".to_string()).unwrap(), VerificationPrice(100)) .unwrap(); let _ = schema_1; @@ -872,7 +997,7 @@ crate::did_or_did_method_key! { schema_0.issuers.get_mut(&Issuer(issuer.into())).unwrap(); *issuer = Default::default(); issuer - .try_insert(BoundedString::new("A".to_string()).unwrap(), Price(800)) + .try_insert(BoundedString::new("A".to_string()).unwrap(), VerificationPrice(800)) .unwrap(); }, ) as _, @@ -881,33 +1006,43 @@ crate::did_or_did_method_key! { line!(), vec![( schema_ids[0], - Some(IssuersUpdate::::Modify(MultiTargetUpdate::from_iter( - [( - Issuer(Did(rand::random()).into()), - SetOrModify::Modify(AddOrRemoveOrModify::Modify(OnlyExistent( + SetOrAddOrRemoveOrModify::Modify(OnlyExistent( + TrustRegistrySchemaMetadataUpdate { + issuers: Some(IssuersUpdate::::Modify( MultiTargetUpdate::from_iter([( - BoundedString::new("W".to_string()).unwrap(), - SetOrModify::Modify(AddOrRemoveOrModify::Add(Price(100))), + Issuer(Did(rand::random()).into()), + SetOrAddOrRemoveOrModify::Modify(OnlyExistent( + MultiTargetUpdate::from_iter([( + BoundedString::new("W".to_string()).unwrap(), + SetOrAddOrRemoveOrModify::Add(VerificationPrice(100)), + )]), + )), )]), - ))), - )], - ))), - None, + )), + verifiers: None, + }, + )), )], Box::new( - |update: UpdateSchemaMetadata, + |update: SetSchemasMetadata, _schemas: &mut BTreeMap< TrustRegistrySchemaId, TrustRegistrySchemaMetadata, >| { assert_noop!( - update.clone().execute_readonly(|action, reg| Mod::update_schema_metadata_(action, reg, - ConvenerOrIssuerOrVerifier(issuer.into()) - )), + update.clone().execute_readonly(|action, reg| { + Mod::set_schemas_metadata_( + action, + reg, + ConvenerOrIssuerOrVerifier(issuer.into()), + ) + }), UpdateError::InvalidActor ); assert_noop!( - update.execute_readonly(|action, reg| Mod::update_schema_metadata_(action, reg, + update.execute_readonly(|action, reg| Mod::set_schemas_metadata_( + action, + reg, ConvenerOrIssuerOrVerifier(verifier.into()) )), UpdateError::InvalidActor @@ -919,27 +1054,35 @@ crate::did_or_did_method_key! { line!(), vec![( schema_ids[0], - Some(IssuersUpdate::::Modify(MultiTargetUpdate::from_iter( - [( - Issuer(issuer.into()), - SetOrModify::Modify(AddOrRemoveOrModify::Modify(OnlyExistent( - MultiTargetUpdate::from_iter((0..20).map(|idx| ( - BoundedString::new(idx.to_string()).unwrap(), - SetOrModify::Modify(AddOrRemoveOrModify::Add(Price(100))), - ))), - ))), - )], - ))), - None, + SetOrAddOrRemoveOrModify::Modify(OnlyExistent( + TrustRegistrySchemaMetadataUpdate { + issuers: Some(IssuersUpdate::::Modify( + MultiTargetUpdate::from_iter([( + Issuer(issuer.into()), + SetOrAddOrRemoveOrModify::Modify(OnlyExistent( + MultiTargetUpdate::from_iter((0..20).map(|idx| { + ( + BoundedString::new(idx.to_string()).unwrap(), + SetOrAddOrRemoveOrModify::Add(VerificationPrice(100)), + ) + })), + )), + )]), + )), + verifiers: None, + }, + )), )], Box::new( - |update: UpdateSchemaMetadata, + |update: SetSchemasMetadata, _schemas: &mut BTreeMap< TrustRegistrySchemaId, TrustRegistrySchemaMetadata, >| { assert_noop!( - update.execute_readonly(|action, reg| Mod::update_schema_metadata_(action, reg, + update.execute_readonly(|action, reg| Mod::set_schemas_metadata_( + action, + reg, ConvenerOrIssuerOrVerifier(issuer.into()) )), UpdateError::CapacityOverflow @@ -949,31 +1092,49 @@ crate::did_or_did_method_key! { ), ( line!(), - vec![ - ( - schema_ids[0], - Some(IssuersUpdate::::Modify( - MultiTargetUpdate::from_iter((0..50).map(|idx| (Issuer(Did([idx as u8; 32]).into()), SetOrModify::Set( - VerificationPrices( - (0..15) - .map(|p_idx| ((0..10).map(|idx| (98 + idx + p_idx) as u8 as char).collect::().try_into().unwrap(), Price(1000))) - .collect::>() - .try_into() - .unwrap() - ) - )))) - )), - None - ) - ], + vec![( + schema_ids[0], + SetOrAddOrRemoveOrModify::Modify(OnlyExistent( + TrustRegistrySchemaMetadataUpdate { + issuers: Some(IssuersUpdate::::Modify( + MultiTargetUpdate::from_iter((0..50).map(|idx| { + ( + Issuer(Did([idx as u8; 32]).into()), + SetOrAddOrRemoveOrModify::Set(VerificationPrices( + (0..15) + .map(|p_idx| { + ( + (0..10) + .map(|idx| { + (98 + idx + p_idx) as u8 as char + }) + .collect::() + .try_into() + .unwrap(), + VerificationPrice(1000), + ) + }) + .collect::>() + .try_into() + .unwrap(), + )), + ) + })), + )), + verifiers: None, + }, + )), + )], Box::new( - |update: UpdateSchemaMetadata, + |update: SetSchemasMetadata, _schemas: &mut BTreeMap< TrustRegistrySchemaId, TrustRegistrySchemaMetadata, >| { assert_noop!( - update.execute_readonly(|action, reg| Mod::update_schema_metadata_(action, reg, + update.execute_readonly(|action, reg| Mod::set_schemas_metadata_( + action, + reg, ConvenerOrIssuerOrVerifier(convener.into()) )), UpdateError::CapacityOverflow @@ -985,42 +1146,47 @@ crate::did_or_did_method_key! { line!(), vec![( schema_ids[0], - Some(IssuersUpdate::::Modify(MultiTargetUpdate::from_iter( - [( - Issuer(issuer.into()), - SetOrModify::Modify(AddOrRemoveOrModify::Modify(OnlyExistent( - MultiTargetUpdate::from_iter((0..19).map(|idx| ( - BoundedString::new(idx.to_string()).unwrap(), - SetOrModify::Modify(AddOrRemoveOrModify::Add(Price(100))), - ))), - ))), - )], - ))), - None, + SetOrAddOrRemoveOrModify::Modify(OnlyExistent( + TrustRegistrySchemaMetadataUpdate { + issuers: Some(IssuersUpdate::::Modify( + MultiTargetUpdate::from_iter([( + Issuer(issuer.into()), + SetOrAddOrRemoveOrModify::Modify(OnlyExistent( + MultiTargetUpdate::from_iter((0..19).map(|idx| { + ( + BoundedString::new(idx.to_string()).unwrap(), + SetOrAddOrRemoveOrModify::Add(VerificationPrice(100)), + ) + })), + )), + )]), + )), + verifiers: None, + }, + )), )], Box::new( - |update: UpdateSchemaMetadata, + |update: SetSchemasMetadata, schemas: &mut BTreeMap< TrustRegistrySchemaId, TrustRegistrySchemaMetadata, >| { - assert_ok!( - update.execute_readonly( - |action, registry| Mod::update_schema_metadata_(action, registry, ConvenerOrIssuerOrVerifier(issuer.into())) + assert_ok!(update.execute_readonly(|action, registry| { + Mod::set_schemas_metadata_( + action, + registry, + ConvenerOrIssuerOrVerifier(issuer.into()), ) - ); + })); let schema_0 = schemas.get_mut(&schema_ids[0]).unwrap(); let issuer: &mut VerificationPrices = schema_0.issuers.get_mut(&Issuer(issuer.into())).unwrap(); - for (key, price) in (0..19).map(|idx| ( - BoundedString::new(idx.to_string()).unwrap(), - Price(100), - )) { - issuer - .try_insert(key, price) - .unwrap(); + for (key, price) in (0..19) + .map(|idx| (BoundedString::new(idx.to_string()).unwrap(), VerificationPrice(100))) + { + issuer.try_insert(key, price).unwrap(); } }, ) as _, @@ -1029,29 +1195,42 @@ crate::did_or_did_method_key! { line!(), vec![( schema_ids[0], - None, - VerifiersUpdate::::Modify(MultiTargetUpdate::from_iter([( - Verifier(verifier.into()), - AddOrRemoveOrModify::Remove, - )])) - .into(), + SetOrAddOrRemoveOrModify::Modify(OnlyExistent( + TrustRegistrySchemaMetadataUpdate { + issuers: None, + verifiers: VerifiersUpdate::::Modify( + MultiTargetUpdate::from_iter([( + Verifier(verifier.into()), + AddOrRemoveOrModify::Remove, + )]), + ) + .into(), + }, + )), )], Box::new( - |update: UpdateSchemaMetadata, + |update: SetSchemasMetadata, schemas: &mut BTreeMap< TrustRegistrySchemaId, TrustRegistrySchemaMetadata, >| { assert_noop!( - update.clone().execute_readonly(|action, reg| Mod::update_schema_metadata_(action, reg, - ConvenerOrIssuerOrVerifier(issuer.into()) - )), + update.clone().execute_readonly(|action, reg| { + Mod::set_schemas_metadata_( + action, + reg, + ConvenerOrIssuerOrVerifier(issuer.into()), + ) + }), UpdateError::InvalidActor ); - assert_ok!(update.execute_readonly(|action, reg| Mod::update_schema_metadata_(action, reg, - - ConvenerOrIssuerOrVerifier(verifier.into()) - ))); + assert_ok!(update.execute_readonly(|action, reg| { + Mod::set_schemas_metadata_( + action, + reg, + ConvenerOrIssuerOrVerifier(verifier.into()), + ) + })); let schema = schemas.get_mut(&schema_ids[0]).unwrap(); schema.verifiers.remove(&Verifier(verifier.into())); @@ -1062,29 +1241,42 @@ crate::did_or_did_method_key! { line!(), vec![( schema_ids[0], - None, - VerifiersUpdate::::Modify(MultiTargetUpdate::from_iter([( - Verifier(issuer.into()), - AddOrRemoveOrModify::Add(()), - )])) - .into(), + SetOrAddOrRemoveOrModify::Modify(OnlyExistent( + TrustRegistrySchemaMetadataUpdate { + issuers: None, + verifiers: VerifiersUpdate::::Modify( + MultiTargetUpdate::from_iter([( + Verifier(issuer.into()), + AddOrRemoveOrModify::Add(()), + )]), + ) + .into(), + }, + )), )], Box::new( - |update: UpdateSchemaMetadata, + |update: SetSchemasMetadata, schemas: &mut BTreeMap< TrustRegistrySchemaId, TrustRegistrySchemaMetadata, >| { assert_noop!( - update.clone().execute_readonly(|action, reg| Mod::update_schema_metadata_(action, reg, - ConvenerOrIssuerOrVerifier(verifier.into()) - )), + update.clone().execute_readonly(|action, reg| { + Mod::set_schemas_metadata_( + action, + reg, + ConvenerOrIssuerOrVerifier(verifier.into()), + ) + }), UpdateError::InvalidActor ); - assert_ok!(update.execute_readonly(|action, reg| Mod::update_schema_metadata_(action, reg, - - ConvenerOrIssuerOrVerifier(convener.into()) - ))); + assert_ok!(update.execute_readonly(|action, reg| { + Mod::set_schemas_metadata_( + action, + reg, + ConvenerOrIssuerOrVerifier(convener.into()), + ) + })); let schema = schemas.get_mut(&schema_ids[0]).unwrap(); schema @@ -1098,45 +1290,180 @@ crate::did_or_did_method_key! { line!(), vec![( schema_ids[0], - None, - VerifiersUpdate::::Set(SchemaVerifiers(Default::default())).into(), + SetOrAddOrRemoveOrModify::Modify(OnlyExistent( + TrustRegistrySchemaMetadataUpdate { + issuers: None, + verifiers: VerifiersUpdate::::Set(SchemaVerifiers( + Default::default(), + )) + .into(), + }, + )), )], Box::new( - |update: UpdateSchemaMetadata, + |update: SetSchemasMetadata, schemas: &mut BTreeMap< TrustRegistrySchemaId, TrustRegistrySchemaMetadata, >| { assert_noop!( - update.clone().execute_readonly(|action, reg| Mod::update_schema_metadata_(action, reg, - ConvenerOrIssuerOrVerifier(issuer.into()) - )), + update.clone().execute_readonly(|action, reg| { + Mod::set_schemas_metadata_( + action, + reg, + ConvenerOrIssuerOrVerifier(issuer.into()), + ) + }), UpdateError::InvalidActor ); - assert_ok!(update.execute_readonly(|action, reg| Mod::update_schema_metadata_(action, reg, - - ConvenerOrIssuerOrVerifier(convener.into()) - ))); + assert_ok!(update.execute_readonly(|action, reg| { + Mod::set_schemas_metadata_( + action, + reg, + ConvenerOrIssuerOrVerifier(convener.into()), + ) + })); let schema = schemas.get_mut(&schema_ids[0]).unwrap(); *schema.verifiers = Default::default(); }, ) as _, ), + ( + line!(), + vec![( + schema_ids[0], + SetOrAddOrRemoveOrModify::Add(TrustRegistrySchemaMetadata { + issuers: Default::default(), + verifiers: Default::default(), + }), + )], + Box::new( + |update: SetSchemasMetadata, + _schemas: &mut BTreeMap< + TrustRegistrySchemaId, + TrustRegistrySchemaMetadata, + >| { + assert_noop!( + update.clone().execute_readonly(|action, reg| { + Mod::set_schemas_metadata_( + action, + reg, + ConvenerOrIssuerOrVerifier(convener.into()), + ) + }), + UpdateError::AlreadyExists + ); + }, + ) as _, + ), + ( + line!(), + vec![ + (schema_ids[4], SetOrAddOrRemoveOrModify::Remove), + ( + new_schema_id, + SetOrAddOrRemoveOrModify::Add( + schemas.get(&schema_ids[3]).cloned().unwrap(), + ), + ), + ], + Box::new( + |update: SetSchemasMetadata, + schemas: &mut BTreeMap< + TrustRegistrySchemaId, + TrustRegistrySchemaMetadata, + >| { + assert_ok!(update.execute_readonly(|action, reg| { + Mod::set_schemas_metadata_( + action, + reg, + ConvenerOrIssuerOrVerifier(convener.into()), + ) + })); + + let new_schema = schemas.get(&schema_ids[3]).cloned().unwrap(); + + schemas.remove(&schema_ids[4]); + schemas.insert(new_schema_id, new_schema); + }, + ) as _, + ), + ( + line!(), + vec![(schema_ids[0], SetOrAddOrRemoveOrModify::Remove)], + Box::new( + |update: SetSchemasMetadata, + schemas: &mut BTreeMap< + TrustRegistrySchemaId, + TrustRegistrySchemaMetadata, + >| { + assert_noop!( + update.clone().execute_readonly(|action, reg| { + Mod::set_schemas_metadata_( + action, + reg, + ConvenerOrIssuerOrVerifier(issuer.into()), + ) + }), + UpdateError::InvalidActor + ); + + assert_ok!(update.clone().execute_readonly(|action, reg| { + Mod::set_schemas_metadata_( + action, + reg, + ConvenerOrIssuerOrVerifier(convener.into()), + ) + })); + + schemas.remove(&schema_ids[0]); + }, + ) as _, + ), + ( + line!(), + vec![( + schema_ids[0], + SetOrAddOrRemoveOrModify::Add(schemas.get(&schema_ids[2]).cloned().unwrap()), + )], + Box::new( + |update: SetSchemasMetadata, + schemas: &mut BTreeMap< + TrustRegistrySchemaId, + TrustRegistrySchemaMetadata, + >| { + assert_noop!( + update.clone().execute_readonly(|action, reg| { + Mod::set_schemas_metadata_( + action, + reg, + ConvenerOrIssuerOrVerifier(issuer.into()), + ) + }), + UpdateError::InvalidActor + ); + + assert_ok!(update.execute_readonly(|action, reg| { + Mod::set_schemas_metadata_( + action, + reg, + ConvenerOrIssuerOrVerifier(convener.into()), + ) + })); + + let new_schema = schemas.get(&schema_ids[2]).cloned().unwrap(); + + schemas.insert(schema_ids[0].clone(), new_schema); + }, + ) as _, + ), ]; for (line, updates, mut execute) in cases { - let update = UpdateSchemaMetadata { + let update = SetSchemasMetadata { registry_id: init_or_update_trust_registry.registry_id, - schemas: updates - .into_iter() - .map(|(schema_id, issuers, verifiers)| { - ( - schema_id, - TrustRegistrySchemaMetadataUpdate { issuers, verifiers }, - ) - }) - .collect(), + schemas: FromIterator::from_iter(updates), nonce: 2, }; diff --git a/pallets/core/src/modules/trust_registry/types.rs b/pallets/core/src/modules/trust_registry/types.rs index 372e7766f..abee6966a 100644 --- a/pallets/core/src/modules/trust_registry/types.rs +++ b/pallets/core/src/modules/trust_registry/types.rs @@ -106,13 +106,13 @@ impl_wrapper!(ConvenerOrIssuerOrVerifier(DidOrDidMethodKey)); impl AuthorizeTarget for ConvenerOrIssuerOrVerifier {} impl AuthorizeTarget for ConvenerOrIssuerOrVerifier {} -/// Price to verify a credential. Lowest denomination should be used +/// Price to verify a credential. Lowest denomination should be used. #[derive(Encode, Decode, Clone, Debug, PartialEq, Eq, Copy, 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 Price(#[codec(compact)] pub u128); +pub struct VerificationPrice(#[codec(compact)] pub u128); /// Price of verifying a credential as per different currencies #[derive( @@ -137,12 +137,12 @@ pub struct VerificationPrices( #[cfg_attr(feature = "serde", serde(with = "btree_map"))] pub BoundedBTreeMap< BoundedString, - Price, + VerificationPrice, T::MaxPriceCurrencies, >, ); -impl_wrapper!(VerificationPrices where T: Limits => (BoundedBTreeMap, Price, T::MaxPriceCurrencies>)); +impl_wrapper!(VerificationPrices where T: Limits => (BoundedBTreeMap, VerificationPrice, T::MaxPriceCurrencies>)); #[derive( Encode, @@ -170,7 +170,14 @@ pub struct AggregatedIssuerInfo { /// A map from `Issuer` to some value. #[derive( - Encode, Decode, CloneNoBound, PartialEqNoBound, EqNoBound, DebugNoBound, MaxEncodedLen, + Encode, + Decode, + CloneNoBound, + PartialEqNoBound, + EqNoBound, + DebugNoBound, + MaxEncodedLen, + DefaultNoBound, )] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( @@ -197,7 +204,14 @@ pub type AggregatedSchemaIssuers = IssuersWith>; /// Schema `Verifier`s. #[derive( - Encode, Decode, CloneNoBound, PartialEqNoBound, EqNoBound, DebugNoBound, MaxEncodedLen, + Encode, + Decode, + CloneNoBound, + PartialEqNoBound, + EqNoBound, + DebugNoBound, + MaxEncodedLen, + DefaultNoBound, )] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( @@ -274,7 +288,7 @@ impl DelegatedUpdate { #[derive(scale_info_derive::TypeInfo)] #[scale_info(skip_type_params(T))] #[scale_info(omit_prefix)] -pub struct TrustRegistryIssuerConfig { +pub struct TrustRegistryIssuerConfiguration { pub suspended: bool, pub delegated: DelegatedIssuers, } @@ -296,6 +310,31 @@ pub struct TrustRegistrySchemaMetadata { pub verifiers: SchemaVerifiers, } +pub type MultiSchemaUpdate> = + MultiTargetUpdate>; + +impl TrustRegistrySchemaMetadata { + fn record_inner_issuers_and_verifiers_diff( + &self, + issuers: &mut MultiSchemaUpdate, + verifiers: &mut MultiSchemaUpdate, + mut record_update: F, + ) -> Result<(), DuplicateKey> + where + F: FnMut(&mut MultiTargetUpdate) -> Result<(), DuplicateKey>, + { + for issuer in self.issuers.keys().cloned() { + record_update(issuers.entry(issuer).or_default())?; + } + + for verifier in self.verifiers.iter().cloned() { + record_update(verifiers.entry(verifier).or_default())?; + } + + Ok(()) + } +} + /// `Trust Registry` schema metadata. #[derive( Encode, Decode, CloneNoBound, PartialEqNoBound, EqNoBound, DebugNoBound, MaxEncodedLen, @@ -326,7 +365,7 @@ impl TrustRegistrySchemaMetadata { .0 .into_iter() .map(|(issuer, verification_prices)| { - let TrustRegistryIssuerConfig { + let TrustRegistryIssuerConfiguration { suspended, delegated, } = super::TrustRegistryIssuerConfigurations::::get(registry_id, issuer); @@ -446,15 +485,12 @@ pub type IssuersUpdate = SetOrModify< SchemaIssuers, MultiTargetUpdate< Issuer, - SetOrModify< + SetOrAddOrRemoveOrModify< VerificationPrices, - AddOrRemoveOrModify< - VerificationPrices, - OnlyExistent< - MultiTargetUpdate< - BoundedString<::MaxIssuerPriceCurrencySymbolSize>, - SetOrModify>, - >, + OnlyExistent< + MultiTargetUpdate< + BoundedString<::MaxIssuerPriceCurrencySymbolSize>, + SetOrAddOrRemoveOrModify, >, >, >, @@ -475,6 +511,94 @@ pub struct TrustRegistrySchemaMetadataUpdate { pub verifiers: Option>, } +impl TrustRegistrySchemaMetadataUpdate { + fn record_inner_issuers_and_verifiers_diff( + &self, + entity: &TrustRegistrySchemaMetadata, + schema_id: TrustRegistrySchemaId, + issuers: &mut MultiSchemaUpdate, + verifiers: &mut MultiSchemaUpdate, + ) -> Result<(), DuplicateKey> { + if let Some(verifiers_update) = self.verifiers.as_ref() { + verifiers_update.record_inner_keys_diff(&entity.verifiers, schema_id, verifiers)? + } + + if let Some(issuers_update) = self.issuers.as_ref() { + issuers_update.record_inner_keys_diff(&entity.issuers, schema_id, issuers)? + } + + Ok(()) + } +} + +pub type TrustRegistrySchemaMetadataModification = SetOrAddOrRemoveOrModify< + TrustRegistrySchemaMetadata, + OnlyExistent>, +>; + +impl TrustRegistrySchemaMetadataModification { + pub(super) fn record_inner_issuers_and_verifiers_diff( + &self, + entity: &Option>, + schema_id: TrustRegistrySchemaId, + issuers: &mut MultiSchemaUpdate, + verifiers: &mut MultiSchemaUpdate, + ) -> Result<(), DuplicateKey> { + match self { + Self::Add(new) => new.record_inner_issuers_and_verifiers_diff( + issuers, + verifiers, + MultiTargetUpdate::bind_modifier( + MultiTargetUpdate::insert_update, + schema_id, + AddOrRemoveOrModify::Add(()), + ), + ), + Self::Remove => entity + .as_ref() + .expect("An entity expected") + .record_inner_issuers_and_verifiers_diff( + issuers, + verifiers, + MultiTargetUpdate::bind_modifier( + MultiTargetUpdate::insert_update, + schema_id, + AddOrRemoveOrModify::Remove, + ), + ), + Self::Set(new) => { + if let Some(old) = entity { + old.record_inner_issuers_and_verifiers_diff( + issuers, + verifiers, + MultiTargetUpdate::bind_modifier( + MultiTargetUpdate::insert_update, + schema_id, + AddOrRemoveOrModify::Remove, + ), + )?; + } + + new.record_inner_issuers_and_verifiers_diff( + issuers, + verifiers, + MultiTargetUpdate::bind_modifier( + MultiTargetUpdate::insert_update_or_remove_duplicate, + schema_id, + AddOrRemoveOrModify::Add(()), + ), + ) + } + Self::Modify(OnlyExistent(update)) => update.record_inner_issuers_and_verifiers_diff( + entity.as_ref().expect("An entity expected"), + schema_id, + issuers, + verifiers, + ), + } + } +} + /// Unique identifier for the `Trust Registry`. #[derive(Encode, Decode, Clone, Debug, PartialEq, Eq, Copy, Ord, PartialOrd, MaxEncodedLen)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] diff --git a/pallets/core/src/modules/trust_registry/update_rules.rs b/pallets/core/src/modules/trust_registry/update_rules.rs index 3d52ff8da..2909d6a23 100644 --- a/pallets/core/src/modules/trust_registry/update_rules.rs +++ b/pallets/core/src/modules/trust_registry/update_rules.rs @@ -4,12 +4,10 @@ use crate::{common::Limits, util::batch_update::*}; impl ApplyUpdate> for TrustRegistrySchemaMetadataUpdate { - type Output<'output> = () where TrustRegistrySchemaMetadata: 'output; - fn apply_update( self, TrustRegistrySchemaMetadata { issuers, verifiers }: &mut TrustRegistrySchemaMetadata, - ) -> Self::Output<'_> { + ) { let Self { issuers: issuers_update, verifiers: verifiers_update, @@ -49,7 +47,7 @@ where A: CanUpdateAndCanUpdateKeyed> + CanUpdateAndCanUpdateKeyed> + CanUpdateAndCanUpdateKeyed> - + CanUpdate, + + CanUpdate, { fn ensure_valid( &self, @@ -67,30 +65,30 @@ where } } -impl CanUpdate for Convener { - fn can_add(&self, _entity: &Price) -> bool { +impl CanUpdate for Convener { + fn can_add(&self, _entity: &VerificationPrice) -> bool { true } - fn can_remove(&self, _entity: &Price) -> bool { + fn can_remove(&self, _entity: &VerificationPrice) -> bool { true } - fn can_replace(&self, _new: &Price, _entity: &Price) -> bool { + fn can_replace(&self, _new: &VerificationPrice, _entity: &VerificationPrice) -> bool { true } } -impl CanUpdate for IssuerOrVerifier { - fn can_add(&self, _entity: &Price) -> bool { +impl CanUpdate for IssuerOrVerifier { + fn can_add(&self, _entity: &VerificationPrice) -> bool { true } - fn can_remove(&self, _entity: &Price) -> bool { + fn can_remove(&self, _entity: &VerificationPrice) -> bool { true } - fn can_replace(&self, _new: &Price, _entity: &Price) -> bool { + fn can_replace(&self, _new: &VerificationPrice, _entity: &VerificationPrice) -> bool { true } } @@ -269,3 +267,23 @@ impl CanUpdate> for Convener { true } } + +impl CanUpdate> for Convener { + fn can_add(&self, _entity: &TrustRegistrySchemaMetadata) -> bool { + true + } + + fn can_remove(&self, _entity: &TrustRegistrySchemaMetadata) -> bool { + true + } + + fn can_replace( + &self, + _new: &TrustRegistrySchemaMetadata, + _entity: &TrustRegistrySchemaMetadata, + ) -> bool { + true + } +} + +impl CanUpdate> for IssuerOrVerifier {} diff --git a/pallets/core/src/modules/trust_registry/weights.rs b/pallets/core/src/modules/trust_registry/weights.rs index e36458634..e5267fa65 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: 2023-10-22, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-06, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` //! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: None, DB CACHE: 1024 // Executed Command: @@ -28,15 +28,12 @@ use sp_std::marker::PhantomData; /// Weight functions needed for trust_registry. pub trait WeightInfo { - fn init_or_update_trust_registry_sr25519(n: u32) -> Weight; - fn init_or_update_trust_registry_ed25519(n: u32) -> Weight; - fn init_or_update_trust_registry_secp256k1(n: u32) -> Weight; - fn add_schema_metadata_sr25519(i: u32, v: u32, s: u32) -> Weight; - fn add_schema_metadata_ed25519(i: u32, v: u32, s: u32) -> Weight; - fn add_schema_metadata_secp256k1(i: u32, v: u32, s: u32) -> Weight; - fn update_schema_metadata_sr25519(i: u32, v: u32, s: u32) -> Weight; - fn update_schema_metadata_ed25519(i: u32, v: u32, s: u32) -> Weight; - fn update_schema_metadata_secp256k1(i: u32, v: u32, s: u32) -> Weight; + fn init_or_update_trust_registry_sr25519(n: u32, g: u32) -> Weight; + fn init_or_update_trust_registry_ed25519(n: u32, g: u32) -> Weight; + fn init_or_update_trust_registry_secp256k1(n: u32, g: u32) -> Weight; + fn set_schemas_metadata_sr25519(i: u32, v: u32, s: u32) -> Weight; + fn set_schemas_metadata_ed25519(i: u32, v: u32, s: u32) -> Weight; + fn set_schemas_metadata_secp256k1(i: u32, v: u32, s: u32) -> Weight; fn update_delegated_issuers_sr25519(i: u32) -> Weight; fn update_delegated_issuers_ed25519(i: u32) -> Weight; fn update_delegated_issuers_secp256k1(i: u32) -> Weight; @@ -51,334 +48,254 @@ 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) -> Weight { - Weight::from_ref_time(67_521_000) // Standard Error: 9_000 - .saturating_add(Weight::from_ref_time(29_000).saturating_mul(n as u64)) + fn init_or_update_trust_registry_sr25519(n: u32, g: u32) -> Weight { + Weight::from_ref_time(64_792_000) // Standard Error: 5_000 + .saturating_add(Weight::from_ref_time(18_000).saturating_mul(n as u64)) // Standard Error: 1_000 + .saturating_add(Weight::from_ref_time(4_000).saturating_mul(g as u64)) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(4)) } - fn init_or_update_trust_registry_ed25519(_n: u32) -> Weight { - Weight::from_ref_time(67_974_000) + fn init_or_update_trust_registry_ed25519(_n: u32, g: u32) -> Weight { + Weight::from_ref_time(63_615_000) // Standard Error: 1_000 + .saturating_add(Weight::from_ref_time(6_000).saturating_mul(g as u64)) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(4)) } - fn init_or_update_trust_registry_secp256k1(_n: u32) -> Weight { - Weight::from_ref_time(160_766_000) + fn init_or_update_trust_registry_secp256k1(_n: u32, _g: u32) -> Weight { + Weight::from_ref_time(157_554_000) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(4)) } - fn add_schema_metadata_sr25519(i: u32, v: u32, s: u32) -> Weight { - Weight::from_ref_time(0) // Standard Error: 120_000 - .saturating_add(Weight::from_ref_time(54_765_000).saturating_mul(i as u64)) // Standard Error: 120_000 - .saturating_add(Weight::from_ref_time(4_719_000).saturating_mul(v as u64)) // Standard Error: 631_000 - .saturating_add(Weight::from_ref_time(288_634_000).saturating_mul(s as u64)) + fn set_schemas_metadata_sr25519(i: u32, v: u32, s: u32) -> Weight { + Weight::from_ref_time(161_621_000) // Standard Error: 135_000 + .saturating_add(Weight::from_ref_time(6_973_000).saturating_mul(v as u64)) // Standard Error: 707_000 + .saturating_add(Weight::from_ref_time(345_665_000).saturating_mul(s as u64)) .saturating_add(T::DbWeight::get().reads(3)) - .saturating_add(T::DbWeight::get().reads(1_u64.saturating_mul(i as u64))) - .saturating_add(T::DbWeight::get().reads(1_u64.saturating_mul(v as u64))) - .saturating_add(T::DbWeight::get().reads(1_u64.saturating_mul(s as u64))) - .saturating_add(T::DbWeight::get().writes(2)) - .saturating_add(T::DbWeight::get().writes(1_u64.saturating_mul(i as u64))) - .saturating_add(T::DbWeight::get().writes(1_u64.saturating_mul(v as u64))) - .saturating_add(T::DbWeight::get().writes(2_u64.saturating_mul(s as u64))) - } - fn add_schema_metadata_ed25519(i: u32, v: u32, s: u32) -> Weight { - Weight::from_ref_time(0) // Standard Error: 148_000 - .saturating_add(Weight::from_ref_time(47_419_000).saturating_mul(i as u64)) // Standard Error: 148_000 - .saturating_add(Weight::from_ref_time(345_000).saturating_mul(v as u64)) // Standard Error: 780_000 - .saturating_add(Weight::from_ref_time(242_555_000).saturating_mul(s as u64)) + .saturating_add(T::DbWeight::get().reads((1 as u64).saturating_mul(i as u64))) + .saturating_add(T::DbWeight::get().reads((1 as u64).saturating_mul(v as u64))) + .saturating_add(T::DbWeight::get().reads((1 as u64).saturating_mul(s as u64))) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(i as u64))) + .saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(v as u64))) + .saturating_add(T::DbWeight::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(666_257_000) // Standard Error: 206_000 + .saturating_add(Weight::from_ref_time(2_161_000).saturating_mul(v as u64)) // Standard Error: 1_080_000 + .saturating_add(Weight::from_ref_time(324_988_000).saturating_mul(s as u64)) .saturating_add(T::DbWeight::get().reads(3)) - .saturating_add(T::DbWeight::get().reads(1_u64.saturating_mul(i as u64))) - .saturating_add(T::DbWeight::get().reads(1_u64.saturating_mul(v as u64))) - .saturating_add(T::DbWeight::get().reads(1_u64.saturating_mul(s as u64))) - .saturating_add(T::DbWeight::get().writes(2)) - .saturating_add(T::DbWeight::get().writes(1_u64.saturating_mul(i as u64))) - .saturating_add(T::DbWeight::get().writes(1_u64.saturating_mul(v as u64))) - .saturating_add(T::DbWeight::get().writes(2_u64.saturating_mul(s as u64))) - } - fn add_schema_metadata_secp256k1(i: u32, v: u32, s: u32) -> Weight { - Weight::from_ref_time(0) // Standard Error: 85_000 - .saturating_add(Weight::from_ref_time(53_089_000).saturating_mul(i as u64)) // Standard Error: 85_000 - .saturating_add(Weight::from_ref_time(5_454_000).saturating_mul(v as u64)) // Standard Error: 446_000 - .saturating_add(Weight::from_ref_time(274_233_000).saturating_mul(s as u64)) - .saturating_add(T::DbWeight::get().reads(3)) - .saturating_add(T::DbWeight::get().reads(1_u64.saturating_mul(i as u64))) - .saturating_add(T::DbWeight::get().reads(1_u64.saturating_mul(v as u64))) - .saturating_add(T::DbWeight::get().reads(1_u64.saturating_mul(s as u64))) - .saturating_add(T::DbWeight::get().writes(2)) - .saturating_add(T::DbWeight::get().writes(1_u64.saturating_mul(i as u64))) - .saturating_add(T::DbWeight::get().writes(1_u64.saturating_mul(v as u64))) - .saturating_add(T::DbWeight::get().writes(2_u64.saturating_mul(s as u64))) - } - fn update_schema_metadata_sr25519(i: u32, v: u32, s: u32) -> Weight { - Weight::from_ref_time(487_656_000) // Standard Error: 98_000 - .saturating_add(Weight::from_ref_time(5_448_000).saturating_mul(v as u64)) // Standard Error: 513_000 - .saturating_add(Weight::from_ref_time(301_780_000).saturating_mul(s as u64)) - .saturating_add(T::DbWeight::get().reads(3)) - .saturating_add(T::DbWeight::get().reads(1_u64.saturating_mul(i as u64))) - .saturating_add(T::DbWeight::get().reads(1_u64.saturating_mul(v as u64))) - .saturating_add(T::DbWeight::get().reads(1_u64.saturating_mul(s as u64))) - .saturating_add(T::DbWeight::get().writes(2)) - .saturating_add(T::DbWeight::get().writes(1_u64.saturating_mul(i as u64))) - .saturating_add(T::DbWeight::get().writes(1_u64.saturating_mul(v as u64))) - .saturating_add(T::DbWeight::get().writes(1_u64.saturating_mul(s as u64))) - } - fn update_schema_metadata_ed25519(i: u32, v: u32, s: u32) -> Weight { - Weight::from_ref_time(754_704_000) // Standard Error: 196_000 - .saturating_add(Weight::from_ref_time(4_864_000).saturating_mul(v as u64)) // Standard Error: 1_027_000 - .saturating_add(Weight::from_ref_time(286_870_000).saturating_mul(s as u64)) - .saturating_add(T::DbWeight::get().reads(3)) - .saturating_add(T::DbWeight::get().reads(1_u64.saturating_mul(i as u64))) - .saturating_add(T::DbWeight::get().reads(1_u64.saturating_mul(v as u64))) - .saturating_add(T::DbWeight::get().reads(1_u64.saturating_mul(s as u64))) - .saturating_add(T::DbWeight::get().writes(2)) - .saturating_add(T::DbWeight::get().writes(1_u64.saturating_mul(i as u64))) - .saturating_add(T::DbWeight::get().writes(1_u64.saturating_mul(v as u64))) - .saturating_add(T::DbWeight::get().writes(1_u64.saturating_mul(s as u64))) - } - fn update_schema_metadata_secp256k1(i: u32, v: u32, s: u32) -> Weight { - Weight::from_ref_time(492_705_000) // Standard Error: 230_000 - .saturating_add(Weight::from_ref_time(8_280_000).saturating_mul(v as u64)) // Standard Error: 1_206_000 - .saturating_add(Weight::from_ref_time(298_766_000).saturating_mul(s as u64)) + .saturating_add(T::DbWeight::get().reads((1 as u64).saturating_mul(i as u64))) + .saturating_add(T::DbWeight::get().reads((1 as u64).saturating_mul(v as u64))) + .saturating_add(T::DbWeight::get().reads((1 as u64).saturating_mul(s as u64))) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(i as u64))) + .saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(v as u64))) + .saturating_add(T::DbWeight::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(688_581_000) // Standard Error: 323_000 + .saturating_add(Weight::from_ref_time(5_203_000).saturating_mul(v as u64)) // Standard Error: 1_693_000 + .saturating_add(Weight::from_ref_time(337_131_000).saturating_mul(s as u64)) .saturating_add(T::DbWeight::get().reads(3)) - .saturating_add(T::DbWeight::get().reads(1_u64.saturating_mul(i as u64))) - .saturating_add(T::DbWeight::get().reads(1_u64.saturating_mul(v as u64))) - .saturating_add(T::DbWeight::get().reads(1_u64.saturating_mul(s as u64))) - .saturating_add(T::DbWeight::get().writes(2)) - .saturating_add(T::DbWeight::get().writes(1_u64.saturating_mul(i as u64))) - .saturating_add(T::DbWeight::get().writes(1_u64.saturating_mul(v as u64))) - .saturating_add(T::DbWeight::get().writes(1_u64.saturating_mul(s as u64))) + .saturating_add(T::DbWeight::get().reads((1 as u64).saturating_mul(i as u64))) + .saturating_add(T::DbWeight::get().reads((1 as u64).saturating_mul(v as u64))) + .saturating_add(T::DbWeight::get().reads((1 as u64).saturating_mul(s as u64))) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(i as u64))) + .saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(v as u64))) + .saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(s as u64))) } fn update_delegated_issuers_sr25519(i: u32) -> Weight { - Weight::from_ref_time(69_735_000) // Standard Error: 20_000 - .saturating_add(Weight::from_ref_time(82_000).saturating_mul(i as u64)) - .saturating_add(T::DbWeight::get().reads(5)) - .saturating_add(T::DbWeight::get().writes(3)) + Weight::from_ref_time(65_067_000) // Standard Error: 15_000 + .saturating_add(Weight::from_ref_time(43_000).saturating_mul(i as u64)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(2)) } fn update_delegated_issuers_ed25519(i: u32) -> Weight { - Weight::from_ref_time(67_411_000) // Standard Error: 25_000 - .saturating_add(Weight::from_ref_time(285_000).saturating_mul(i as u64)) - .saturating_add(T::DbWeight::get().reads(5)) - .saturating_add(T::DbWeight::get().writes(3)) + Weight::from_ref_time(63_198_000) // Standard Error: 14_000 + .saturating_add(Weight::from_ref_time(174_000).saturating_mul(i as u64)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(2)) } fn update_delegated_issuers_secp256k1(i: u32) -> Weight { - Weight::from_ref_time(156_238_000) // Standard Error: 27_000 - .saturating_add(Weight::from_ref_time(440_000).saturating_mul(i as u64)) - .saturating_add(T::DbWeight::get().reads(5)) - .saturating_add(T::DbWeight::get().writes(3)) + Weight::from_ref_time(154_618_000) // Standard Error: 41_000 + .saturating_add(Weight::from_ref_time(310_000).saturating_mul(i as u64)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(2)) } fn suspend_issuers_sr25519(i: u32) -> Weight { - Weight::from_ref_time(68_092_000) // Standard Error: 18_000 - .saturating_add(Weight::from_ref_time(6_287_000).saturating_mul(i as u64)) + Weight::from_ref_time(65_636_000) // Standard Error: 9_000 + .saturating_add(Weight::from_ref_time(5_865_000).saturating_mul(i as u64)) .saturating_add(T::DbWeight::get().reads(3)) - .saturating_add(T::DbWeight::get().reads(2_u64.saturating_mul(i as u64))) - .saturating_add(T::DbWeight::get().writes(2)) - .saturating_add(T::DbWeight::get().writes(1_u64.saturating_mul(i as u64))) + .saturating_add(T::DbWeight::get().reads((2 as u64).saturating_mul(i as u64))) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(i as u64))) } fn suspend_issuers_ed25519(i: u32) -> Weight { - Weight::from_ref_time(68_414_000) // Standard Error: 12_000 - .saturating_add(Weight::from_ref_time(6_145_000).saturating_mul(i as u64)) + Weight::from_ref_time(65_358_000) // Standard Error: 17_000 + .saturating_add(Weight::from_ref_time(5_964_000).saturating_mul(i as u64)) .saturating_add(T::DbWeight::get().reads(3)) - .saturating_add(T::DbWeight::get().reads(2_u64.saturating_mul(i as u64))) - .saturating_add(T::DbWeight::get().writes(2)) - .saturating_add(T::DbWeight::get().writes(1_u64.saturating_mul(i as u64))) + .saturating_add(T::DbWeight::get().reads((2 as u64).saturating_mul(i as u64))) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(i as u64))) } fn suspend_issuers_secp256k1(i: u32) -> Weight { - Weight::from_ref_time(154_606_000) // Standard Error: 15_000 - .saturating_add(Weight::from_ref_time(6_280_000).saturating_mul(i as u64)) + Weight::from_ref_time(158_218_000) // Standard Error: 21_000 + .saturating_add(Weight::from_ref_time(5_945_000).saturating_mul(i as u64)) .saturating_add(T::DbWeight::get().reads(3)) - .saturating_add(T::DbWeight::get().reads(2_u64.saturating_mul(i as u64))) - .saturating_add(T::DbWeight::get().writes(2)) - .saturating_add(T::DbWeight::get().writes(1_u64.saturating_mul(i as u64))) + .saturating_add(T::DbWeight::get().reads((2 as u64).saturating_mul(i as u64))) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(i as u64))) } fn unsuspend_issuers_sr25519(i: u32) -> Weight { - Weight::from_ref_time(66_790_000) // Standard Error: 16_000 - .saturating_add(Weight::from_ref_time(6_381_000).saturating_mul(i as u64)) + Weight::from_ref_time(73_542_000) // Standard Error: 24_000 + .saturating_add(Weight::from_ref_time(7_295_000).saturating_mul(i as u64)) .saturating_add(T::DbWeight::get().reads(3)) - .saturating_add(T::DbWeight::get().reads(2_u64.saturating_mul(i as u64))) - .saturating_add(T::DbWeight::get().writes(2)) - .saturating_add(T::DbWeight::get().writes(1_u64.saturating_mul(i as u64))) + .saturating_add(T::DbWeight::get().reads((2 as u64).saturating_mul(i as u64))) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(i as u64))) } fn unsuspend_issuers_ed25519(i: u32) -> Weight { - Weight::from_ref_time(65_885_000) // Standard Error: 21_000 - .saturating_add(Weight::from_ref_time(6_341_000).saturating_mul(i as u64)) + Weight::from_ref_time(68_090_000) // Standard Error: 16_000 + .saturating_add(Weight::from_ref_time(7_295_000).saturating_mul(i as u64)) .saturating_add(T::DbWeight::get().reads(3)) - .saturating_add(T::DbWeight::get().reads(2_u64.saturating_mul(i as u64))) - .saturating_add(T::DbWeight::get().writes(2)) - .saturating_add(T::DbWeight::get().writes(1_u64.saturating_mul(i as u64))) + .saturating_add(T::DbWeight::get().reads((2 as u64).saturating_mul(i as u64))) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(i as u64))) } fn unsuspend_issuers_secp256k1(i: u32) -> Weight { - Weight::from_ref_time(158_605_000) // Standard Error: 16_000 - .saturating_add(Weight::from_ref_time(6_207_000).saturating_mul(i as u64)) + Weight::from_ref_time(155_935_000) // Standard Error: 19_000 + .saturating_add(Weight::from_ref_time(7_347_000).saturating_mul(i as u64)) .saturating_add(T::DbWeight::get().reads(3)) - .saturating_add(T::DbWeight::get().reads(2_u64.saturating_mul(i as u64))) - .saturating_add(T::DbWeight::get().writes(2)) - .saturating_add(T::DbWeight::get().writes(1_u64.saturating_mul(i as u64))) + .saturating_add(T::DbWeight::get().reads((2 as u64).saturating_mul(i as u64))) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(i as u64))) } } // For backwards compatibility and tests impl WeightInfo for () { - fn init_or_update_trust_registry_sr25519(n: u32) -> Weight { - Weight::from_ref_time(67_521_000) // Standard Error: 9_000 - .saturating_add(Weight::from_ref_time(29_000).saturating_mul(n as u64)) + fn init_or_update_trust_registry_sr25519(n: u32, g: u32) -> Weight { + Weight::from_ref_time(64_792_000) // Standard Error: 5_000 + .saturating_add(Weight::from_ref_time(18_000).saturating_mul(n as u64)) // Standard Error: 1_000 + .saturating_add(Weight::from_ref_time(4_000).saturating_mul(g as u64)) .saturating_add(RocksDbWeight::get().reads(5)) .saturating_add(RocksDbWeight::get().writes(4)) } - fn init_or_update_trust_registry_ed25519(_n: u32) -> Weight { - Weight::from_ref_time(67_974_000) + fn init_or_update_trust_registry_ed25519(_n: u32, g: u32) -> Weight { + Weight::from_ref_time(63_615_000) // Standard Error: 1_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) -> Weight { - Weight::from_ref_time(160_766_000) + fn init_or_update_trust_registry_secp256k1(_n: u32, _g: u32) -> Weight { + Weight::from_ref_time(157_554_000) .saturating_add(RocksDbWeight::get().reads(5)) .saturating_add(RocksDbWeight::get().writes(4)) } - fn add_schema_metadata_sr25519(i: u32, v: u32, s: u32) -> Weight { - Weight::from_ref_time(0) // Standard Error: 120_000 - .saturating_add(Weight::from_ref_time(54_765_000).saturating_mul(i as u64)) // Standard Error: 120_000 - .saturating_add(Weight::from_ref_time(4_719_000).saturating_mul(v as u64)) // Standard Error: 631_000 - .saturating_add(Weight::from_ref_time(288_634_000).saturating_mul(s as u64)) + fn set_schemas_metadata_sr25519(i: u32, v: u32, s: u32) -> Weight { + Weight::from_ref_time(161_621_000) // Standard Error: 135_000 + .saturating_add(Weight::from_ref_time(6_973_000).saturating_mul(v as u64)) // Standard Error: 707_000 + .saturating_add(Weight::from_ref_time(345_665_000).saturating_mul(s as u64)) .saturating_add(RocksDbWeight::get().reads(3)) - .saturating_add(RocksDbWeight::get().reads(1_u64.saturating_mul(i as u64))) - .saturating_add(RocksDbWeight::get().reads(1_u64.saturating_mul(v as u64))) - .saturating_add(RocksDbWeight::get().reads(1_u64.saturating_mul(s as u64))) - .saturating_add(RocksDbWeight::get().writes(2)) - .saturating_add(RocksDbWeight::get().writes(1_u64.saturating_mul(i as u64))) - .saturating_add(RocksDbWeight::get().writes(1_u64.saturating_mul(v as u64))) - .saturating_add(RocksDbWeight::get().writes(2_u64.saturating_mul(s as u64))) - } - fn add_schema_metadata_ed25519(i: u32, v: u32, s: u32) -> Weight { - Weight::from_ref_time(0) // Standard Error: 148_000 - .saturating_add(Weight::from_ref_time(47_419_000).saturating_mul(i as u64)) // Standard Error: 148_000 - .saturating_add(Weight::from_ref_time(345_000).saturating_mul(v as u64)) // Standard Error: 780_000 - .saturating_add(Weight::from_ref_time(242_555_000).saturating_mul(s as u64)) + .saturating_add(RocksDbWeight::get().reads((1 as u64).saturating_mul(i as u64))) + .saturating_add(RocksDbWeight::get().reads((1 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(1)) + .saturating_add(RocksDbWeight::get().writes((1 as u64).saturating_mul(i as u64))) + .saturating_add(RocksDbWeight::get().writes((1 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(666_257_000) // Standard Error: 206_000 + .saturating_add(Weight::from_ref_time(2_161_000).saturating_mul(v as u64)) // Standard Error: 1_080_000 + .saturating_add(Weight::from_ref_time(324_988_000).saturating_mul(s as u64)) .saturating_add(RocksDbWeight::get().reads(3)) - .saturating_add(RocksDbWeight::get().reads(1_u64.saturating_mul(i as u64))) - .saturating_add(RocksDbWeight::get().reads(1_u64.saturating_mul(v as u64))) - .saturating_add(RocksDbWeight::get().reads(1_u64.saturating_mul(s as u64))) - .saturating_add(RocksDbWeight::get().writes(2)) - .saturating_add(RocksDbWeight::get().writes(1_u64.saturating_mul(i as u64))) - .saturating_add(RocksDbWeight::get().writes(1_u64.saturating_mul(v as u64))) - .saturating_add(RocksDbWeight::get().writes(2_u64.saturating_mul(s as u64))) - } - fn add_schema_metadata_secp256k1(i: u32, v: u32, s: u32) -> Weight { - Weight::from_ref_time(0) // Standard Error: 85_000 - .saturating_add(Weight::from_ref_time(53_089_000).saturating_mul(i as u64)) // Standard Error: 85_000 - .saturating_add(Weight::from_ref_time(5_454_000).saturating_mul(v as u64)) // Standard Error: 446_000 - .saturating_add(Weight::from_ref_time(274_233_000).saturating_mul(s as u64)) - .saturating_add(RocksDbWeight::get().reads(3)) - .saturating_add(RocksDbWeight::get().reads(1_u64.saturating_mul(i as u64))) - .saturating_add(RocksDbWeight::get().reads(1_u64.saturating_mul(v as u64))) - .saturating_add(RocksDbWeight::get().reads(1_u64.saturating_mul(s as u64))) - .saturating_add(RocksDbWeight::get().writes(2)) - .saturating_add(RocksDbWeight::get().writes(1_u64.saturating_mul(i as u64))) - .saturating_add(RocksDbWeight::get().writes(1_u64.saturating_mul(v as u64))) - .saturating_add(RocksDbWeight::get().writes(2_u64.saturating_mul(s as u64))) - } - fn update_schema_metadata_sr25519(i: u32, v: u32, s: u32) -> Weight { - Weight::from_ref_time(487_656_000) // Standard Error: 98_000 - .saturating_add(Weight::from_ref_time(5_448_000).saturating_mul(v as u64)) // Standard Error: 513_000 - .saturating_add(Weight::from_ref_time(301_780_000).saturating_mul(s as u64)) - .saturating_add(RocksDbWeight::get().reads(3)) - .saturating_add(RocksDbWeight::get().reads(1_u64.saturating_mul(i as u64))) - .saturating_add(RocksDbWeight::get().reads(1_u64.saturating_mul(v as u64))) - .saturating_add(RocksDbWeight::get().reads(1_u64.saturating_mul(s as u64))) - .saturating_add(RocksDbWeight::get().writes(2)) - .saturating_add(RocksDbWeight::get().writes(1_u64.saturating_mul(i as u64))) - .saturating_add(RocksDbWeight::get().writes(1_u64.saturating_mul(v as u64))) - .saturating_add(RocksDbWeight::get().writes(1_u64.saturating_mul(s as u64))) - } - fn update_schema_metadata_ed25519(i: u32, v: u32, s: u32) -> Weight { - Weight::from_ref_time(754_704_000) // Standard Error: 196_000 - .saturating_add(Weight::from_ref_time(4_864_000).saturating_mul(v as u64)) // Standard Error: 1_027_000 - .saturating_add(Weight::from_ref_time(286_870_000).saturating_mul(s as u64)) - .saturating_add(RocksDbWeight::get().reads(3)) - .saturating_add(RocksDbWeight::get().reads(1_u64.saturating_mul(i as u64))) - .saturating_add(RocksDbWeight::get().reads(1_u64.saturating_mul(v as u64))) - .saturating_add(RocksDbWeight::get().reads(1_u64.saturating_mul(s as u64))) - .saturating_add(RocksDbWeight::get().writes(2)) - .saturating_add(RocksDbWeight::get().writes(1_u64.saturating_mul(i as u64))) - .saturating_add(RocksDbWeight::get().writes(1_u64.saturating_mul(v as u64))) - .saturating_add(RocksDbWeight::get().writes(1_u64.saturating_mul(s as u64))) - } - fn update_schema_metadata_secp256k1(i: u32, v: u32, s: u32) -> Weight { - Weight::from_ref_time(492_705_000) // Standard Error: 230_000 - .saturating_add(Weight::from_ref_time(8_280_000).saturating_mul(v as u64)) // Standard Error: 1_206_000 - .saturating_add(Weight::from_ref_time(298_766_000).saturating_mul(s as u64)) + .saturating_add(RocksDbWeight::get().reads((1 as u64).saturating_mul(i as u64))) + .saturating_add(RocksDbWeight::get().reads((1 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(1)) + .saturating_add(RocksDbWeight::get().writes((1 as u64).saturating_mul(i as u64))) + .saturating_add(RocksDbWeight::get().writes((1 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(688_581_000) // Standard Error: 323_000 + .saturating_add(Weight::from_ref_time(5_203_000).saturating_mul(v as u64)) // Standard Error: 1_693_000 + .saturating_add(Weight::from_ref_time(337_131_000).saturating_mul(s as u64)) .saturating_add(RocksDbWeight::get().reads(3)) - .saturating_add(RocksDbWeight::get().reads(1_u64.saturating_mul(i as u64))) - .saturating_add(RocksDbWeight::get().reads(1_u64.saturating_mul(v as u64))) - .saturating_add(RocksDbWeight::get().reads(1_u64.saturating_mul(s as u64))) - .saturating_add(RocksDbWeight::get().writes(2)) - .saturating_add(RocksDbWeight::get().writes(1_u64.saturating_mul(i as u64))) - .saturating_add(RocksDbWeight::get().writes(1_u64.saturating_mul(v as u64))) - .saturating_add(RocksDbWeight::get().writes(1_u64.saturating_mul(s as u64))) + .saturating_add(RocksDbWeight::get().reads((1 as u64).saturating_mul(i as u64))) + .saturating_add(RocksDbWeight::get().reads((1 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(1)) + .saturating_add(RocksDbWeight::get().writes((1 as u64).saturating_mul(i as u64))) + .saturating_add(RocksDbWeight::get().writes((1 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(69_735_000) // Standard Error: 20_000 - .saturating_add(Weight::from_ref_time(82_000).saturating_mul(i as u64)) - .saturating_add(RocksDbWeight::get().reads(5)) - .saturating_add(RocksDbWeight::get().writes(3)) + Weight::from_ref_time(65_067_000) // Standard Error: 15_000 + .saturating_add(Weight::from_ref_time(43_000).saturating_mul(i as u64)) + .saturating_add(RocksDbWeight::get().reads(4)) + .saturating_add(RocksDbWeight::get().writes(2)) } fn update_delegated_issuers_ed25519(i: u32) -> Weight { - Weight::from_ref_time(67_411_000) // Standard Error: 25_000 - .saturating_add(Weight::from_ref_time(285_000).saturating_mul(i as u64)) - .saturating_add(RocksDbWeight::get().reads(5)) - .saturating_add(RocksDbWeight::get().writes(3)) + Weight::from_ref_time(63_198_000) // Standard Error: 14_000 + .saturating_add(Weight::from_ref_time(174_000).saturating_mul(i as u64)) + .saturating_add(RocksDbWeight::get().reads(4)) + .saturating_add(RocksDbWeight::get().writes(2)) } fn update_delegated_issuers_secp256k1(i: u32) -> Weight { - Weight::from_ref_time(156_238_000) // Standard Error: 27_000 - .saturating_add(Weight::from_ref_time(440_000).saturating_mul(i as u64)) - .saturating_add(RocksDbWeight::get().reads(5)) - .saturating_add(RocksDbWeight::get().writes(3)) + Weight::from_ref_time(154_618_000) // Standard Error: 41_000 + .saturating_add(Weight::from_ref_time(310_000).saturating_mul(i as u64)) + .saturating_add(RocksDbWeight::get().reads(4)) + .saturating_add(RocksDbWeight::get().writes(2)) } fn suspend_issuers_sr25519(i: u32) -> Weight { - Weight::from_ref_time(68_092_000) // Standard Error: 18_000 - .saturating_add(Weight::from_ref_time(6_287_000).saturating_mul(i as u64)) + Weight::from_ref_time(65_636_000) // Standard Error: 9_000 + .saturating_add(Weight::from_ref_time(5_865_000).saturating_mul(i as u64)) .saturating_add(RocksDbWeight::get().reads(3)) - .saturating_add(RocksDbWeight::get().reads(2_u64.saturating_mul(i as u64))) - .saturating_add(RocksDbWeight::get().writes(2)) - .saturating_add(RocksDbWeight::get().writes(1_u64.saturating_mul(i as u64))) + .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(68_414_000) // Standard Error: 12_000 - .saturating_add(Weight::from_ref_time(6_145_000).saturating_mul(i as u64)) + Weight::from_ref_time(65_358_000) // Standard Error: 17_000 + .saturating_add(Weight::from_ref_time(5_964_000).saturating_mul(i as u64)) .saturating_add(RocksDbWeight::get().reads(3)) - .saturating_add(RocksDbWeight::get().reads(2_u64.saturating_mul(i as u64))) - .saturating_add(RocksDbWeight::get().writes(2)) - .saturating_add(RocksDbWeight::get().writes(1_u64.saturating_mul(i as u64))) + .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(154_606_000) // Standard Error: 15_000 - .saturating_add(Weight::from_ref_time(6_280_000).saturating_mul(i as u64)) + Weight::from_ref_time(158_218_000) // Standard Error: 21_000 + .saturating_add(Weight::from_ref_time(5_945_000).saturating_mul(i as u64)) .saturating_add(RocksDbWeight::get().reads(3)) - .saturating_add(RocksDbWeight::get().reads(2_u64.saturating_mul(i as u64))) - .saturating_add(RocksDbWeight::get().writes(2)) - .saturating_add(RocksDbWeight::get().writes(1_u64.saturating_mul(i as u64))) + .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(66_790_000) // Standard Error: 16_000 - .saturating_add(Weight::from_ref_time(6_381_000).saturating_mul(i as u64)) + Weight::from_ref_time(73_542_000) // Standard Error: 24_000 + .saturating_add(Weight::from_ref_time(7_295_000).saturating_mul(i as u64)) .saturating_add(RocksDbWeight::get().reads(3)) - .saturating_add(RocksDbWeight::get().reads(2_u64.saturating_mul(i as u64))) - .saturating_add(RocksDbWeight::get().writes(2)) - .saturating_add(RocksDbWeight::get().writes(1_u64.saturating_mul(i as u64))) + .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(65_885_000) // Standard Error: 21_000 - .saturating_add(Weight::from_ref_time(6_341_000).saturating_mul(i as u64)) + Weight::from_ref_time(68_090_000) // Standard Error: 16_000 + .saturating_add(Weight::from_ref_time(7_295_000).saturating_mul(i as u64)) .saturating_add(RocksDbWeight::get().reads(3)) - .saturating_add(RocksDbWeight::get().reads(2_u64.saturating_mul(i as u64))) - .saturating_add(RocksDbWeight::get().writes(2)) - .saturating_add(RocksDbWeight::get().writes(1_u64.saturating_mul(i as u64))) + .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(158_605_000) // Standard Error: 16_000 - .saturating_add(Weight::from_ref_time(6_207_000).saturating_mul(i as u64)) + Weight::from_ref_time(155_935_000) // Standard Error: 19_000 + .saturating_add(Weight::from_ref_time(7_347_000).saturating_mul(i as u64)) .saturating_add(RocksDbWeight::get().reads(3)) - .saturating_add(RocksDbWeight::get().reads(2_u64.saturating_mul(i as u64))) - .saturating_add(RocksDbWeight::get().writes(2)) - .saturating_add(RocksDbWeight::get().writes(1_u64.saturating_mul(i as u64))) + .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))) } } diff --git a/pallets/core/src/util/action.rs b/pallets/core/src/util/action.rs index 0686e290b..e5f7e5c3a 100644 --- a/pallets/core/src/util/action.rs +++ b/pallets/core/src/util/action.rs @@ -217,14 +217,19 @@ where } } -/// Allows mutating a value associated with `Self`. +/// Allows to view and mutate a value associated with `Self`. pub trait StorageRef: Sized { + /// Some value type associated with `Self`. type Value; + /// Attempts to mutate a value associated with `Self`. + /// If the value under the option is taken, the associated value will be removed. + /// All updates will be applied only in case of a successful result. fn try_mutate_associated(self, f: F) -> Result where F: FnOnce(&mut Option) -> Result; + /// Calls provided function with an associated value as an argument. fn view_associated(self, f: F) -> R where F: FnOnce(Option) -> R; diff --git a/pallets/core/src/util/batch_update.rs b/pallets/core/src/util/batch_update.rs index b4a7e6121..3f65d7084 100644 --- a/pallets/core/src/util/batch_update.rs +++ b/pallets/core/src/util/batch_update.rs @@ -1,5 +1,5 @@ use super::BoundedKeyValue; -use alloc::collections::{BTreeMap, BTreeSet}; +use alloc::collections::{btree_map, BTreeMap, BTreeSet}; use codec::{Decode, Encode, MaxEncodedLen}; use core::ops::{Deref, DerefMut}; use frame_support::*; @@ -56,12 +56,8 @@ where /// Applies an update to the entity. pub trait ApplyUpdate { - type Output<'output> - where - Entity: 'output; - /// Applies update contained in `self` to the supplied entity. - fn apply_update(self, entity: &mut Entity) -> Self::Output<'_>; + fn apply_update(self, entity: &mut Entity); /// Returns the underlying update's kind. fn kind(&self, entity: &Entity) -> UpdateKind; @@ -128,16 +124,26 @@ where ::Key, MultiTargetUpdate>, >, - ) { + ) -> Result<(), DuplicateKey> { for (key, update) in self.keys_diff(entity).0 { map.entry(key) .or_default() - .insert(inner_key.clone(), update); + .insert_update(inner_key.clone(), update)?; } + + Ok(()) } } -/// Map representing keyed updates applied over dictionary over given keys. +pub struct DuplicateKey; + +impl From for DispatchError { + fn from(DuplicateKey: DuplicateKey) -> Self { + Self::Other("Duplicate key") + } +} + +/// Map representing keyed updates applied over given keys. #[derive(Encode, Decode, Clone, PartialEq, Eq, Debug, DefaultNoBound)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(scale_info_derive::TypeInfo)] @@ -153,8 +159,76 @@ where } } +impl MultiTargetUpdate { + pub fn insert_update(&mut self, key: K, value: U) -> Result<(), DuplicateKey> { + match self.entry(key) { + btree_map::Entry::Occupied(_) => { + Err(DuplicateKey)?; + } + btree_map::Entry::Vacant(vacant) => { + vacant.insert(value); + } + } + + Ok(()) + } + + pub fn insert_update_or_remove_duplicate( + &mut self, + key: K, + value: U, + ) -> Result<(), DuplicateKey> { + match self.entry(key) { + btree_map::Entry::Occupied(entry) => { + entry.remove(); + } + btree_map::Entry::Vacant(vacant) => { + vacant.insert(value); + } + } + + Ok(()) + } + + pub fn bind_modifier( + mut f: impl FnMut(&mut Self, K, U) -> Result<(), DuplicateKey>, + key: K, + value: U, + ) -> impl FnMut(&mut Self) -> Result<(), DuplicateKey> + where + K: Clone, + U: Clone, + { + move |map| f(map, key.clone(), value.clone()) + } +} + +impl IntoIterator for MultiTargetUpdate +where + K: Ord, +{ + type Item = (K, U); + type IntoIter = btree_map::IntoIter; + + fn into_iter(self) -> Self::IntoIter { + self.0.into_iter() + } +} + 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)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(scale_info_derive::TypeInfo)] +#[scale_info(omit_prefix)] +pub enum SetOrAddOrRemoveOrModify { + Set(V), + Add(V), + Remove, + Modify(U), +} + /// 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))] @@ -184,8 +258,6 @@ pub enum SetOrModify { pub struct OnlyExistent(pub U); impl ApplyUpdate for () { - type Output<'output> = () where V: 'output; - fn apply_update(self, _: &mut V) {} fn kind(&self, _: &V) -> UpdateKind { @@ -203,9 +275,7 @@ impl ApplyUpdate> for OnlyExistent where U: ApplyUpdate, { - type Output<'output> = U::Output<'output> where Option: 'output; - - fn apply_update(self, entity: &mut Option) -> Self::Output<'_> { + fn apply_update(self, entity: &mut Option) { self.0 .apply_update(entity.as_mut().expect("`OnlyExistent` update failed")) } @@ -225,20 +295,21 @@ impl, V, U: ValidateUpdate> ValidateUpdate> f } } -impl>> ApplyUpdate> for AddOrRemoveOrModify { - type Output<'output> = () where Option: 'output; - +impl>> ApplyUpdate> for SetOrAddOrRemoveOrModify { fn apply_update(self, entity: &mut Option) { match self { - AddOrRemoveOrModify::Add(value) => { + Self::Set(value) => { + entity.replace(value); + } + Self::Add(value) => { if entity.replace(value).is_some() { panic!("Entity already exists"); } } - AddOrRemoveOrModify::Remove => { + Self::Remove => { entity.take().expect("Can't remove non-existing entity"); } - AddOrRemoveOrModify::Modify(update) => { + Self::Modify(update) => { update.apply_update(entity); } } @@ -246,100 +317,127 @@ impl>> ApplyUpdate> for AddOrRemoveOrModif fn kind(&self, entity: &Option) -> UpdateKind { match self { - AddOrRemoveOrModify::Add(_) => { + Self::Set(_) => { if entity.is_none() { UpdateKind::Add } else { UpdateKind::Replace } } - AddOrRemoveOrModify::Remove => { + Self::Add(_) => { + if entity.is_none() { + UpdateKind::Add + } else { + UpdateKind::None + } + } + Self::Remove => { if entity.is_some() { UpdateKind::Remove } else { UpdateKind::None } } - AddOrRemoveOrModify::Modify(update) => update.kind(entity), + Self::Modify(update) => update.kind(entity), } } } impl, V, U: ValidateUpdate>> ValidateUpdate> - for AddOrRemoveOrModify + for SetOrAddOrRemoveOrModify { fn ensure_valid(&self, actor: &A, entity: &Option) -> Result<(), UpdateError> { match self { - AddOrRemoveOrModify::Add(value) => { - ensure!(entity.is_none(), UpdateError::AlreadyExists); + Self::Set(new) => { + let cond = match entity { + Some(current) => actor.can_replace(new, current), + None => actor.can_add(new), + }; + + ensure!(cond, UpdateError::InvalidActor); + } + Self::Add(value) => { ensure!(actor.can_add(value), UpdateError::InvalidActor); + ensure!(entity.is_none(), UpdateError::AlreadyExists); } - AddOrRemoveOrModify::Remove => { + Self::Remove => { let existing = entity.as_ref().ok_or(UpdateError::DoesntExist)?; ensure!(actor.can_remove(existing), UpdateError::InvalidActor); } - AddOrRemoveOrModify::Modify(update) => return update.ensure_valid(actor, entity), + Self::Modify(update) => return update.ensure_valid(actor, entity), }; Ok(()) } } -impl>> ApplyUpdate> for SetOrModify { - type Output<'output> = Option> where Option: 'output; - - fn apply_update(self, entity: &mut Option) -> Self::Output<'_> { +impl, V, U: ValidateUpdate>> ValidateUpdate> + for AddOrRemoveOrModify +{ + fn ensure_valid(&self, actor: &A, entity: &Option) -> Result<(), UpdateError> { match self { - SetOrModify::Set(value) => { - entity.replace(value); - None + Self::Add(value) => { + ensure!(actor.can_add(value), UpdateError::InvalidActor); + ensure!(entity.is_none(), UpdateError::AlreadyExists); } - SetOrModify::Modify(update) => Some(update.apply_update(entity)), + Self::Remove => { + let existing = entity.as_ref().ok_or(UpdateError::DoesntExist)?; + + ensure!(actor.can_remove(existing), UpdateError::InvalidActor); + } + Self::Modify(update) => return update.ensure_valid(actor, entity), } + + Ok(()) } +} - fn kind(&self, entity: &Option) -> UpdateKind { +impl>> ApplyUpdate> for AddOrRemoveOrModify { + fn apply_update(self, entity: &mut Option) { match self { - SetOrModify::Set(_) => match entity { - Some(_) => UpdateKind::Replace, - None => UpdateKind::Add, - }, - SetOrModify::Modify(update) => update.kind(entity), + Self::Add(value) => { + if entity.replace(value).is_some() { + panic!("Entity already exists"); + } + } + Self::Remove => { + entity.take().expect("Can't remove non-existing entity"); + } + Self::Modify(update) => { + update.apply_update(entity); + } } } -} -impl, V, U: ValidateUpdate>> ValidateUpdate> - for SetOrModify -{ - fn ensure_valid(&self, actor: &A, entity: &Option) -> Result<(), UpdateError> { + fn kind(&self, entity: &Option) -> UpdateKind { match self { - SetOrModify::Set(new) => { - let cond = match entity { - Some(current) => actor.can_replace(new, current), - None => actor.can_add(new), - }; - - ensure!(cond, UpdateError::InvalidActor); - - Ok(()) + Self::Add(_) => { + if entity.is_none() { + UpdateKind::Add + } else { + UpdateKind::None + } } - SetOrModify::Modify(update) => update.ensure_valid(actor, entity), + Self::Remove => { + if entity.is_some() { + UpdateKind::Remove + } else { + UpdateKind::None + } + } + Self::Modify(update) => update.kind(entity), } } } impl> ApplyUpdate for SetOrModify { - type Output<'output> = Option> where V: 'output; - - fn apply_update(self, entity: &mut V) -> Self::Output<'_> { + fn apply_update(self, entity: &mut V) { match self { SetOrModify::Set(value) => { *entity = value; - None } - SetOrModify::Modify(update) => Some(update.apply_update(entity)), + SetOrModify::Modify(update) => update.apply_update(entity), } } @@ -391,9 +489,7 @@ where C::Target: BoundedKeyValue, U: ApplyUpdate::Value>>, { - type Output<'output> = () where C: 'output; - - fn apply_update(self, entity: &mut C) -> Self::Output<'_> { + fn apply_update(self, entity: &mut C) { #[cfg(not(feature = "std"))] use alloc::vec::Vec; @@ -549,7 +645,7 @@ mod tests { ApplyUpdate, BoundedKeyValue, CanUpdate, CanUpdateKeyed, KeyedUpdate, UpdateError, }; - use super::{AddOrRemoveOrModify, MultiTargetUpdate, ValidateUpdate}; + use super::*; #[derive(Clone, PartialEq, Eq, Debug)] struct S(BoundedBTreeMap>); @@ -581,6 +677,27 @@ mod tests { } } + struct CanAdd; + impl CanUpdate for CanAdd { + fn can_add(&self, _new: &u8) -> bool { + true + } + } + + struct CanRemove; + impl CanUpdate for CanRemove { + fn can_remove(&self, _entity: &u8) -> bool { + true + } + } + + struct CanReplace; + impl CanUpdate for CanReplace { + fn can_replace(&self, _new: &u8, _current: &u8) -> bool { + true + } + } + struct CanDoEverything; impl CanUpdateKeyed for CanDoEverything { fn can_update_keyed>( @@ -639,6 +756,8 @@ mod tests { MultiTargetUpdate::from_iter([("2".to_string(), AddOrRemoveOrModify::Add::<_, ()>(1))]); let mut cloned_entity = entity.clone(); + assert_eq!(update.kind(&cloned_entity), UpdateKind::Replace); + update.apply_update(&mut cloned_entity); entity.try_insert("2".to_string(), 1).unwrap(); @@ -678,6 +797,7 @@ mod tests { entity.take("11".to_string()).unwrap(); assert_eq!(update.ensure_valid(&CanDoEverything, &entity), Ok(())); + assert_eq!(update.kind(&entity), UpdateKind::Replace); update.apply_update(&mut entity); @@ -690,4 +810,227 @@ mod tests { assert_eq!(new_entity, entity); } + + #[test] + fn set_or_add_or_remove_or_modify() { + let mut value = Some(0); + + let set = SetOrAddOrRemoveOrModify::::Set(10); + + assert_eq!( + set.ensure_valid(&CanAdd, &value), + Err(UpdateError::InvalidActor) + ); + assert_eq!( + set.ensure_valid(&CanRemove, &value), + Err(UpdateError::InvalidActor) + ); + assert_eq!(set.ensure_valid(&CanReplace, &value), Ok(())); + assert_eq!( + set.ensure_valid(&CanReplace, &None), + Err(UpdateError::InvalidActor) + ); + assert_eq!(set.ensure_valid(&CanAdd, &None), Ok(())); + + assert_eq!(set.kind(&value), UpdateKind::Replace); + assert_eq!(set.kind(&None), UpdateKind::Add); + + set.apply_update(&mut value); + assert_eq!(value, Some(10)); + + let remove = SetOrAddOrRemoveOrModify::::Remove; + + assert_eq!( + remove.ensure_valid(&CanAdd, &value), + Err(UpdateError::InvalidActor) + ); + assert_eq!( + remove.ensure_valid(&CanReplace, &value), + Err(UpdateError::InvalidActor) + ); + assert_eq!(remove.ensure_valid(&CanRemove, &value), Ok(())); + assert_eq!( + remove.ensure_valid(&CanReplace, &None), + Err(UpdateError::DoesntExist) + ); + assert_eq!( + remove.ensure_valid(&CanRemove, &None), + Err(UpdateError::DoesntExist) + ); + + assert_eq!(remove.kind(&value), UpdateKind::Remove); + assert_eq!(remove.kind(&None), UpdateKind::None); + + remove.apply_update(&mut value); + assert_eq!(value, None); + + let add = AddOrRemoveOrModify::::Add(10); + + assert_eq!( + add.ensure_valid(&CanAdd, &Some(5)), + Err(UpdateError::AlreadyExists) + ); + assert_eq!( + add.ensure_valid(&CanReplace, &value), + Err(UpdateError::InvalidActor) + ); + assert_eq!(add.ensure_valid(&CanAdd, &value), Ok(())); + assert_eq!( + add.ensure_valid(&CanReplace, &None), + Err(UpdateError::InvalidActor) + ); + + assert_eq!(add.kind(&value), UpdateKind::Add); + assert_eq!(add.kind(&Some(1)), UpdateKind::None); + + add.apply_update(&mut value); + assert_eq!(value, Some(10)); + + let modify = + SetOrAddOrRemoveOrModify::::Modify(OnlyExistent(SetOrModify::::Set(30))); + + assert_eq!( + modify.ensure_valid(&CanAdd, &Some(5)), + Err(UpdateError::InvalidActor) + ); + assert_eq!( + modify.ensure_valid(&CanAdd, &value), + Err(UpdateError::InvalidActor) + ); + assert_eq!(modify.ensure_valid(&CanReplace, &value), Ok(())); + assert_eq!( + modify.ensure_valid(&CanRemove, &None), + Err(UpdateError::DoesntExist) + ); + + assert_eq!(modify.kind(&value), UpdateKind::Replace); + assert_eq!(modify.kind(&None), UpdateKind::None); + + modify.apply_update(&mut value); + assert_eq!(value, Some(30)); + } + + #[test] + fn add_or_remove_or_modify() { + let mut value = Some(0); + + let remove = AddOrRemoveOrModify::::Remove; + + assert_eq!( + remove.ensure_valid(&CanAdd, &value), + Err(UpdateError::InvalidActor) + ); + assert_eq!( + remove.ensure_valid(&CanReplace, &value), + Err(UpdateError::InvalidActor) + ); + assert_eq!(remove.ensure_valid(&CanRemove, &value), Ok(())); + assert_eq!( + remove.ensure_valid(&CanReplace, &None), + Err(UpdateError::DoesntExist) + ); + assert_eq!( + remove.ensure_valid(&CanRemove, &None), + Err(UpdateError::DoesntExist) + ); + + assert_eq!(remove.kind(&value), UpdateKind::Remove); + assert_eq!(remove.kind(&None), UpdateKind::None); + + remove.apply_update(&mut value); + assert_eq!(value, None); + + let add = AddOrRemoveOrModify::::Add(10); + + assert_eq!( + add.ensure_valid(&CanAdd, &Some(5)), + Err(UpdateError::AlreadyExists) + ); + assert_eq!( + add.ensure_valid(&CanReplace, &value), + Err(UpdateError::InvalidActor) + ); + assert_eq!(add.ensure_valid(&CanAdd, &value), Ok(())); + assert_eq!( + add.ensure_valid(&CanReplace, &None), + Err(UpdateError::InvalidActor) + ); + + assert_eq!(add.kind(&value), UpdateKind::Add); + assert_eq!(add.kind(&Some(1)), UpdateKind::None); + + add.apply_update(&mut value); + assert_eq!(value, Some(10)); + + let modify = + SetOrAddOrRemoveOrModify::::Modify(OnlyExistent(SetOrModify::::Set(30))); + + assert_eq!( + modify.ensure_valid(&CanAdd, &Some(5)), + Err(UpdateError::InvalidActor) + ); + assert_eq!( + modify.ensure_valid(&CanAdd, &value), + Err(UpdateError::InvalidActor) + ); + assert_eq!(modify.ensure_valid(&CanReplace, &value), Ok(())); + assert_eq!( + modify.ensure_valid(&CanRemove, &None), + Err(UpdateError::DoesntExist) + ); + + assert_eq!(modify.kind(&value), UpdateKind::Replace); + assert_eq!(modify.kind(&None), UpdateKind::None); + + modify.apply_update(&mut value); + assert_eq!(value, Some(30)); + } + + #[test] + fn set_or_modify() { + let mut value = 0; + + let set = SetOrModify::::Set(10); + + assert_eq!( + set.ensure_valid(&CanAdd, &value), + Err(UpdateError::InvalidActor) + ); + assert_eq!( + set.ensure_valid(&CanRemove, &value), + Err(UpdateError::InvalidActor) + ); + assert_eq!(set.ensure_valid(&CanReplace, &value), Ok(())); + assert_eq!(set.ensure_valid(&CanReplace, &value), Ok(())); + assert_eq!( + set.ensure_valid(&CanAdd, &value), + Err(UpdateError::InvalidActor) + ); + + assert_eq!(set.kind(&value), UpdateKind::Replace); + + set.apply_update(&mut value); + assert_eq!(value, 10); + + let modify = SetOrModify::::Modify(SetOrModify::::Set(30)); + + assert_eq!( + modify.ensure_valid(&CanAdd, &value), + Err(UpdateError::InvalidActor) + ); + assert_eq!( + modify.ensure_valid(&CanAdd, &value), + Err(UpdateError::InvalidActor) + ); + assert_eq!(modify.ensure_valid(&CanReplace, &value), Ok(())); + assert_eq!( + modify.ensure_valid(&CanRemove, &value), + Err(UpdateError::InvalidActor) + ); + + assert_eq!(modify.kind(&value), UpdateKind::Replace); + + modify.apply_update(&mut value); + assert_eq!(value, 30); + } } diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index 7080d8f83..c81e99ffe 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -203,7 +203,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("dock-pos-dev-runtime"), impl_name: create_runtime_str!("Dock"), authoring_version: 1, - spec_version: 50, + spec_version: 51, impl_version: 2, transaction_version: 2, apis: RUNTIME_API_VERSIONS,