difftreelog
refactor(pallet-refungible) disallow invalid bulk mints
in: master
`create_multiple_items_ex` was allowing invalid (that will be always rejected at runtime level) refungible mint extrinsics, by passing multiple users into `RefungibleMultipleItems` call.
5 files changed
pallets/refungible/Cargo.tomldiffbeforeafterboth--- a/pallets/refungible/Cargo.toml
+++ b/pallets/refungible/Cargo.toml
@@ -28,6 +28,7 @@
sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24" }
sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24" }
sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24" }
+derivative = { version = "2.2.0", features = ["use_core"] }
[features]
default = ["std"]
pallets/refungible/src/common.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617use core::marker::PhantomData;1819use sp_std::collections::btree_map::BTreeMap;20use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, traits::Get};21use up_data_structs::{22 CollectionId, TokenId, CreateItemExData, budget::Budget, Property, PropertyKey, PropertyValue,23 PropertyKeyPermission, CollectionPropertiesVec, CreateRefungibleExMultipleOwners,24 CreateRefungibleExSingleOwner,25};26use pallet_common::{27 CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,28 weights::WeightInfo as _,29};30use pallet_structure::Error as StructureError;31use sp_runtime::{DispatchError};32use sp_std::{vec::Vec, vec};3334use crate::{35 AccountBalance, Allowance, Balance, Config, Error, Owned, Pallet, RefungibleHandle,36 SelfWeightOf, TokenData, weights::WeightInfo, TokensMinted, TotalSupply, CreateItemData,37};3839macro_rules! max_weight_of {40 ($($method:ident ($($args:tt)*)),*) => {41 042 $(43 .max(<SelfWeightOf<T>>::$method($($args)*))44 )*45 };46}4748fn properties_weight<T: Config>(properties: &CollectionPropertiesVec) -> u64 {49 if properties.len() > 0 {50 <CommonWeights<T>>::set_token_properties(properties.len() as u32)51 } else {52 053 }54}5556pub struct CommonWeights<T: Config>(PhantomData<T>);57impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {58 fn create_item() -> Weight {59 <SelfWeightOf<T>>::create_item()60 }6162 fn create_multiple_items(data: &[up_data_structs::CreateItemData]) -> Weight {63 <SelfWeightOf<T>>::create_multiple_items(data.len() as u32).saturating_add(64 data.iter()65 .map(|data| match data {66 up_data_structs::CreateItemData::ReFungible(rft_data) => {67 properties_weight::<T>(&rft_data.properties)68 }69 _ => 0,70 })71 .fold(0, |a, b| a.saturating_add(b)),72 )73 }7475 fn create_multiple_items_ex(call: &CreateItemExData<T::CrossAccountId>) -> Weight {76 match call {77 CreateItemExData::RefungibleMultipleOwners(i) => {78 <SelfWeightOf<T>>::create_multiple_items_ex_multiple_owners(i.users.len() as u32)79 .saturating_add(properties_weight::<T>(&i.properties))80 }81 CreateItemExData::RefungibleMultipleItems(i) => {82 <SelfWeightOf<T>>::create_multiple_items_ex_multiple_items(i.len() as u32)83 .saturating_add(84 i.iter()85 .map(|d| properties_weight::<T>(&d.properties))86 .fold(0, |a, b| a.saturating_add(b)),87 )88 }89 _ => 0,90 }91 }9293 fn burn_item() -> Weight {94 max_weight_of!(burn_item_partial(), burn_item_fully())95 }9697 fn set_collection_properties(amount: u32) -> Weight {98 <pallet_common::SelfWeightOf<T>>::set_collection_properties(amount)99 }100101 fn delete_collection_properties(amount: u32) -> Weight {102 <pallet_common::SelfWeightOf<T>>::delete_collection_properties(amount)103 }104105 fn set_token_properties(amount: u32) -> Weight {106 <SelfWeightOf<T>>::set_token_properties(amount)107 }108109 fn delete_token_properties(amount: u32) -> Weight {110 <SelfWeightOf<T>>::delete_token_properties(amount)111 }112113 fn set_token_property_permissions(amount: u32) -> Weight {114 <SelfWeightOf<T>>::set_token_property_permissions(amount)115 }116117 fn transfer() -> Weight {118 max_weight_of!(119 transfer_normal(),120 transfer_creating(),121 transfer_removing(),122 transfer_creating_removing()123 )124 }125126 fn approve() -> Weight {127 <SelfWeightOf<T>>::approve()128 }129130 fn transfer_from() -> Weight {131 max_weight_of!(132 transfer_from_normal(),133 transfer_from_creating(),134 transfer_from_removing(),135 transfer_from_creating_removing()136 )137 }138139 fn burn_from() -> Weight {140 <SelfWeightOf<T>>::burn_from()141 }142143 fn burn_recursively_self_raw() -> Weight {144 // Read to get total balance145 Self::burn_item() + T::DbWeight::get().reads(1)146 }147 fn burn_recursively_breadth_raw(_amount: u32) -> Weight {148 // Refungible token can't have children149 0150 }151}152153fn map_create_data<T: Config>(154 data: up_data_structs::CreateItemData,155 to: &T::CrossAccountId,156) -> Result<CreateItemData<T::CrossAccountId>, DispatchError> {157 match data {158 up_data_structs::CreateItemData::ReFungible(data) => Ok(CreateItemData {159 users: {160 let mut out = BTreeMap::new();161 out.insert(to.clone(), data.pieces);162 out.try_into().expect("limit > 0")163 },164 properties: data.properties,165 }),166 _ => fail!(<Error<T>>::NotRefungibleDataUsedToMintFungibleCollectionToken),167 }168}169170/// Implementation of `CommonCollectionOperations` for `RefungibleHandle`. It wraps Refungible Pallete171/// methods and adds weight info.172impl<T: Config> CommonCollectionOperations<T> for RefungibleHandle<T> {173 fn create_item(174 &self,175 sender: T::CrossAccountId,176 to: T::CrossAccountId,177 data: up_data_structs::CreateItemData,178 nesting_budget: &dyn Budget,179 ) -> DispatchResultWithPostInfo {180 with_weight(181 <Pallet<T>>::create_item(182 self,183 &sender,184 map_create_data::<T>(data, &to)?,185 nesting_budget,186 ),187 <CommonWeights<T>>::create_item(),188 )189 }190191 fn create_multiple_items(192 &self,193 sender: T::CrossAccountId,194 to: T::CrossAccountId,195 data: Vec<up_data_structs::CreateItemData>,196 nesting_budget: &dyn Budget,197 ) -> DispatchResultWithPostInfo {198 let weight = <CommonWeights<T>>::create_multiple_items(&data);199 let data = data200 .into_iter()201 .map(|d| map_create_data::<T>(d, &to))202 .collect::<Result<Vec<_>, DispatchError>>()?;203204 with_weight(205 <Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),206 weight,207 )208 }209210 fn create_multiple_items_ex(211 &self,212 sender: <T>::CrossAccountId,213 data: CreateItemExData<T::CrossAccountId>,214 nesting_budget: &dyn Budget,215 ) -> DispatchResultWithPostInfo {216 let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);217 let data = match data {218 CreateItemExData::RefungibleMultipleOwners(CreateRefungibleExMultipleOwners {219 users,220 properties,221 }) => vec![CreateItemData { users, properties }],222 CreateItemExData::RefungibleMultipleItems(r) => r223 .into_inner()224 .into_iter()225 .map(226 |CreateRefungibleExSingleOwner {227 user,228 pieces,229 properties,230 }| CreateItemData {231 users: BTreeMap::from([(user, pieces)])232 .try_into()233 .expect("limit >= 1"),234 properties,235 },236 )237 .collect(),238 _ => fail!(<Error<T>>::NotRefungibleDataUsedToMintFungibleCollectionToken),239 };240241 with_weight(242 <Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),243 weight,244 )245 }246247 fn burn_item(248 &self,249 sender: T::CrossAccountId,250 token: TokenId,251 amount: u128,252 ) -> DispatchResultWithPostInfo {253 with_weight(254 <Pallet<T>>::burn(self, &sender, token, amount),255 <CommonWeights<T>>::burn_item(),256 )257 }258259 fn burn_item_recursively(260 &self,261 sender: T::CrossAccountId,262 token: TokenId,263 self_budget: &dyn Budget,264 _breadth_budget: &dyn Budget,265 ) -> DispatchResultWithPostInfo {266 ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);267 with_weight(268 <Pallet<T>>::burn(269 self,270 &sender,271 token,272 <Balance<T>>::get((self.id, token, &sender)),273 ),274 <CommonWeights<T>>::burn_recursively_self_raw(),275 )276 }277278 fn transfer(279 &self,280 from: T::CrossAccountId,281 to: T::CrossAccountId,282 token: TokenId,283 amount: u128,284 nesting_budget: &dyn Budget,285 ) -> DispatchResultWithPostInfo {286 with_weight(287 <Pallet<T>>::transfer(self, &from, &to, token, amount, nesting_budget),288 <CommonWeights<T>>::transfer(),289 )290 }291292 fn approve(293 &self,294 sender: T::CrossAccountId,295 spender: T::CrossAccountId,296 token: TokenId,297 amount: u128,298 ) -> DispatchResultWithPostInfo {299 with_weight(300 <Pallet<T>>::set_allowance(self, &sender, &spender, token, amount),301 <CommonWeights<T>>::approve(),302 )303 }304305 fn transfer_from(306 &self,307 sender: T::CrossAccountId,308 from: T::CrossAccountId,309 to: T::CrossAccountId,310 token: TokenId,311 amount: u128,312 nesting_budget: &dyn Budget,313 ) -> DispatchResultWithPostInfo {314 with_weight(315 <Pallet<T>>::transfer_from(self, &sender, &from, &to, token, amount, nesting_budget),316 <CommonWeights<T>>::transfer_from(),317 )318 }319320 fn burn_from(321 &self,322 sender: T::CrossAccountId,323 from: T::CrossAccountId,324 token: TokenId,325 amount: u128,326 nesting_budget: &dyn Budget,327 ) -> DispatchResultWithPostInfo {328 with_weight(329 <Pallet<T>>::burn_from(self, &sender, &from, token, amount, nesting_budget),330 <CommonWeights<T>>::burn_from(),331 )332 }333334 fn set_collection_properties(335 &self,336 sender: T::CrossAccountId,337 properties: Vec<Property>,338 ) -> DispatchResultWithPostInfo {339 let weight = <CommonWeights<T>>::set_collection_properties(properties.len() as u32);340341 with_weight(342 <Pallet<T>>::set_collection_properties(self, &sender, properties),343 weight,344 )345 }346347 fn delete_collection_properties(348 &self,349 sender: &T::CrossAccountId,350 property_keys: Vec<PropertyKey>,351 ) -> DispatchResultWithPostInfo {352 let weight = <CommonWeights<T>>::delete_collection_properties(property_keys.len() as u32);353354 with_weight(355 <Pallet<T>>::delete_collection_properties(self, sender, property_keys),356 weight,357 )358 }359360 fn set_token_properties(361 &self,362 sender: T::CrossAccountId,363 token_id: TokenId,364 properties: Vec<Property>,365 nesting_budget: &dyn Budget,366 ) -> DispatchResultWithPostInfo {367 let weight = <CommonWeights<T>>::set_token_properties(properties.len() as u32);368369 with_weight(370 <Pallet<T>>::set_token_properties(371 self,372 &sender,373 token_id,374 properties.into_iter(),375 false,376 nesting_budget,377 ),378 weight,379 )380 }381382 fn set_token_property_permissions(383 &self,384 sender: &T::CrossAccountId,385 property_permissions: Vec<PropertyKeyPermission>,386 ) -> DispatchResultWithPostInfo {387 let weight =388 <CommonWeights<T>>::set_token_property_permissions(property_permissions.len() as u32);389390 with_weight(391 <Pallet<T>>::set_token_property_permissions(self, sender, property_permissions),392 weight,393 )394 }395396 fn delete_token_properties(397 &self,398 sender: T::CrossAccountId,399 token_id: TokenId,400 property_keys: Vec<PropertyKey>,401 nesting_budget: &dyn Budget,402 ) -> DispatchResultWithPostInfo {403 let weight = <CommonWeights<T>>::delete_token_properties(property_keys.len() as u32);404405 with_weight(406 <Pallet<T>>::delete_token_properties(407 self,408 &sender,409 token_id,410 property_keys.into_iter(),411 nesting_budget,412 ),413 weight,414 )415 }416417 fn check_nesting(418 &self,419 _sender: <T>::CrossAccountId,420 _from: (CollectionId, TokenId),421 _under: TokenId,422 _nesting_budget: &dyn Budget,423 ) -> sp_runtime::DispatchResult {424 fail!(<Error<T>>::RefungibleDisallowsNesting)425 }426427 fn nest(&self, _under: TokenId, _to_nest: (CollectionId, TokenId)) {}428429 fn unnest(&self, _under: TokenId, _to_nest: (CollectionId, TokenId)) {}430431 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {432 <Owned<T>>::iter_prefix((self.id, account))433 .map(|(id, _)| id)434 .collect()435 }436437 fn collection_tokens(&self) -> Vec<TokenId> {438 <TotalSupply<T>>::iter_prefix((self.id,))439 .map(|(id, _)| id)440 .collect()441 }442443 fn token_exists(&self, token: TokenId) -> bool {444 <Pallet<T>>::token_exists(self, token)445 }446447 fn last_token_id(&self) -> TokenId {448 TokenId(<TokensMinted<T>>::get(self.id))449 }450451 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId> {452 <Pallet<T>>::token_owner(self.id, token)453 }454455 /// Returns 10 token in no particular order.456 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId> {457 <Pallet<T>>::token_owners(self.id, token).unwrap_or_default()458 }459460 fn token_property(&self, _token_id: TokenId, _key: &PropertyKey) -> Option<PropertyValue> {461 None462 }463464 fn token_properties(465 &self,466 _token_id: TokenId,467 _keys: Option<Vec<PropertyKey>>,468 ) -> Vec<Property> {469 Vec::new()470 }471472 fn total_supply(&self) -> u32 {473 <Pallet<T>>::total_supply(self)474 }475476 fn account_balance(&self, account: T::CrossAccountId) -> u32 {477 <AccountBalance<T>>::get((self.id, account))478 }479480 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {481 <Balance<T>>::get((self.id, token, account))482 }483484 fn allowance(485 &self,486 sender: T::CrossAccountId,487 spender: T::CrossAccountId,488 token: TokenId,489 ) -> u128 {490 <Allowance<T>>::get((self.id, token, sender, spender))491 }492493 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {494 Some(self)495 }496497 fn total_pieces(&self, token: TokenId) -> Option<u128> {498 <Pallet<T>>::total_pieces(self.id, token)499 }500}501502impl<T: Config> RefungibleExtensions<T> for RefungibleHandle<T> {503 fn repartition(504 &self,505 owner: &T::CrossAccountId,506 token: TokenId,507 amount: u128,508 ) -> DispatchResultWithPostInfo {509 with_weight(510 <Pallet<T>>::repartition(self, owner, token, amount),511 <SelfWeightOf<T>>::repartition_item(),512 )513 }514}pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -494,7 +494,7 @@
<Pallet<T>>::create_item(
self,
&caller,
- CreateItemData::<T> {
+ CreateItemData::<T::CrossAccountId> {
users,
properties: CollectionPropertiesVec::default(),
},
@@ -560,7 +560,7 @@
<Pallet<T>>::create_item(
self,
&caller,
- CreateItemData::<T> { users, properties },
+ CreateItemData::<T::CrossAccountId> { users, properties },
&budget,
)
.map_err(dispatch_to_evm::<T>)?;
@@ -717,7 +717,7 @@
.collect::<BTreeMap<_, _>>()
.try_into()
.unwrap();
- let create_item_data = CreateItemData::<T> {
+ let create_item_data = CreateItemData::<T::CrossAccountId> {
users,
properties: CollectionPropertiesVec::default(),
};
@@ -777,7 +777,7 @@
})
.map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;
- let create_item_data = CreateItemData::<T> {
+ let create_item_data = CreateItemData::<T::CrossAccountId> {
users: users.clone(),
properties,
};
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -93,7 +93,9 @@
use codec::{Encode, Decode, MaxEncodedLen};
use core::ops::Deref;
use evm_coder::ToLog;
-use frame_support::{BoundedVec, ensure, fail, storage::with_transaction, transactional};
+use frame_support::{
+ BoundedVec, ensure, fail, storage::with_transaction, transactional, pallet_prelude::ConstU32,
+};
use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
use pallet_evm_coder_substrate::WithRecorder;
use pallet_common::{
@@ -106,11 +108,13 @@
use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};
use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};
use up_data_structs::{
- AccessMode, budget::Budget, CollectionId, CreateCollectionData, CreateRefungibleExData,
- CustomDataLimit, mapping::TokenAddressMapping, MAX_REFUNGIBLE_PIECES, TokenId, Property,
+ AccessMode, budget::Budget, CollectionId, CreateCollectionData, CustomDataLimit,
+ mapping::TokenAddressMapping, MAX_REFUNGIBLE_PIECES, MAX_ITEMS_PER_BATCH, TokenId, Property,
PropertyKey, PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue,
- TrySetProperty,
+ TrySetProperty, CollectionPropertiesVec,
};
+use frame_support::BoundedBTreeMap;
+use derivative::Derivative;
pub use pallet::*;
#[cfg(feature = "runtime-benchmarks")]
@@ -120,8 +124,13 @@
pub mod erc_token;
pub mod weights;
-pub type CreateItemData<T> =
- CreateRefungibleExData<<T as pallet_evm::account::Config>::CrossAccountId>;
+#[derive(Derivative, Clone)]
+pub struct CreateItemData<CrossAccountId> {
+ #[derivative(Debug(format_with = "bounded::map_debug"))]
+ pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,
+ #[derivative(Debug(format_with = "bounded::vec_debug"))]
+ pub properties: CollectionPropertiesVec,
+}
pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;
/// Token data, stored independently from other data used to describe it
@@ -873,7 +882,7 @@
pub fn create_multiple_items(
collection: &RefungibleHandle<T>,
sender: &T::CrossAccountId,
- data: Vec<CreateItemData<T>>,
+ data: Vec<CreateItemData<T::CrossAccountId>>,
nesting_budget: &dyn Budget,
) -> DispatchResult {
if !collection.is_owner_or_admin(sender) {
@@ -1213,7 +1222,7 @@
pub fn create_item(
collection: &RefungibleHandle<T>,
sender: &T::CrossAccountId,
- data: CreateItemData<T>,
+ data: CreateItemData<T::CrossAccountId>,
nesting_budget: &dyn Budget,
) -> DispatchResult {
Self::create_multiple_items(collection, sender, vec![data], nesting_budget)
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -826,13 +826,23 @@
/// Extended data for create ReFungible item.
#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]
#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]
-pub struct CreateRefungibleExData<CrossAccountId> {
+pub struct CreateRefungibleExMultipleOwners<CrossAccountId> {
#[derivative(Debug(format_with = "bounded::map_debug"))]
pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,
#[derivative(Debug(format_with = "bounded::vec_debug"))]
pub properties: CollectionPropertiesVec,
}
+/// Extended data for create ReFungible item.
+#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]
+#[derivative(Debug(bound = "CrossAccountId: fmt::Debug"))]
+pub struct CreateRefungibleExSingleOwner<CrossAccountId> {
+ pub user: CrossAccountId,
+ pub pieces: u128,
+ #[derivative(Debug(format_with = "bounded::vec_debug"))]
+ pub properties: CollectionPropertiesVec,
+}
+
/// Unified extended data for creating item.
#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]
#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]
@@ -853,12 +863,12 @@
/// many tokens, each may have only one owner
RefungibleMultipleItems(
#[derivative(Debug(format_with = "bounded::vec_debug"))]
- BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,
+ BoundedVec<CreateRefungibleExSingleOwner<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,
),
/// Extended data for create ReFungible item in case of
/// single token, which may have many owners
- RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),
+ RefungibleMultipleOwners(CreateRefungibleExMultipleOwners<CrossAccountId>),
}
impl From<CreateNftData> for CreateItemData {