difftreelog
feat prevent ouroboros creation during nest
in: master
11 files changed
client/rpc/src/lib.rsdiffbeforeafterboth--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -77,11 +77,7 @@
) -> Result<Vec<u8>>;
#[rpc(name = "unique_totalSupply")]
- fn total_supply(
- &self,
- collection: CollectionId,
- at: Option<BlockHash>,
- ) -> Result<u32>;
+ fn total_supply(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<u32>;
#[rpc(name = "unique_accountBalance")]
fn account_balance(
&self,
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -918,7 +918,7 @@
fn check_nesting(
&self,
sender: T::CrossAccountId,
- from: CollectionId,
+ from: (CollectionId, TokenId),
under: TokenId,
budget: &dyn Budget,
) -> DispatchResult;
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -237,7 +237,7 @@
fn check_nesting(
&self,
_sender: <T>::CrossAccountId,
- _from: CollectionId,
+ _from: (CollectionId, TokenId),
_under: TokenId,
_budget: &dyn Budget,
) -> sp_runtime::DispatchResult {
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -224,7 +224,12 @@
let dispatch = T::CollectionDispatch::dispatch(handle);
let dispatch = dispatch.as_dyn();
- dispatch.check_nesting(from.clone(), collection.id, target.1, nesting_budget)?;
+ dispatch.check_nesting(
+ from.clone(),
+ (collection.id, TokenId::default()),
+ target.1,
+ nesting_budget,
+ )?;
}
// =========
@@ -293,7 +298,12 @@
let dispatch = T::CollectionDispatch::dispatch(handle);
let dispatch = dispatch.as_dyn();
- dispatch.check_nesting(sender.clone(), collection.id, target.1, nesting_budget)?;
+ dispatch.check_nesting(
+ sender.clone(),
+ (collection.id, TokenId::default()),
+ target.1,
+ nesting_budget,
+ )?;
}
}
@@ -386,10 +396,11 @@
if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {
// TODO: should collection owner be allowed to perform this transfer?
ensure!(
- <PalletStructure<T>>::indirectly_owned(
+ <PalletStructure<T>>::check_indirectly_owned(
spender.clone(),
source.0,
source.1,
+ None,
nesting_budget
)?,
<CommonError<T>>::ApprovedValueTooLow,
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -251,7 +251,7 @@
fn check_nesting(
&self,
sender: T::CrossAccountId,
- from: CollectionId,
+ from: (CollectionId, TokenId),
under: TokenId,
budget: &dyn Budget,
) -> sp_runtime::DispatchResult {
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -296,7 +296,12 @@
let dispatch = T::CollectionDispatch::dispatch(handle);
let dispatch = dispatch.as_dyn();
- dispatch.check_nesting(from.clone(), collection.id, target.1, nesting_budget)?;
+ dispatch.check_nesting(
+ from.clone(),
+ (collection.id, token),
+ target.1,
+ nesting_budget,
+ )?;
}
// =========
@@ -381,13 +386,18 @@
);
}
- for (to, _) in balances.iter() {
- if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {
+ for (i, data) in data.iter().enumerate() {
+ let token = TokenId(first_token + i as u32 + 1);
+ if let Some(target) = T::CrossTokenAddressMapping::address_to_token(&data.owner) {
let handle = <CollectionHandle<T>>::try_get(target.0)?;
let dispatch = T::CollectionDispatch::dispatch(handle);
let dispatch = dispatch.as_dyn();
-
- dispatch.check_nesting(sender.clone(), collection.id, target.1, nesting_budget)?;
+ dispatch.check_nesting(
+ sender.clone(),
+ (collection.id, token),
+ target.1,
+ nesting_budget,
+ )?;
}
}
@@ -535,10 +545,11 @@
if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {
// TODO: should collection owner be allowed to perform this transfer?
ensure!(
- <PalletStructure<T>>::indirectly_owned(
+ <PalletStructure<T>>::check_indirectly_owned(
spender.clone(),
source.0,
source.1,
+ None,
nesting_budget
)?,
<CommonError<T>>::ApprovedValueTooLow,
@@ -610,31 +621,40 @@
pub fn check_nesting(
handle: &NonfungibleHandle<T>,
sender: T::CrossAccountId,
- from: CollectionId,
+ from: (CollectionId, TokenId),
under: TokenId,
nesting_budget: &dyn Budget,
) -> DispatchResult {
fn ensure_sender_allowed<T: Config>(
collection: CollectionId,
token: TokenId,
+ for_nest: (CollectionId, TokenId),
sender: T::CrossAccountId,
budget: &dyn Budget,
) -> DispatchResult {
ensure!(
- <PalletStructure<T>>::indirectly_owned(sender, collection, token, budget)?,
+ <PalletStructure<T>>::check_indirectly_owned(
+ sender,
+ collection,
+ token,
+ Some(for_nest),
+ budget
+ )?,
<CommonError<T>>::OnlyOwnerAllowedToNest,
);
Ok(())
}
match handle.limits.nesting_rule() {
NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),
- NestingRule::Owner => ensure_sender_allowed::<T>(handle.id, under, sender, nesting_budget)?,
+ NestingRule::Owner => {
+ ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?
+ }
NestingRule::OwnerRestricted(whitelist) => {
ensure!(
- whitelist.contains(&from),
+ whitelist.contains(&from.0),
<CommonError<T>>::SourceCollectionIsNotAllowedToNest
);
- ensure_sender_allowed::<T>(handle.id, under, sender, nesting_budget)?
+ ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?
}
}
Ok(())
pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -260,7 +260,7 @@
fn check_nesting(
&self,
_sender: <T>::CrossAccountId,
- _from: CollectionId,
+ _from: (CollectionId, TokenId),
_under: TokenId,
_budget: &dyn Budget,
) -> sp_runtime::DispatchResult {
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -352,7 +352,12 @@
let dispatch = T::CollectionDispatch::dispatch(handle);
let dispatch = dispatch.as_dyn();
- dispatch.check_nesting(from.clone(), collection.id, target.1, nesting_budget)?;
+ dispatch.check_nesting(
+ from.clone(),
+ (collection.id, token),
+ target.1,
+ nesting_budget,
+ )?;
}
// =========
@@ -455,7 +460,8 @@
}
}
- for token in data.iter() {
+ for (i, token) in data.iter().enumerate() {
+ let token_id = TokenId(first_token_id + i as u32 + 1);
for (to, _) in token.users.iter() {
if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {
let handle = <CollectionHandle<T>>::try_get(target.0)?;
@@ -464,7 +470,7 @@
dispatch.check_nesting(
sender.clone(),
- collection.id,
+ (collection.id, token_id),
target.1,
nesting_budget,
)?;
@@ -575,10 +581,11 @@
if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {
// TODO: should collection owner be allowed to perform this transfer?
ensure!(
- <PalletStructure<T>>::indirectly_owned(
+ <PalletStructure<T>>::check_indirectly_owned(
spender.clone(),
source.0,
source.1,
+ None,
nesting_budget
)?,
<CommonError<T>>::ApprovedValueTooLow,
pallets/structure/src/lib.rsdiffbeforeafterboth1#![cfg_attr(not(feature = "std"), no_std)]23use sp_std::collections::btree_set::BTreeSet;45use frame_support::dispatch::DispatchError;6use frame_support::fail;7pub use pallet::*;8use pallet_common::{dispatch::CollectionDispatch, CollectionHandle};9use up_data_structs::{CollectionId, TokenId, mapping::TokenAddressMapping, budget::Budget};1011#[cfg(feature = "runtime-benchmarks")]12pub mod benchmarking;13pub mod weights;1415pub type SelfWeightOf<T> = <T as crate::Config>::WeightInfo;1617#[frame_support::pallet]18pub mod pallet {19 use frame_support::Parameter;20 use frame_support::dispatch::{GetDispatchInfo, UnfilteredDispatchable};21 use frame_support::pallet_prelude::*;2223 use super::*;2425 #[pallet::error]26 pub enum Error<T> {27 /// While searched for owner, got already checked account28 OuroborosDetected,29 /// While searched for owner, encountered depth limit30 DepthLimit,31 /// While searched for owner, found token owner by not-yet-existing token32 TokenNotFound,33 }3435 #[pallet::event]36 pub enum Event<T> {37 /// Executed call on behalf of token38 Executed(DispatchResult),39 }4041 #[pallet::config]42 pub trait Config: frame_system::Config + pallet_common::Config {43 type WeightInfo: weights::WeightInfo;44 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;45 type Call: Parameter + UnfilteredDispatchable<Origin = Self::Origin> + GetDispatchInfo;46 }4748 #[pallet::pallet]49 pub struct Pallet<T>(_);5051 #[pallet::call]52 impl<T: Config> Pallet<T> {53 // #[pallet::weight({54 // let dispatch_info = call.get_dispatch_info();5556 // (57 // dispatch_info.weight58 // // Cost of dereferencing parent59 // .saturating_add(T::DbWeight::get().reads(2 * *max_depth as Weight))60 // .saturating_add(4000 * *max_depth as Weight),61 // dispatch_info.class)62 // })]63 // pub fn execute(64 // origin: OriginFor<T>,65 // call: Box<<T as Config>::Call>,66 // max_depth: u32,67 // ) -> DispatchResult {68 }69}7071#[derive(PartialEq)]72pub enum Parent<CrossAccountId> {73 /// Token owned by normal account74 Normal(CrossAccountId),75 /// Passed token not found76 TokenNotFound,77 /// Token owner is another token (target token still may not exist)78 Token(CollectionId, TokenId),79}8081impl<T: Config> Pallet<T> {82 pub fn find_parent(83 collection: CollectionId,84 token: TokenId,85 ) -> Result<Parent<T::CrossAccountId>, DispatchError> {86 // TODO: Reduce cost by not reading collection config87 let handle = match CollectionHandle::try_get(collection) {88 Ok(v) => v,89 Err(_) => return Ok(Parent::TokenNotFound),90 };91 let handle = T::CollectionDispatch::dispatch(handle);92 let handle = handle.as_dyn();9394 Ok(match handle.token_owner(token) {95 Some(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {96 Some((collection, token)) => Parent::Token(collection, token),97 None => Parent::Normal(owner),98 },99 None => Parent::TokenNotFound,100 })101 }102103 pub fn parent_chain(104 mut collection: CollectionId,105 mut token: TokenId,106 ) -> impl Iterator<Item = Result<Parent<T::CrossAccountId>, DispatchError>> {107 let mut finished = false;108 let mut visited = BTreeSet::new();109 visited.insert((collection, token));110 core::iter::from_fn(move || {111 if finished {112 return None;113 }114 let parent = Self::find_parent(collection, token);115 match parent {116 Ok(Parent::Token(new_collection, new_token)) => {117 collection = new_collection;118 token = new_token;119 if !visited.insert((new_collection, new_token)) {120 finished = true;121 return Some(Err(<Error<T>>::OuroborosDetected.into()));122 }123 }124 _ => finished = true,125 }126 Some(parent as Result<_, DispatchError>)127 })128 }129130 /// Try to dereference address, until finding top level owner131 ///132 /// May return token address if parent token not yet exists133 pub fn find_topmost_owner(134 collection: CollectionId,135 token: TokenId,136 budget: &dyn Budget,137 ) -> Result<T::CrossAccountId, DispatchError> {138 let owner = Self::parent_chain(collection, token)139 .take_while(|_| budget.consume())140 .find(|p| matches!(p, Ok(Parent::Normal(_) | Parent::TokenNotFound)))141 .ok_or(<Error<T>>::DepthLimit)??;142143 Ok(match owner {144 Parent::Normal(v) => v,145 _ => fail!(<Error<T>>::TokenNotFound),146 })147 }148149 /// Check if token indirectly owned by specified user150 pub fn indirectly_owned(151 user: T::CrossAccountId,152 collection: CollectionId,153 token: TokenId,154 budget: &dyn Budget,155 ) -> Result<bool, DispatchError> {156 let target_parent = match T::CrossTokenAddressMapping::address_to_token(&user) {157 Some((collection, token)) => Parent::Token(collection, token),158 None => Parent::Normal(user),159 };160161 Ok(Self::parent_chain(collection, token)162 .take_while(|_| budget.consume())163 .any(|parent| Ok(&target_parent) == parent.as_ref()))164 }165}1#![cfg_attr(not(feature = "std"), no_std)]23use sp_std::collections::btree_set::BTreeSet;45use frame_support::dispatch::DispatchError;6use frame_support::fail;7pub use pallet::*;8use pallet_common::{dispatch::CollectionDispatch, CollectionHandle};9use up_data_structs::{CollectionId, TokenId, mapping::TokenAddressMapping, budget::Budget};1011#[cfg(feature = "runtime-benchmarks")]12pub mod benchmarking;13pub mod weights;1415pub type SelfWeightOf<T> = <T as crate::Config>::WeightInfo;1617#[frame_support::pallet]18pub mod pallet {19 use frame_support::Parameter;20 use frame_support::dispatch::{GetDispatchInfo, UnfilteredDispatchable};21 use frame_support::pallet_prelude::*;2223 use super::*;2425 #[pallet::error]26 pub enum Error<T> {27 /// While searched for owner, got already checked account28 OuroborosDetected,29 /// While searched for owner, encountered depth limit30 DepthLimit,31 /// While searched for owner, found token owner by not-yet-existing token32 TokenNotFound,33 }3435 #[pallet::event]36 pub enum Event<T> {37 /// Executed call on behalf of token38 Executed(DispatchResult),39 }4041 #[pallet::config]42 pub trait Config: frame_system::Config + pallet_common::Config {43 type WeightInfo: weights::WeightInfo;44 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;45 type Call: Parameter + UnfilteredDispatchable<Origin = Self::Origin> + GetDispatchInfo;46 }4748 #[pallet::pallet]49 pub struct Pallet<T>(_);5051 #[pallet::call]52 impl<T: Config> Pallet<T> {53 // #[pallet::weight({54 // let dispatch_info = call.get_dispatch_info();5556 // (57 // dispatch_info.weight58 // // Cost of dereferencing parent59 // .saturating_add(T::DbWeight::get().reads(2 * *max_depth as Weight))60 // .saturating_add(4000 * *max_depth as Weight),61 // dispatch_info.class)62 // })]63 // pub fn execute(64 // origin: OriginFor<T>,65 // call: Box<<T as Config>::Call>,66 // max_depth: u32,67 // ) -> DispatchResult {68 }69}7071#[derive(PartialEq)]72pub enum Parent<CrossAccountId> {73 /// Token owned by normal account74 User(CrossAccountId),75 /// Passed token not found76 TokenNotFound,77 /// Token owner is another token (target token still may not exist)78 Token(CollectionId, TokenId),79}8081impl<T: Config> Pallet<T> {82 pub fn find_parent(83 collection: CollectionId,84 token: TokenId,85 ) -> Result<Parent<T::CrossAccountId>, DispatchError> {86 // TODO: Reduce cost by not reading collection config87 let handle = match CollectionHandle::try_get(collection) {88 Ok(v) => v,89 Err(_) => return Ok(Parent::TokenNotFound),90 };91 let handle = T::CollectionDispatch::dispatch(handle);92 let handle = handle.as_dyn();9394 Ok(match handle.token_owner(token) {95 Some(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {96 Some((collection, token)) => Parent::Token(collection, token),97 None => Parent::User(owner),98 },99 None => Parent::TokenNotFound,100 })101 }102103 pub fn parent_chain(104 mut collection: CollectionId,105 mut token: TokenId,106 ) -> impl Iterator<Item = Result<Parent<T::CrossAccountId>, DispatchError>> {107 let mut finished = false;108 let mut visited = BTreeSet::new();109 visited.insert((collection, token));110 core::iter::from_fn(move || {111 if finished {112 return None;113 }114 let parent = Self::find_parent(collection, token);115 match parent {116 Ok(Parent::Token(new_collection, new_token)) => {117 collection = new_collection;118 token = new_token;119 if !visited.insert((new_collection, new_token)) {120 finished = true;121 return Some(Err(<Error<T>>::OuroborosDetected.into()));122 }123 }124 _ => finished = true,125 }126 Some(parent as Result<_, DispatchError>)127 })128 }129130 /// Try to dereference address, until finding top level owner131 ///132 /// May return token address if parent token not yet exists133 pub fn find_topmost_owner(134 collection: CollectionId,135 token: TokenId,136 budget: &dyn Budget,137 ) -> Result<T::CrossAccountId, DispatchError> {138 let owner = Self::parent_chain(collection, token)139 .take_while(|_| budget.consume())140 .find(|p| matches!(p, Ok(Parent::User(_) | Parent::TokenNotFound)))141 .ok_or(<Error<T>>::DepthLimit)??;142143 Ok(match owner {144 Parent::User(v) => v,145 _ => fail!(<Error<T>>::TokenNotFound),146 })147 }148149 /// Check if token indirectly owned by specified user150 pub fn check_indirectly_owned(151 user: T::CrossAccountId,152 collection: CollectionId,153 token: TokenId,154 for_nest: Option<(CollectionId, TokenId)>,155 budget: &dyn Budget,156 ) -> Result<bool, DispatchError> {157 let target_parent = match T::CrossTokenAddressMapping::address_to_token(&user) {158 Some((collection, token)) => Parent::Token(collection, token),159 None => Parent::User(user),160 };161162 // Tried to nest token in itself163 if Some((collection, token)) == for_nest {164 return Err(<Error<T>>::OuroborosDetected.into());165 }166167 for parent in Self::parent_chain(collection, token).take_while(|_| budget.consume()) {168 match parent? {169 // Tried to nest token in chain, which has this token as one of parents170 Parent::Token(collection, token) if Some((collection, token)) == for_nest => {171 return Err(<Error<T>>::OuroborosDetected.into())172 }173 // Found needed parent, token is indirecty owned174 v if v == target_parent => return Ok(true),175 Parent::TokenNotFound => return Ok(false),176 _ => {}177 }178 }179180 Err(<Error<T>>::DepthLimit.into())181 }182}tests/src/eth/util/helpers.tsdiffbeforeafterboth--- a/tests/src/eth/util/helpers.ts
+++ b/tests/src/eth/util/helpers.ts
@@ -23,7 +23,7 @@
import usingApi, {submitTransactionAsync} from '../../substrate/substrate-api';
import {IKeyringPair} from '@polkadot/types/types';
import {expect} from 'chai';
-import {getGenericResult, UNIQUE} from '../../util/helpers';
+import {CrossAccountId, getGenericResult, UNIQUE} from '../../util/helpers';
import * as solc from 'solc';
import config from '../../config';
import privateKey from '../../substrate/privateKey';
@@ -80,6 +80,11 @@
]);
return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));
}
+export function tokenIdToCross(collection: number, token: number): CrossAccountId {
+ return {
+ Ethereum: tokenIdToAddress(collection, token),
+ };
+}
export function createEthAccount(web3: Web3) {
const account = web3.eth.accounts.create();
tests/src/nesting/graphs.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/nesting/graphs.test.ts
@@ -0,0 +1,51 @@
+import {ApiPromise} from '@polkadot/api';
+import {IKeyringPair} from '@polkadot/types/types';
+import {expect} from 'chai';
+import {tokenIdToCross} from '../eth/util/helpers';
+import privateKey from '../substrate/privateKey';
+import usingApi, {executeTransaction} from '../substrate/substrate-api';
+import {getCreateCollectionResult, transferExpectSuccess} from '../util/helpers';
+
+/**
+ * ```dot
+ * 4 -> 3 -> 2 -> 1
+ * 7 -> 6 -> 5 -> 2
+ * 8 -> 5
+ * ```
+ */
+async function buildComplexObjectGraph(api: ApiPromise, sender: IKeyringPair): Promise<number> {
+ const events = await executeTransaction(api, sender, api.tx.unique.createCollectionEx({mode: 'NFT'}));
+ const {collectionId} = getCreateCollectionResult(events);
+
+ await executeTransaction(api, sender, api.tx.unique.createMultipleItemsEx(collectionId, {NFT: Array(8).fill({owner: {Substrate: sender.address}})}));
+
+ await transferExpectSuccess(collectionId, 8, sender, tokenIdToCross(collectionId, 5));
+
+ await transferExpectSuccess(collectionId, 7, sender, tokenIdToCross(collectionId, 6));
+ await transferExpectSuccess(collectionId, 6, sender, tokenIdToCross(collectionId, 5));
+ await transferExpectSuccess(collectionId, 5, sender, tokenIdToCross(collectionId, 2));
+
+ await transferExpectSuccess(collectionId, 4, sender, tokenIdToCross(collectionId, 3));
+ await transferExpectSuccess(collectionId, 3, sender, tokenIdToCross(collectionId, 2));
+ await transferExpectSuccess(collectionId, 2, sender, tokenIdToCross(collectionId, 1));
+
+ return collectionId;
+}
+
+describe('graphs', () => {
+ it('ouroboros can\'t be created in graph', async () => {
+ await usingApi(async api => {
+ const alice = privateKey('//Alice');
+ const collection = await buildComplexObjectGraph(api, alice);
+
+ // to self
+ await expect(executeTransaction(api, alice, api.tx.unique.transfer(tokenIdToCross(collection, 1), collection, 1, 1)))
+ .to.be.rejectedWith(/structure\.OuroborosDetected/);
+ // to nested part of graph
+ await expect(executeTransaction(api, alice, api.tx.unique.transfer(tokenIdToCross(collection, 5), collection, 1, 1)))
+ .to.be.rejectedWith(/structure\.OuroborosDetected/);
+ await expect(executeTransaction(api, alice, api.tx.unique.transfer(tokenIdToCross(collection, 8), collection, 2, 1)))
+ .to.be.rejectedWith(/structure\.OuroborosDetected/);
+ });
+ });
+});