difftreelog
fix disallow nesting under non-existing tokens
in: master
3 files changed
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -1332,7 +1332,10 @@
let permissive = nesting.permissive;
if permissive {
- // Pass
+ ensure!(
+ <TokenData<T>>::contains_key((handle.id, under)),
+ <CommonError<T>>::TokenNotFound
+ );
} else if nesting.token_owner
&& <PalletStructure<T>>::check_indirectly_owned(
sender.clone(),
@@ -1341,9 +1344,12 @@
Some(from),
nesting_budget,
)? {
- // Pass
+ // Pass, token existence is checked in `check_indirectly_owned`
} else if nesting.collection_admin && handle.is_owner_or_admin(&sender) {
- // Pass
+ ensure!(
+ <TokenData<T>>::contains_key((handle.id, under)),
+ <CommonError<T>>::TokenNotFound
+ );
} else {
fail!(<CommonError<T>>::UserIsNotAllowedToNest);
}
pallets/structure/Cargo.tomldiffbeforeafterboth--- a/pallets/structure/Cargo.toml
+++ b/pallets/structure/Cargo.toml
@@ -17,19 +17,10 @@
] }
up-data-structs = { path = "../../primitives/data-structs", default-features = false }
pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.36" }
+log = { version = "0.4.17", default-features = false }
[features]
default = ["std"]
-std = [
- "frame-support/std",
- "frame-system/std",
- "frame-benchmarking/std",
- "sp-std/std",
- "pallet-common/std",
- "scale-info/std",
- "parity-scale-codec/std",
- "up-data-structs/std",
- "pallet-evm/std",
-]
+std = ["frame-support/std", "frame-system/std", "frame-benchmarking/std", "sp-std/std", "pallet-common/std", "scale-info/std", "parity-scale-codec/std", "up-data-structs/std", "pallet-evm/std"]
runtime-benchmarks = ['frame-benchmarking', 'pallet-common/runtime-benchmarks']
try-runtime = ["frame-support/try-runtime"]
pallets/structure/src/lib.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/>.1617//! # Structure Pallet18//!19//! The Structure pallet provides functionality for handling tokens nesting an unnesting.20//!21//! - [`Config`]22//! - [`Pallet`]23//!24//! ## Overview25//!26//! The Structure pallet provides functions for:27//!28//! - Searching for token parents, children and owners. Actual implementation of searching for29//! parent/child is done by pallets corresponding to token's collection type.30//! - Nesting and unnesting tokens. Actual implementation of nesting is done by pallets corresponding31//! to token's collection type.32//!33//! ### Terminology34//!35//! - **Nesting:** Setting up parent-child relationship between tokens. Nested tokens are inhereting36//! owner from their parent. There could be multiple levels of nesting. Token couldn't be nested in37//! it's child token i.e. parent-child relationship graph shouldn't have38//!39//! - **Parent:** Token that current token is nested in.40//!41//! - **Owner:** Account that owns the token and all nested tokens.42//!43//! ## Interface44//!45//! ### Available Functions46//!47//! - `find_parent` - Find parent of the token. It could be an account or another token.48//! - `parent_chain` - Find chain of parents of the token.49//! - `find_topmost_owner` - Find account or token in the end of the chain of parents.50//! - `check_nesting` - Check if the token could be nested in the other token51//! - `nest_if_sent_to_token` - Nest the token in the other token52//! - `unnest_if_nested` - Unnest the token from the other token5354#![cfg_attr(not(feature = "std"), no_std)]5556use pallet_common::CommonCollectionOperations;57use sp_std::collections::btree_set::BTreeSet;5859use frame_support::dispatch::{DispatchError, DispatchResult, DispatchResultWithPostInfo};60use frame_support::fail;61pub use pallet::*;62use pallet_common::{dispatch::CollectionDispatch, CollectionHandle};63use up_data_structs::{CollectionId, TokenId, mapping::TokenAddressMapping, budget::Budget};6465#[cfg(feature = "runtime-benchmarks")]66pub mod benchmarking;67pub mod weights;6869pub type SelfWeightOf<T> = <T as crate::Config>::WeightInfo;7071#[frame_support::pallet]72pub mod pallet {73 use frame_support::Parameter;74 use frame_support::dispatch::{GetDispatchInfo, UnfilteredDispatchable};75 use frame_support::pallet_prelude::*;7677 use super::*;7879 #[pallet::error]80 pub enum Error<T> {81 /// While nesting, encountered an already checked account, detecting a loop.82 OuroborosDetected,83 /// While nesting, reached the depth limit of nesting, exceeding the provided budget.84 DepthLimit,85 /// While nesting, reached the breadth limit of nesting, exceeding the provided budget.86 BreadthLimit,87 /// Couldn't find the token owner that is itself a token.88 TokenNotFound,89 }9091 #[pallet::event]92 pub enum Event<T> {93 /// Executed call on behalf of the token.94 Executed(DispatchResult),95 }9697 #[pallet::config]98 pub trait Config: frame_system::Config + pallet_common::Config {99 type WeightInfo: weights::WeightInfo;100 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;101 type RuntimeCall: Parameter102 + UnfilteredDispatchable<RuntimeOrigin = Self::RuntimeOrigin>103 + GetDispatchInfo;104 }105106 #[pallet::pallet]107 pub struct Pallet<T>(_);108109 #[pallet::call]110 impl<T: Config> Pallet<T> {111 // #[pallet::weight({112 // let dispatch_info = call.get_dispatch_info();113114 // (115 // dispatch_info.weight116 // // Cost of dereferencing parent117 // .saturating_add(T::DbWeight::get().reads(2 * *max_depth as Weight))118 // .saturating_add(4000 * *max_depth as Weight),119 // dispatch_info.class)120 // })]121 // pub fn execute(122 // origin: OriginFor<T>,123 // call: Box<<T as Config>::Call>,124 // max_depth: u32,125 // ) -> DispatchResult {126 }127}128129#[derive(PartialEq)]130pub enum Parent<CrossAccountId> {131 /// Token owned by a normal account.132 User(CrossAccountId),133 /// Could not find the token provided as the owner.134 TokenNotFound,135 /// Token owner is another token (still, the target token may not exist).136 Token(CollectionId, TokenId),137}138139impl<T: Config> Pallet<T> {140 /// Find account owning the `token` or a token that the `token` is nested in.141 ///142 /// Returns the enum that have three variants:143 /// - [`User`](crate::Parent<T>::User): Contains account.144 /// - [`Token`](crate::Parent<T>::Token): Contains token id and collection id.145 /// - [`TokenNotFound`](crate::Parent<T>::TokenNotFound): Indicates that parent was not found146 pub fn find_parent(147 collection: CollectionId,148 token: TokenId,149 ) -> Result<Parent<T::CrossAccountId>, DispatchError> {150 // TODO: Reduce cost by not reading collection config151 let handle = match CollectionHandle::try_get(collection) {152 Ok(v) => v,153 Err(_) => return Ok(Parent::TokenNotFound),154 };155 let handle = T::CollectionDispatch::dispatch(handle);156 let handle = handle.as_dyn();157158 Ok(match handle.token_owner(token) {159 Some(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {160 Some((collection, token)) => Parent::Token(collection, token),161 None => Parent::User(owner),162 },163 None => Parent::TokenNotFound,164 })165 }166167 /// Get the chain of parents of a token in the nesting hierarchy168 ///169 /// Returns an iterator of addresses of the owning tokens and the owning account,170 /// starting from the immediate parent token, ending with the account.171 /// Returns error if cycle is detected.172 pub fn parent_chain(173 mut collection: CollectionId,174 mut token: TokenId,175 ) -> impl Iterator<Item = Result<Parent<T::CrossAccountId>, DispatchError>> {176 let mut finished = false;177 let mut visited = BTreeSet::new();178 visited.insert((collection, token));179 core::iter::from_fn(move || {180 if finished {181 return None;182 }183 let parent = Self::find_parent(collection, token);184 match parent {185 Ok(Parent::Token(new_collection, new_token)) => {186 collection = new_collection;187 token = new_token;188 if !visited.insert((new_collection, new_token)) {189 finished = true;190 return Some(Err(<Error<T>>::OuroborosDetected.into()));191 }192 }193 _ => finished = true,194 }195 Some(parent as Result<_, DispatchError>)196 })197 }198199 /// Try to dereference address, until finding top level owner200 ///201 /// May return token address if parent token not yet exists202 ///203 /// - `budget`: Limit for searching parents in depth.204 pub fn find_topmost_owner(205 collection: CollectionId,206 token: TokenId,207 budget: &dyn Budget,208 ) -> Result<T::CrossAccountId, DispatchError> {209 let owner = Self::parent_chain(collection, token)210 .take_while(|_| budget.consume())211 .find(|p| matches!(p, Ok(Parent::User(_) | Parent::TokenNotFound)))212 .ok_or(<Error<T>>::DepthLimit)??;213214 Ok(match owner {215 Parent::User(v) => v,216 _ => fail!(<Error<T>>::TokenNotFound),217 })218 }219220 /// Find the topmost parent and check that assigning `for_nest` token as a child for221 /// `token` wouldn't create a cycle.222 ///223 /// - `budget`: Limit for searching parents in depth.224 pub fn get_checked_topmost_owner(225 collection: CollectionId,226 token: TokenId,227 for_nest: Option<(CollectionId, TokenId)>,228 budget: &dyn Budget,229 ) -> Result<T::CrossAccountId, DispatchError> {230 // Tried to nest token in itself231 if Some((collection, token)) == for_nest {232 return Err(<Error<T>>::OuroborosDetected.into());233 }234235 for parent in Self::parent_chain(collection, token).take_while(|_| budget.consume()) {236 match parent? {237 // Tried to nest token in chain, which has this token as one of parents238 Parent::Token(collection, token) if Some((collection, token)) == for_nest => {239 return Err(<Error<T>>::OuroborosDetected.into())240 }241 // Token is owned by other user242 Parent::User(user) => return Ok(user),243 Parent::TokenNotFound => return Err(<Error<T>>::TokenNotFound.into()),244 // Continue parent chain245 Parent::Token(_, _) => {}246 }247 }248249 Err(<Error<T>>::DepthLimit.into())250 }251252 /// Burn token and all of it's nested tokens253 ///254 /// - `self_budget`: Limit for searching children in depth.255 /// - `breadth_budget`: Limit of breadth of searching children.256 pub fn burn_item_recursively(257 from: T::CrossAccountId,258 collection: CollectionId,259 token: TokenId,260 self_budget: &dyn Budget,261 breadth_budget: &dyn Budget,262 ) -> DispatchResultWithPostInfo {263 let handle = <CollectionHandle<T>>::try_get(collection)?;264 let dispatch = T::CollectionDispatch::dispatch(handle);265 let dispatch = dispatch.as_dyn();266 dispatch.burn_item_recursively(from.clone(), token, self_budget, breadth_budget)267 }268269 /// Check if `token` indirectly owned by `user`270 ///271 /// Returns `true` if `user` is `token`'s owner. Or If token is provided as `user` then272 /// check that `user` and `token` have same owner.273 /// Checks that assigning `for_nest` token as a child for `token` wouldn't create a cycle.274 ///275 /// - `budget`: Limit for searching parents in depth.276 pub fn check_indirectly_owned(277 user: T::CrossAccountId,278 collection: CollectionId,279 token: TokenId,280 for_nest: Option<(CollectionId, TokenId)>,281 budget: &dyn Budget,282 ) -> Result<bool, DispatchError> {283 let target_parent = match T::CrossTokenAddressMapping::address_to_token(&user) {284 Some((collection, token)) => Self::find_topmost_owner(collection, token, budget)?,285 None => user,286 };287288 Self::get_checked_topmost_owner(collection, token, for_nest, budget)289 .map(|indirect_owner| indirect_owner == target_parent)290 }291292 /// Checks that `under` is valid token and that `token_id` could be nested under it293 /// and that `from` is `under`'s owner294 ///295 /// Returns OK if `under` is not a token296 ///297 /// - `nesting_budget`: Limit for searching parents in depth.298 pub fn check_nesting(299 from: T::CrossAccountId,300 under: &T::CrossAccountId,301 collection_id: CollectionId,302 token_id: TokenId,303 nesting_budget: &dyn Budget,304 ) -> DispatchResult {305 Self::try_exec_if_owner_is_valid_nft(under, |collection, parent_id| {306 collection.check_nesting(from, (collection_id, token_id), parent_id, nesting_budget)307 })308 }309310 /// Nests `token_id` under `under` token311 ///312 /// Returns OK if `under` is not a token. Checks that nesting is possible.313 ///314 /// - `nesting_budget`: Limit for searching parents in depth.315 pub fn nest_if_sent_to_token(316 from: T::CrossAccountId,317 under: &T::CrossAccountId,318 collection_id: CollectionId,319 token_id: TokenId,320 nesting_budget: &dyn Budget,321 ) -> DispatchResult {322 Self::try_exec_if_owner_is_valid_nft(under, |collection, parent_id| {323 collection.check_nesting(from, (collection_id, token_id), parent_id, nesting_budget)?;324325 collection.nest(parent_id, (collection_id, token_id));326327 Ok(())328 })329 }330331 /// Nests `token_id` under `owner` token332 ///333 /// Caller should check that nesting wouldn't cause recursion in nesting334 pub fn nest_if_sent_to_token_unchecked(335 owner: &T::CrossAccountId,336 collection_id: CollectionId,337 token_id: TokenId,338 ) {339 Self::exec_if_owner_is_valid_nft(owner, |collection, parent_id| {340 collection.nest(parent_id, (collection_id, token_id))341 });342 }343344 /// Unnests `token_id` from `owner`.345 pub fn unnest_if_nested(346 owner: &T::CrossAccountId,347 collection_id: CollectionId,348 token_id: TokenId,349 ) {350 Self::exec_if_owner_is_valid_nft(owner, |collection, parent_id| {351 collection.unnest(parent_id, (collection_id, token_id))352 });353 }354355 fn exec_if_owner_is_valid_nft(356 account: &T::CrossAccountId,357 action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId),358 ) {359 Self::try_exec_if_owner_is_valid_nft(account, |collection, id| {360 action(collection, id);361 Ok(())362 })363 .unwrap();364 }365366 fn try_exec_if_owner_is_valid_nft(367 account: &T::CrossAccountId,368 action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId) -> DispatchResult,369 ) -> DispatchResult {370 let account = T::CrossTokenAddressMapping::address_to_token(account);371372 if account.is_none() {373 return Ok(());374 }375376 let account = account.unwrap();377378 let handle = <CollectionHandle<T>>::try_get(account.0);379380 if handle.is_err() {381 return Ok(());382 }383384 let handle = handle.unwrap();385386 let dispatch = T::CollectionDispatch::dispatch(handle);387 let dispatch = dispatch.as_dyn();388389 action(dispatch, account.1)390 }391}