git.delta.rocks / unique-network / refs/commits / bebe624eff63

difftreelog

feat prevent ouroboros creation during nest

Yaroslav Bolyukin2022-04-19parent: #07a6969.patch.diff
in: master

11 files changed

modifiedclient/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,
modifiedpallets/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;
modifiedpallets/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 {
modifiedpallets/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,
modifiedpallets/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 {
modifiedpallets/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(())
modifiedpallets/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 {
modifiedpallets/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,
modifiedpallets/structure/src/lib.rsdiffbeforeafterboth
71#[derive(PartialEq)]71#[derive(PartialEq)]
72pub enum Parent<CrossAccountId> {72pub enum Parent<CrossAccountId> {
73 /// Token owned by normal account73 /// Token owned by normal account
74 Normal(CrossAccountId),74 User(CrossAccountId),
75 /// Passed token not found75 /// Passed token not found
76 TokenNotFound,76 TokenNotFound,
77 /// Token owner is another token (target token still may not exist)77 /// Token owner is another token (target token still may not exist)
94 Ok(match handle.token_owner(token) {94 Ok(match handle.token_owner(token) {
95 Some(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {95 Some(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {
96 Some((collection, token)) => Parent::Token(collection, token),96 Some((collection, token)) => Parent::Token(collection, token),
97 None => Parent::Normal(owner),97 None => Parent::User(owner),
98 },98 },
99 None => Parent::TokenNotFound,99 None => Parent::TokenNotFound,
100 })100 })
137 ) -> Result<T::CrossAccountId, DispatchError> {137 ) -> Result<T::CrossAccountId, DispatchError> {
138 let owner = Self::parent_chain(collection, token)138 let owner = Self::parent_chain(collection, token)
139 .take_while(|_| budget.consume())139 .take_while(|_| budget.consume())
140 .find(|p| matches!(p, Ok(Parent::Normal(_) | Parent::TokenNotFound)))140 .find(|p| matches!(p, Ok(Parent::User(_) | Parent::TokenNotFound)))
141 .ok_or(<Error<T>>::DepthLimit)??;141 .ok_or(<Error<T>>::DepthLimit)??;
142142
143 Ok(match owner {143 Ok(match owner {
144 Parent::Normal(v) => v,144 Parent::User(v) => v,
145 _ => fail!(<Error<T>>::TokenNotFound),145 _ => fail!(<Error<T>>::TokenNotFound),
146 })146 })
147 }147 }
148148
149 /// Check if token indirectly owned by specified user149 /// Check if token indirectly owned by specified user
150 pub fn indirectly_owned(150 pub fn check_indirectly_owned(
151 user: T::CrossAccountId,151 user: T::CrossAccountId,
152 collection: CollectionId,152 collection: CollectionId,
153 token: TokenId,153 token: TokenId,
154 for_nest: Option<(CollectionId, TokenId)>,
154 budget: &dyn Budget,155 budget: &dyn Budget,
155 ) -> Result<bool, DispatchError> {156 ) -> Result<bool, DispatchError> {
156 let target_parent = match T::CrossTokenAddressMapping::address_to_token(&user) {157 let target_parent = match T::CrossTokenAddressMapping::address_to_token(&user) {
157 Some((collection, token)) => Parent::Token(collection, token),158 Some((collection, token)) => Parent::Token(collection, token),
158 None => Parent::Normal(user),159 None => Parent::User(user),
159 };160 };
161
162 // Tried to nest token in itself
163 if Some((collection, token)) == for_nest {
164 return Err(<Error<T>>::OuroborosDetected.into());
165 }
160166
161 Ok(Self::parent_chain(collection, token)167 for parent in Self::parent_chain(collection, token).take_while(|_| budget.consume()) {
162 .take_while(|_| budget.consume())
163 .any(|parent| Ok(&target_parent) == parent.as_ref()))168 match parent? {
169 // Tried to nest token in chain, which has this token as one of parents
170 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 owned
174 v if v == target_parent => return Ok(true),
175 Parent::TokenNotFound => return Ok(false),
176 _ => {}
177 }
178 }
179
180 Err(<Error<T>>::DepthLimit.into())
164 }181 }
165}182}
166183
modifiedtests/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();
addedtests/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/);
+    });
+  });
+});