git.delta.rocks / unique-network / refs/commits / 2976d69d82a2

difftreelog

Add properties key chars check

Daniel Shiposha2022-05-11parent: #6ac8e66.patch.diff
in: master

4 files changed

modifiedpallets/common/src/lib.rsdiffbeforeafterboth
1818
19use core::ops::{Deref, DerefMut};19use core::ops::{Deref, DerefMut};
20use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};20use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
21use sp_std::{vec::Vec, collections::btree_map::BTreeMap};21use sp_std::vec::Vec;
22use pallet_evm::account::CrossAccountId;22use pallet_evm::account::CrossAccountId;
23use frame_support::{23use frame_support::{
24 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},24 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},
36 CUSTOM_DATA_LIMIT, CollectionLimits, CustomDataLimit, CreateCollectionData, SponsorshipState,36 CUSTOM_DATA_LIMIT, CollectionLimits, CustomDataLimit, CreateCollectionData, SponsorshipState,
37 CreateItemExData, SponsoringRateLimit, budget::Budget, COLLECTION_FIELD_LIMIT, CollectionField,37 CreateItemExData, SponsoringRateLimit, budget::Budget, COLLECTION_FIELD_LIMIT, CollectionField,
38 PhantomType, Property, Properties, PropertiesPermissionMap, PropertyKey, PropertyPermission,38 PhantomType, Property, Properties, PropertiesPermissionMap, PropertyKey, PropertyPermission,
39 PropertiesError, PropertyKeyPermission, TokenData, CollectionPropertiesPermissionsVec,39 PropertiesError, PropertyKeyPermission, TokenData, TrySet,
40};40};
41pub use pallet::*;41pub use pallet::*;
42use sp_core::H160;42use sp_core::H160;
375 /// Unable to read array of unbounded keys375 /// Unable to read array of unbounded keys
376 UnableToReadUnboundedKeys,376 UnableToReadUnboundedKeys,
377
378 /// Only ASCII letters, digits, and '_', '-' are allowed
379 InvalidCharacterInPropertyKey,
377 }380 }
378381
379 #[pallet::storage]382 #[pallet::storage]
676 meta_update_permission: data.meta_update_permission.unwrap_or_default(),679 meta_update_permission: data.meta_update_permission.unwrap_or_default(),
677 };680 };
678681
679 CollectionProperties::<T>::insert(682 let mut collection_properties = up_data_structs::CollectionProperties::get();
680 id,683 collection_properties.try_set_from_iter(
681 Properties::from_collection_props_vec(data.properties)684 data.properties.into_iter()
685 .map(|p| (p.key, p.value))
682 .map_err(|e| -> Error<T> { e.into() })?,686 ).map_err(|e| -> Error<T> { e.into() })?;
683 );687
688 CollectionProperties::<T>::insert(id, collection_properties);
684689
685 let token_props_permissions: PropertiesPermissionMap = data690 let mut token_props_permissions = PropertiesPermissionMap::new();
691 token_props_permissions.try_set_from_iter(
686 .token_property_permissions692 data.token_property_permissions
687 .into_iter()693 .into_iter()
688 .map(|property| (property.key, property.permission))694 .map(|property| (property.key, property.permission))
689 .collect::<BTreeMap<_, _>>()
690 .try_into()
691 .map_err(|_| -> Error<T> { PropertiesError::PropertyLimitReached.into() })?;695 ).map_err(|e| -> Error<T> { e.into() })?;
692696
693 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);697 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);
694698
771 collection.check_is_owner_or_admin(sender)?;775 collection.check_is_owner_or_admin(sender)?;
772776
773 CollectionProperties::<T>::try_mutate(collection.id, |properties| {777 CollectionProperties::<T>::try_mutate(collection.id, |properties| {
774 properties.try_set_property(property.clone())778 let property = property.clone();
779 properties.try_set(property.key, property.value)
775 })780 })
776 .map_err(|e| -> Error<T> { e.into() })?;781 .map_err(|e| -> Error<T> { e.into() })?;
777782
799 ) -> DispatchResult {804 ) -> DispatchResult {
800 collection.check_is_owner_or_admin(sender)?;805 collection.check_is_owner_or_admin(sender)?;
801806
802 CollectionProperties::<T>::mutate(collection.id, |properties| {807 CollectionProperties::<T>::try_mutate(collection.id, |properties| {
803 properties.remove_property(&property_key);808 properties.remove(&property_key)
804 });809 }).map_err(|e| -> Error<T> { e.into() })?;
805810
806 Self::deposit_event(Event::CollectionPropertyDeleted(811 Self::deposit_event(Event::CollectionPropertyDeleted(
807 collection.id,812 collection.id,
841846
842 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {847 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {
843 let property_permission = property_permission.clone();848 let property_permission = property_permission.clone();
844 permissions.try_insert(property_permission.key, property_permission.permission)849 permissions.try_set(property_permission.key, property_permission.permission)
845 })850 })
846 .map_err(|_| -> Error<T> { PropertiesError::PropertyLimitReached.into() })?;851 .map_err(|_| -> Error<T> { PropertiesError::PropertyLimitReached.into() })?;
847852
876 .collect::<Result<Vec<PropertyKey>, DispatchError>>()881 .collect::<Result<Vec<PropertyKey>, DispatchError>>()
877 }882 }
883
884 pub fn check_property_key(key: &PropertyKey) -> Result<(), DispatchError> {
885 let key_str = sp_std::str::from_utf8(key.as_slice())
886 .map_err(|_| <Error<T>>::InvalidCharacterInPropertyKey)?;
887
888 for ch in key_str.chars() {
889 if !ch.is_ascii_alphanumeric() && ch != '_' && ch != '-' {
890 return Err(<Error<T>>::InvalidCharacterInPropertyKey.into());
891 }
892 }
893
894 Ok(())
895 }
878896
879 pub fn filter_collection_properties(897 pub fn filter_collection_properties(
880 collection_id: CollectionId,898 collection_id: CollectionId,
885 let properties = keys903 let properties = keys
886 .into_iter()904 .into_iter()
887 .filter_map(|key| {905 .filter_map(|key| {
888 properties.get_property(&key).map(|value| Property {906 properties.get(&key)
907 .map(|value| Property {
889 key,908 key,
890 value: value.clone(),909 value: value.clone(),
1222 match error {1241 match error {
1223 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,1242 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,
1224 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,1243 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,
1244 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,
1225 }1245 }
1226 }1246 }
1227}1247}
modifiedpallets/nonfungible/src/common.rsdiffbeforeafterboth
391391
392 keys.into_iter()392 keys.into_iter()
393 .filter_map(|key| {393 .filter_map(|key| {
394 properties.get_property(&key).map(|value| Property {394 properties.get(&key)
395 .map(|value| Property {
395 key,396 key,
396 value: value.clone(),397 value: value.clone(),
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
21use up_data_structs::{21use up_data_structs::{
22 AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,22 AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,
23 mapping::TokenAddressMapping, NestingRule, budget::Budget, Property, PropertyPermission,23 mapping::TokenAddressMapping, NestingRule, budget::Budget, Property, PropertyPermission,
24 PropertyKey, PropertyKeyPermission, Properties,24 PropertyKey, PropertyKeyPermission, Properties, TrySet,
25};25};
26use pallet_evm::account::CrossAccountId;26use pallet_evm::account::CrossAccountId;
27use pallet_common::{27use pallet_common::{
265 Self::check_token_change_permission(collection, sender, token_id, &property.key)?;265 Self::check_token_change_permission(collection, sender, token_id, &property.key)?;
266266
267 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {267 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {
268 properties.try_set_property(property.clone())268 let property = property.clone();
269 properties.try_set(property.key, property.value)
269 })270 })
270 .map_err(|e| -> CommonError<T> { e.into() })?;271 .map_err(|e| -> CommonError<T> { e.into() })?;
271272
299 ) -> DispatchResult {300 ) -> DispatchResult {
300 Self::check_token_change_permission(collection, sender, token_id, &property_key)?;301 Self::check_token_change_permission(collection, sender, token_id, &property_key)?;
301302
302 <TokenProperties<T>>::mutate((collection.id, token_id), |properties| {303 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {
303 properties.remove_property(&property_key);304 properties.remove(&property_key)
304 });305 }).map_err(|e| -> CommonError<T> { e.into() })?;
305306
306 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(307 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(
307 collection.id,308 collection.id,
332 };333 };
333334
334 let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))335 let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))
335 .get_property(property_key)336 .get(property_key)
336 .is_some();337 .is_some();
337338
338 match permission {339 match permission {
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
689pub enum PropertiesError {689pub enum PropertiesError {
690 NoSpaceForProperty,690 NoSpaceForProperty,
691 PropertyLimitReached,691 PropertyLimitReached,
692 InvalidCharacterInPropertyKey,
692}693}
693694
694pub type PropertiesMap =695pub trait TrySet: Sized {
695 BoundedBTreeMap<PropertyKey, PropertyValue, ConstU32<MAX_PROPERTIES_PER_ITEM>>;
696pub type PropertiesPermissionMap =696 type Value;
697 BoundedBTreeMap<PropertyKey, PropertyPermission, ConstU32<MAX_PROPERTIES_PER_ITEM>>;697
698
699#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]
700pub struct Properties {
701 map: PropertiesMap,698 fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError>;
702 consumed_space: u32,
703 space_limit: u32,
704}
705
706impl Properties {
707 pub fn new(space_limit: u32) -> Self {
708 Self {
709 map: BoundedBTreeMap::new(),
710 consumed_space: 0,
711 space_limit,
712 }
713 }
714699
715 pub fn from_collection_props_vec(700 fn try_set_from_iter<I>(&mut self, iter: I) -> Result<(), PropertiesError>
716 data: CollectionPropertiesVec,701 where
717 ) -> Result<Self, PropertiesError> {
718 let mut props = Self::new(MAX_COLLECTION_PROPERTIES_SIZE);702 I: Iterator<Item=(PropertyKey, Self::Value)>
719703 {
720 for property in data.into_iter() {704 for (key, value) in iter {
721 props.try_set_property(property)?;705 self.try_set(key, value)?;
722 }706 }
723707
724 Ok(props)708 Ok(())
725 }709 }
710}
711
712#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]
713#[derivative(Default(bound = ""))]
714pub struct PropertiesMap<Value>(BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>);
715
716impl<Value> PropertiesMap<Value> {
717 pub fn new() -> Self {
718 Self(BoundedBTreeMap::new())
719 }
720
721 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {
722 Self::check_property_key(key)?;
723
724 Ok(self.0.remove(key))
725 }
726
727 pub fn get(&self, key: &PropertyKey) -> Option<&Value> {
728 self.0.get(key)
729 }
730
731 pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &Value)> {
732 self.0.iter()
733 }
734
735 fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {
736 let key_str = sp_std::str::from_utf8(key.as_slice())
737 .map_err(|_| PropertiesError::InvalidCharacterInPropertyKey)?;
738
739 for ch in key_str.chars() {
740 if !ch.is_ascii_alphanumeric() && ch != '_' && ch != '-' {
741 return Err(PropertiesError::InvalidCharacterInPropertyKey);
742 }
743 }
744
745 Ok(())
746 }
747}
748
749impl<Value> TrySet for PropertiesMap<Value> {
750 type Value = Value;
726751
727 pub fn try_set_property(&mut self, property: Property) -> Result<(), PropertiesError> {752 fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {
728 let value_len = property.value.len();
729
730 if self.consumed_space as usize + value_len > self.space_limit as usize {
731 return Err(PropertiesError::NoSpaceForProperty);753 Self::check_property_key(&key)?;
732 }
733754
734 self.map755 self.0
735 .try_insert(property.key, property.value)756 .try_insert(key, value)
736 .map_err(|_| PropertiesError::PropertyLimitReached)?;757 .map_err(|_| PropertiesError::PropertyLimitReached)?;
737
738 self.consumed_space += value_len as u32;
739758
740 Ok(())759 Ok(())
741 }760 }
761}
762
763pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;
764
765#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]
766pub struct Properties {
767 map: PropertiesMap<PropertyValue>,
768 consumed_space: u32,
769 space_limit: u32,
770}
771
772impl Properties {
773 pub fn new(space_limit: u32) -> Self {
774 Self {
775 map: PropertiesMap::new(),
776 consumed_space: 0,
777 space_limit,
778 }
779 }
742780
743 pub fn remove_property(&mut self, key: &PropertyKey) {781 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {
744 let property = self.map.get(key);782 let value = self.map.remove(key)?;
745783
746 if let Some(value) = property {784 if let Some(ref value) = value {
747 let value_len = value.len() as u32;785 let value_len = value.len() as u32;
748
749 self.map.remove(key);
750 self.consumed_space -= value_len;786 self.consumed_space -= value_len;
751 }787 }
788
789 Ok(value)
752 }790 }
753791
754 pub fn get_property(&self, key: &PropertyKey) -> Option<&PropertyValue> {792 pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {
755 self.map.get(key)793 self.map.get(key)
756 }794 }
757795
758 pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &PropertyValue)> {796 pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &PropertyValue)> {
759 self.map.iter()797 self.map.iter()
760 }798 }
761}799}
800
801impl TrySet for Properties {
802 type Value = PropertyValue;
803
804 fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {
805 let value_len = value.len();
806
807 if self.consumed_space as usize + value_len > self.space_limit as usize {
808 return Err(PropertiesError::NoSpaceForProperty);
809 }
810
811 self.map.try_set(key, value)?;
812
813 self.consumed_space += value_len as u32;
814
815 Ok(())
816 }
817}
762818
763pub struct CollectionProperties;819pub struct CollectionProperties;
764820