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.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.tsdiffbeforeafterboth1// 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// eslint-disable-next-line @typescript-eslint/triple-slash-reference18/// <reference path="helpers.d.ts" />1920import {ApiPromise} from '@polkadot/api';21import {addressToEvm, evmToAddress} from '@polkadot/util-crypto';22import Web3 from 'web3';23import usingApi, {submitTransactionAsync} from '../../substrate/substrate-api';24import {IKeyringPair} from '@polkadot/types/types';25import {expect} from 'chai';26import {getGenericResult, UNIQUE} from '../../util/helpers';27import * as solc from 'solc';28import config from '../../config';29import privateKey from '../../substrate/privateKey';30import contractHelpersAbi from './contractHelpersAbi.json';31import getBalance from '../../substrate/get-balance';32import waitNewBlocks from '../../substrate/wait-new-blocks';3334export const GAS_ARGS = {gas: 2500000};3536export enum SponsoringMode {37 Disabled = 0,38 Allowlisted = 1,39 Generous = 2,40}4142let web3Connected = false;43export async function usingWeb3<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {44 if (web3Connected) throw new Error('do not nest usingWeb3 calls');45 web3Connected = true;4647 const provider = new Web3.providers.WebsocketProvider(config.substrateUrl);48 const web3 = new Web3(provider);4950 try {51 return await cb(web3);52 } finally {53 // provider.disconnect(3000, 'normal disconnect');54 provider.connection.close();55 web3Connected = false;56 }57}5859function encodeIntBE(v: number): number[] {60 if (v >= 0xffffffff || v < 0) throw new Error('id overflow');61 return [62 v >> 24,63 (v >> 16) & 0xff,64 (v >> 8) & 0xff,65 v & 0xff,66 ];67}6869export function collectionIdToAddress(collection: number): string {70 const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,71 ...encodeIntBE(collection),72 ]);73 return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));74}7576export function tokenIdToAddress(collection: number, token: number): string {77 const buf = Buffer.from([0xf8, 0x23, 0x8c, 0xcf, 0xff, 0x8e, 0xd8, 0x87, 0x46, 0x3f, 0xd5, 0xe0,78 ...encodeIntBE(collection),79 ...encodeIntBE(token),80 ]);81 return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));82}8384export function createEthAccount(web3: Web3) {85 const account = web3.eth.accounts.create();86 web3.eth.accounts.wallet.add(account.privateKey);87 return account.address;88}8990export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3) {91 const alice = privateKey('//Alice');92 const account = createEthAccount(web3);93 await transferBalanceToEth(api, alice, account);9495 return account;96}9798export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {99 const tx = api.tx.balances.transfer(evmToAddress(target), amount);100 const events = await submitTransactionAsync(source, tx);101 const result = getGenericResult(events);102 expect(result.success).to.be.true;103}104105export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any, opts: { only?: boolean, skip?: boolean } = {}) {106 let i: any = it;107 if (opts.only) i = i.only;108 else if (opts.skip) i = i.skip;109 i(name, async () => {110 await usingApi(async api => {111 await usingWeb3(async web3 => {112 await cb({api, web3});113 });114 });115 });116}117itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {only: true});118itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {skip: true});119120export async function generateSubstrateEthPair(web3: Web3) {121 const account = web3.eth.accounts.create();122 evmToAddress(account.address);123}124125type NormalizedEvent = {126 address: string,127 event: string,128 args: { [key: string]: string }129};130131export function normalizeEvents(events: any): NormalizedEvent[] {132 const output = [];133 for (const key of Object.keys(events)) {134 if (key.match(/^[0-9]+$/)) {135 output.push(events[key]);136 } else if (Array.isArray(events[key])) {137 output.push(...events[key]);138 } else {139 output.push(events[key]);140 }141 }142 output.sort((a, b) => a.logIndex - b.logIndex);143 return output.map(({address, event, returnValues}) => {144 const args: { [key: string]: string } = {};145 for (const key of Object.keys(returnValues)) {146 if (!key.match(/^[0-9]+$/)) {147 args[key] = returnValues[key];148 }149 }150 return {151 address,152 event,153 args,154 };155 });156}157158export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {159 const out: any = [];160 contract.events.allEvents((_: any, event: any) => {161 out.push(event);162 });163 await action();164 return normalizeEvents(out);165}166167export function subToEthLowercase(eth: string): string {168 const bytes = addressToEvm(eth);169 return '0x' + Buffer.from(bytes).toString('hex');170}171172export function subToEth(eth: string): string {173 return Web3.utils.toChecksumAddress(subToEthLowercase(eth));174}175176export function compileContract(name: string, src: string) {177 const out = JSON.parse(solc.compile(JSON.stringify({178 language: 'Solidity',179 sources: {180 [`${name}.sol`]: {181 content: `182 // SPDX-License-Identifier: UNLICENSED183 pragma solidity ^0.8.6;184185 ${src}186 `,187 },188 },189 settings: {190 outputSelection: {191 '*': {192 '*': ['*'],193 },194 },195 },196 }))).contracts[`${name}.sol`][name];197198 return {199 abi: out.abi,200 object: '0x' + out.evm.bytecode.object,201 };202}203204export async function deployFlipper(web3: Web3, deployer: string) {205 const compiled = compileContract('Flipper', `206 contract Flipper {207 bool value = false;208 function flip() public {209 value = !value;210 }211 function getValue() public view returns (bool) {212 return value;213 }214 }215 `);216 const flipperContract = new web3.eth.Contract(compiled.abi, undefined, {217 data: compiled.object,218 from: deployer,219 ...GAS_ARGS,220 });221 const flipper = await flipperContract.deploy({data: compiled.object}).send({from: deployer});222223 return flipper;224}225226export async function deployCollector(web3: Web3, deployer: string) {227 const compiled = compileContract('Collector', `228 contract Collector {229 uint256 collected;230 fallback() external payable {231 giveMoney();232 }233 function giveMoney() public payable {234 collected += msg.value;235 }236 function getCollected() public view returns (uint256) {237 return collected;238 }239 function getUnaccounted() public view returns (uint256) {240 return address(this).balance - collected;241 }242243 function withdraw(address payable target) public {244 target.transfer(collected);245 collected = 0;246 }247 }248 `);249 const collectorContract = new web3.eth.Contract(compiled.abi, undefined, {250 data: compiled.object,251 from: deployer,252 ...GAS_ARGS,253 });254 const collector = await collectorContract.deploy({data: compiled.object}).send({from: deployer});255256 return collector;257}258259/** 260 * pallet evm_contract_helpers261 * @param web3 262 * @param caller - eth address263 * @returns 264 */265export function contractHelpers(web3: Web3, caller: string) {266 return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});267}268269/**270 * Execute ethereum method call using substrate account271 * @param to target contract272 * @param mkTx - closure, receiving `contract.methods`, and returning method call,273 * to be used as following (assuming `to` = erc20 contract):274 * `m => m.transfer(to, amount)`275 *276 * # Example277 * ```ts278 * executeEthTxOnSub(api, alice, erc20Contract, m => m.transfer(target, amount));279 * ```280 */281export async function executeEthTxOnSub(web3: Web3, api: ApiPromise, from: IKeyringPair, to: any, mkTx: (methods: any) => any, {value = 0}: {value?: bigint | number} = { }) {282 const tx = api.tx.evm.call(283 subToEth(from.address),284 to.options.address,285 mkTx(to.methods).encodeABI(),286 value,287 GAS_ARGS.gas,288 await web3.eth.getGasPrice(),289 null,290 null,291 [],292 );293 const events = await submitTransactionAsync(from, tx);294 expect(events.some(({event: {section, method}}) => section == 'evm' && method == 'Executed')).to.be.true;295}296297export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {298 return (await getBalance(api, [evmToAddress(address)]))[0];299}300301/**302 * Measure how much gas given closure consumes303 *304 * @param user which user balance will be checked305 */306export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {307 const before = await ethBalanceViaSub(api, user);308309 await call();310311 // In dev mode, the transaction might not finish processing in time312 await waitNewBlocks(api, 1);313 const after = await ethBalanceViaSub(api, user);314315 // Can't use .to.be.less, because chai doesn't supports bigint316 expect(after < before).to.be.true;317318 return before - after;319}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/);
+ });
+ });
+});