difftreelog
feat prevent ouroboros creation during nest
in: master
11 files changed
client/rpc/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/>.1617use std::sync::Arc;1819use codec::Decode;20use jsonrpc_core::{Error as RpcError, ErrorCode, Result};21use jsonrpc_derive::rpc;22use up_data_structs::{RpcCollection, CollectionId, CollectionStats, CollectionLimits, TokenId};23use sp_api::{BlockId, BlockT, ProvideRuntimeApi, ApiExt};24use sp_blockchain::HeaderBackend;25use up_rpc::UniqueApi as UniqueRuntimeApi;2627#[rpc]28pub trait UniqueApi<BlockHash, CrossAccountId, AccountId> {29 #[rpc(name = "unique_accountTokens")]30 fn account_tokens(31 &self,32 collection: CollectionId,33 account: CrossAccountId,34 at: Option<BlockHash>,35 ) -> Result<Vec<TokenId>>;36 #[rpc(name = "unique_collectionTokens")]37 fn collection_tokens(38 &self,39 collection: CollectionId,40 at: Option<BlockHash>,41 ) -> Result<Vec<TokenId>>;42 #[rpc(name = "unique_tokenExists")]43 fn token_exists(44 &self,45 collection: CollectionId,46 token: TokenId,47 at: Option<BlockHash>,48 ) -> Result<bool>;4950 #[rpc(name = "unique_tokenOwner")]51 fn token_owner(52 &self,53 collection: CollectionId,54 token: TokenId,55 at: Option<BlockHash>,56 ) -> Result<Option<CrossAccountId>>;57 #[rpc(name = "unique_topmostTokenOwner")]58 fn topmost_token_owner(59 &self,60 collection: CollectionId,61 token: TokenId,62 at: Option<BlockHash>,63 ) -> Result<Option<CrossAccountId>>;64 #[rpc(name = "unique_constMetadata")]65 fn const_metadata(66 &self,67 collection: CollectionId,68 token: TokenId,69 at: Option<BlockHash>,70 ) -> Result<Vec<u8>>;71 #[rpc(name = "unique_variableMetadata")]72 fn variable_metadata(73 &self,74 collection: CollectionId,75 token: TokenId,76 at: Option<BlockHash>,77 ) -> Result<Vec<u8>>;7879 #[rpc(name = "unique_totalSupply")]80 fn total_supply(81 &self,82 collection: CollectionId,83 at: Option<BlockHash>,84 ) -> Result<u32>;85 #[rpc(name = "unique_accountBalance")]86 fn account_balance(87 &self,88 collection: CollectionId,89 account: CrossAccountId,90 at: Option<BlockHash>,91 ) -> Result<u32>;92 #[rpc(name = "unique_balance")]93 fn balance(94 &self,95 collection: CollectionId,96 account: CrossAccountId,97 token: TokenId,98 at: Option<BlockHash>,99 ) -> Result<String>;100 #[rpc(name = "unique_allowance")]101 fn allowance(102 &self,103 collection: CollectionId,104 sender: CrossAccountId,105 spender: CrossAccountId,106 token: TokenId,107 at: Option<BlockHash>,108 ) -> Result<String>;109110 #[rpc(name = "unique_adminlist")]111 fn adminlist(112 &self,113 collection: CollectionId,114 at: Option<BlockHash>,115 ) -> Result<Vec<CrossAccountId>>;116 #[rpc(name = "unique_allowlist")]117 fn allowlist(118 &self,119 collection: CollectionId,120 at: Option<BlockHash>,121 ) -> Result<Vec<CrossAccountId>>;122 #[rpc(name = "unique_allowed")]123 fn allowed(124 &self,125 collection: CollectionId,126 user: CrossAccountId,127 at: Option<BlockHash>,128 ) -> Result<bool>;129 #[rpc(name = "unique_lastTokenId")]130 fn last_token_id(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<TokenId>;131 #[rpc(name = "unique_collectionById")]132 fn collection_by_id(133 &self,134 collection: CollectionId,135 at: Option<BlockHash>,136 ) -> Result<Option<RpcCollection<AccountId>>>;137 #[rpc(name = "unique_collectionStats")]138 fn collection_stats(&self, at: Option<BlockHash>) -> Result<CollectionStats>;139140 #[rpc(name = "unique_nextSponsored")]141 fn next_sponsored(142 &self,143 collection: CollectionId,144 account: CrossAccountId,145 token: TokenId,146 at: Option<BlockHash>,147 ) -> Result<Option<u64>>;148 #[rpc(name = "unique_effectiveCollectionLimits")]149 fn effective_collection_limits(150 &self,151 collection_id: CollectionId,152 at: Option<BlockHash>,153 ) -> Result<Option<CollectionLimits>>;154}155156pub struct Unique<C, P> {157 client: Arc<C>,158 _marker: std::marker::PhantomData<P>,159}160161impl<C, P> Unique<C, P> {162 pub fn new(client: Arc<C>) -> Self {163 Self {164 client,165 _marker: Default::default(),166 }167 }168}169170pub enum Error {171 RuntimeError,172}173174impl From<Error> for i64 {175 fn from(e: Error) -> i64 {176 match e {177 Error::RuntimeError => 1,178 }179 }180}181182macro_rules! pass_method {183 (184 $method_name:ident($($name:ident: $ty:ty),* $(,)?) -> $result:ty $(=> $mapper:expr)?185 $(; changed_in $ver:expr, $changed_method_name:ident ($($changed_name:expr), * $(,)?) => $fixer:expr)*186 ) => {187 fn $method_name(188 &self,189 $(190 $name: $ty,191 )*192 at: Option<<Block as BlockT>::Hash>,193 ) -> Result<$result> {194 let api = self.client.runtime_api();195 let at = BlockId::hash(at.unwrap_or_else(|| self.client.info().best_hash));196 let _api_version = if let Ok(Some(api_version)) =197 api.api_version::<dyn UniqueRuntimeApi<Block, CrossAccountId, AccountId>>(&at)198 {199 api_version200 } else {201 // unreachable for our runtime202 return Err(RpcError {203 code: ErrorCode::InvalidParams,204 message: "Api is not available".into(),205 data: None,206 })207 };208209 let result = $(if _api_version < $ver {210 api.$changed_method_name(&at, $($changed_name),*).map(|r| r.map($fixer))211 } else)*212 { api.$method_name(&at, $($name),*) };213214 let result = result.map_err(|e| RpcError {215 code: ErrorCode::ServerError(Error::RuntimeError.into()),216 message: "Unable to query".into(),217 data: Some(format!("{:?}", e).into()),218 })?;219 result.map_err(|e| RpcError {220 code: ErrorCode::InvalidParams,221 message: "Runtime returned error".into(),222 data: Some(format!("{:?}", e).into()),223 })$(.map($mapper))?224 }225 };226}227228#[allow(deprecated)]229impl<C, Block, CrossAccountId, AccountId>230 UniqueApi<<Block as BlockT>::Hash, CrossAccountId, AccountId> for Unique<C, Block>231where232 Block: BlockT,233 AccountId: Decode,234 C: 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,235 C::Api: UniqueRuntimeApi<Block, CrossAccountId, AccountId>,236 CrossAccountId: pallet_evm::account::CrossAccountId<AccountId>,237{238 pass_method!(account_tokens(collection: CollectionId, account: CrossAccountId) -> Vec<TokenId>);239 pass_method!(collection_tokens(collection: CollectionId) -> Vec<TokenId>);240 pass_method!(token_exists(collection: CollectionId, token: TokenId) -> bool);241 pass_method!(242 token_owner(collection: CollectionId, token: TokenId) -> Option<CrossAccountId>;243 changed_in 2, token_owner_before_version_2(collection, token) => |u| Some(u)244 );245 pass_method!(topmost_token_owner(collection: CollectionId, token: TokenId) -> Option<CrossAccountId>);246 pass_method!(const_metadata(collection: CollectionId, token: TokenId) -> Vec<u8>);247 pass_method!(variable_metadata(collection: CollectionId, token: TokenId) -> Vec<u8>);248249 pass_method!(total_supply(collection: CollectionId) -> u32);250 pass_method!(account_balance(collection: CollectionId, account: CrossAccountId) -> u32);251 pass_method!(balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> String => |v| v.to_string());252 pass_method!(allowance(collection: CollectionId, sender: CrossAccountId, spender: CrossAccountId, token: TokenId) -> String => |v| v.to_string());253254 pass_method!(adminlist(collection: CollectionId) -> Vec<CrossAccountId>);255 pass_method!(allowlist(collection: CollectionId) -> Vec<CrossAccountId>);256 pass_method!(allowed(collection: CollectionId, user: CrossAccountId) -> bool);257 pass_method!(last_token_id(collection: CollectionId) -> TokenId);258 pass_method!(collection_by_id(collection: CollectionId) -> Option<RpcCollection<AccountId>>);259 pass_method!(collection_stats() -> CollectionStats);260 pass_method!(next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Option<u64>);261 pass_method!(effective_collection_limits(collection_id: CollectionId) -> Option<CollectionLimits>);262}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.rsdiffbeforeafterboth--- a/pallets/structure/src/lib.rs
+++ b/pallets/structure/src/lib.rs
@@ -71,7 +71,7 @@
#[derive(PartialEq)]
pub enum Parent<CrossAccountId> {
/// Token owned by normal account
- Normal(CrossAccountId),
+ User(CrossAccountId),
/// Passed token not found
TokenNotFound,
/// Token owner is another token (target token still may not exist)
@@ -94,7 +94,7 @@
Ok(match handle.token_owner(token) {
Some(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {
Some((collection, token)) => Parent::Token(collection, token),
- None => Parent::Normal(owner),
+ None => Parent::User(owner),
},
None => Parent::TokenNotFound,
})
@@ -137,29 +137,46 @@
) -> Result<T::CrossAccountId, DispatchError> {
let owner = Self::parent_chain(collection, token)
.take_while(|_| budget.consume())
- .find(|p| matches!(p, Ok(Parent::Normal(_) | Parent::TokenNotFound)))
+ .find(|p| matches!(p, Ok(Parent::User(_) | Parent::TokenNotFound)))
.ok_or(<Error<T>>::DepthLimit)??;
Ok(match owner {
- Parent::Normal(v) => v,
+ Parent::User(v) => v,
_ => fail!(<Error<T>>::TokenNotFound),
})
}
/// Check if token indirectly owned by specified user
- pub fn indirectly_owned(
+ pub fn check_indirectly_owned(
user: T::CrossAccountId,
collection: CollectionId,
token: TokenId,
+ for_nest: Option<(CollectionId, TokenId)>,
budget: &dyn Budget,
) -> Result<bool, DispatchError> {
let target_parent = match T::CrossTokenAddressMapping::address_to_token(&user) {
Some((collection, token)) => Parent::Token(collection, token),
- None => Parent::Normal(user),
+ None => Parent::User(user),
};
- Ok(Self::parent_chain(collection, token)
- .take_while(|_| budget.consume())
- .any(|parent| Ok(&target_parent) == parent.as_ref()))
+ // Tried to nest token in itself
+ if Some((collection, token)) == for_nest {
+ return Err(<Error<T>>::OuroborosDetected.into());
+ }
+
+ for parent in Self::parent_chain(collection, token).take_while(|_| budget.consume()) {
+ match parent? {
+ // Tried to nest token in chain, which has this token as one of parents
+ Parent::Token(collection, token) if Some((collection, token)) == for_nest => {
+ return Err(<Error<T>>::OuroborosDetected.into())
+ }
+ // Found needed parent, token is indirecty owned
+ v if v == target_parent => return Ok(true),
+ Parent::TokenNotFound => return Ok(false),
+ _ => {}
+ }
+ }
+
+ Err(<Error<T>>::DepthLimit.into())
}
}
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/);
+ });
+ });
+});