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
--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -391,10 +391,11 @@
 
 		keys.into_iter()
 			.filter_map(|key| {
-				properties.get_property(&key).map(|value| Property {
-					key,
-					value: value.clone(),
-				})
+				properties.get(&key)
+					.map(|value| Property {
+						key,
+						value: value.clone(),
+					})
 			})
 			.collect()
 	}
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -21,7 +21,7 @@
 use up_data_structs::{
 	AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,
 	mapping::TokenAddressMapping, NestingRule, budget::Budget, Property, PropertyPermission,
-	PropertyKey, PropertyKeyPermission, Properties,
+	PropertyKey, PropertyKeyPermission, Properties, TrySet,
 };
 use pallet_evm::account::CrossAccountId;
 use pallet_common::{
@@ -265,7 +265,8 @@
 		Self::check_token_change_permission(collection, sender, token_id, &property.key)?;
 
 		<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {
-			properties.try_set_property(property.clone())
+			let property = property.clone();
+			properties.try_set(property.key, property.value)
 		})
 		.map_err(|e| -> CommonError<T> { e.into() })?;
 
@@ -299,9 +300,9 @@
 	) -> DispatchResult {
 		Self::check_token_change_permission(collection, sender, token_id, &property_key)?;
 
-		<TokenProperties<T>>::mutate((collection.id, token_id), |properties| {
-			properties.remove_property(&property_key);
-		});
+		<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {
+			properties.remove(&property_key)
+		}).map_err(|e| -> CommonError<T> { e.into() })?;
 
 		<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(
 			collection.id,
@@ -332,7 +333,7 @@
 		};
 
 		let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))
-			.get_property(property_key)
+			.get(property_key)
 			.is_some();
 
 		match permission {
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -689,16 +689,82 @@
 pub enum PropertiesError {
 	NoSpaceForProperty,
 	PropertyLimitReached,
+	InvalidCharacterInPropertyKey,
+}
+
+pub trait TrySet: Sized {
+	type Value;
+
+	fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError>;
+
+	fn try_set_from_iter<I>(&mut self, iter: I) -> Result<(), PropertiesError>
+	where
+		I: Iterator<Item=(PropertyKey, Self::Value)>
+	{
+		for (key, value) in iter {
+			self.try_set(key, value)?;
+		}
+
+		Ok(())
+	}
+}
+
+#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]
+#[derivative(Default(bound = ""))]
+pub struct PropertiesMap<Value>(BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>);
+
+impl<Value> PropertiesMap<Value> {
+	pub fn new() -> Self {
+		Self(BoundedBTreeMap::new())
+	}
+
+	pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {
+		Self::check_property_key(key)?;
+
+		Ok(self.0.remove(key))
+	}
+
+	pub fn get(&self, key: &PropertyKey) -> Option<&Value> {
+		self.0.get(key)
+	}
+
+	pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &Value)> {
+		self.0.iter()
+	}
+
+	fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {
+		let key_str = sp_std::str::from_utf8(key.as_slice())
+			.map_err(|_| PropertiesError::InvalidCharacterInPropertyKey)?;
+
+		for ch in key_str.chars() {
+			if !ch.is_ascii_alphanumeric() && ch != '_' && ch != '-' {
+				return Err(PropertiesError::InvalidCharacterInPropertyKey);
+			}
+		}
+
+		Ok(())
+	}
+}
+
+impl<Value> TrySet for PropertiesMap<Value> {
+	type Value = Value;
+
+	fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {
+		Self::check_property_key(&key)?;
+
+		self.0
+			.try_insert(key, value)
+			.map_err(|_| PropertiesError::PropertyLimitReached)?;
+
+		Ok(())
+	}
 }
 
-pub type PropertiesMap =
-	BoundedBTreeMap<PropertyKey, PropertyValue, ConstU32<MAX_PROPERTIES_PER_ITEM>>;
-pub type PropertiesPermissionMap =
-	BoundedBTreeMap<PropertyKey, PropertyPermission, ConstU32<MAX_PROPERTIES_PER_ITEM>>;
+pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;
 
 #[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]
 pub struct Properties {
-	map: PropertiesMap,
+	map: PropertiesMap<PropertyValue>,
 	consumed_space: u32,
 	space_limit: u32,
 }
@@ -706,57 +772,47 @@
 impl Properties {
 	pub fn new(space_limit: u32) -> Self {
 		Self {
-			map: BoundedBTreeMap::new(),
+			map: PropertiesMap::new(),
 			consumed_space: 0,
 			space_limit,
 		}
 	}
 
-	pub fn from_collection_props_vec(
-		data: CollectionPropertiesVec,
-	) -> Result<Self, PropertiesError> {
-		let mut props = Self::new(MAX_COLLECTION_PROPERTIES_SIZE);
+	pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {
+		let value = self.map.remove(key)?;
 
-		for property in data.into_iter() {
-			props.try_set_property(property)?;
+		if let Some(ref value) = value {
+			let value_len = value.len() as u32;
+			self.consumed_space -= value_len;
 		}
 
-		Ok(props)
+		Ok(value)
 	}
 
-	pub fn try_set_property(&mut self, property: Property) -> Result<(), PropertiesError> {
-		let value_len = property.value.len();
+	pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {
+		self.map.get(key)
+	}
 
+	pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &PropertyValue)> {
+		self.map.iter()
+	}
+}
+
+impl TrySet for Properties {
+	type Value = PropertyValue;
+
+	fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {
+		let value_len = value.len();
+
 		if self.consumed_space as usize + value_len > self.space_limit as usize {
 			return Err(PropertiesError::NoSpaceForProperty);
 		}
 
-		self.map
-			.try_insert(property.key, property.value)
-			.map_err(|_| PropertiesError::PropertyLimitReached)?;
+		self.map.try_set(key, value)?;
 
 		self.consumed_space += value_len as u32;
 
 		Ok(())
-	}
-
-	pub fn remove_property(&mut self, key: &PropertyKey) {
-		let property = self.map.get(key);
-
-		if let Some(value) = property {
-			let value_len = value.len() as u32;
-
-			self.map.remove(key);
-			self.consumed_space -= value_len;
-		}
-	}
-
-	pub fn get_property(&self, key: &PropertyKey) -> Option<&PropertyValue> {
-		self.map.get(key)
-	}
-
-	pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &PropertyValue)> {
-		self.map.iter()
 	}
 }