git.delta.rocks / unique-network / refs/commits / 6ec8a32fcc0b

difftreelog

refactor(preimage-execution) remove preimage length bound + fix benchmarks

Fahrrader2023-02-22parent: #1ae086c.patch.diff
in: master

7 files changed

modifiedMakefilediffbeforeafterboth
--- a/Makefile
+++ b/Makefile
@@ -137,9 +137,13 @@
 bench-app-promotion:
 	make _bench PALLET=app-promotion PALLET_DIR=app-promotion
 
+.PHONY: bench-maintenance
+bench-maintenance:
+	make _bench PALLET=maintenance
+
 .PHONY: bench
 # Disabled: bench-scheduler, bench-collator-selection, bench-identity
-bench: bench-common bench-evm-migration bench-unique bench-structure bench-fungible bench-refungible bench-nonfungible bench-configuration bench-foreign-assets
+bench: bench-common bench-evm-migration bench-unique bench-structure bench-fungible bench-refungible bench-nonfungible bench-configuration bench-foreign-assets bench-maintenance
 
 .PHONY: check
 check:
modifiedpallets/maintenance/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/maintenance/src/benchmarking.rs
+++ b/pallets/maintenance/src/benchmarking.rs
@@ -17,11 +17,10 @@
 use super::*;
 use crate::{Pallet as Maintenance, Config};
 
+use codec::Encode;
 use frame_benchmarking::benchmarks;
-use frame_system::{Call as RuntimeCall, RawOrigin};
+use frame_system::RawOrigin;
 use frame_support::{ensure, pallet_prelude::Weight, traits::StorePreimage};
-use codec::Encode;
-use sp_std::vec;
 
 benchmarks! {
 	enable {
@@ -38,9 +37,9 @@
 	}
 
 	execute_preimage {
-		let call_hash = RuntimeCall::<T>::set_storage { items: vec![] }.encode();
-		let hash = T::Preimages::note(call_hash.into())?;
-	}: _(RawOrigin::Root, hash, None, Weight::from_parts(100000000000, 100000000000))
+		let call = <T as Config>::RuntimeCall::from(frame_system::Call::<T>::remark { remark: 1u32.encode() });
+		let hash = T::Preimages::note(call.encode().into())?;
+	}: _(RawOrigin::Root, hash, Weight::from_parts(100000000000, 100000000000))
 	verify {
 	}
 }
modifiedpallets/maintenance/src/lib.rsdiffbeforeafterboth
--- a/pallets/maintenance/src/lib.rs
+++ b/pallets/maintenance/src/lib.rs
@@ -102,19 +102,22 @@
 			Ok(())
 		}
 
+		/// Execute a runtime call stored as a preimage.
+		///
+		/// `weight_bound` is the maximum weight that the caller is willing
+		/// to allow the extrinsic to be executed with.
 		#[pallet::call_index(2)]
 		#[pallet::weight(<T as Config>::WeightInfo::execute_preimage())]
 		pub fn execute_preimage(
 			origin: OriginFor<T>,
 			hash: H256,
-			preimage_length: Option<u32>,
 			weight_bound: Weight,
 		) -> DispatchResultWithPostInfo {
 			use codec::Decode;
 
 			ensure_root(origin)?;
 
-			let data = T::Preimages::fetch(&hash, preimage_length)?;
+			let data = T::Preimages::fetch(&hash, None)?;
 			weight_bound.set_proof_size(
 				weight_bound
 					.proof_size()
@@ -135,15 +138,9 @@
 			);
 
 			match call.dispatch(frame_system::RawOrigin::Root.into()) {
-				Ok(post_info) => Ok(PostDispatchInfo {
-					actual_weight: post_info.actual_weight,
-					pays_fee: Pays::No,
-				}),
+				Ok(_) => Ok(Pays::No.into()),
 				Err(error_and_info) => Err(DispatchErrorWithPostInfo {
-					post_info: PostDispatchInfo {
-						actual_weight: error_and_info.post_info.actual_weight,
-						pays_fee: Pays::No,
-					},
+					post_info: Pays::No.into(),
 					error: error_and_info.error,
 				}),
 			}
modifiedpallets/maintenance/src/weights.rsdiffbeforeafterboth
--- a/pallets/maintenance/src/weights.rs
+++ b/pallets/maintenance/src/weights.rs
@@ -3,7 +3,7 @@
 //! Autogenerated weights for pallet_maintenance
 //!
 //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
-//! DATE: 2022-11-01, STEPS: `50`, REPEAT: 80, LOW RANGE: `[]`, HIGH RANGE: `[]`
+//! DATE: 2023-02-22, STEPS: `50`, REPEAT: 80, LOW RANGE: `[]`, HIGH RANGE: `[]`
 //! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: None, DB CACHE: 1024
 
 // Executed Command:
@@ -26,6 +26,7 @@
 #![cfg_attr(rustfmt, rustfmt_skip)]
 #![allow(unused_parens)]
 #![allow(unused_imports)]
+#![allow(missing_docs)]
 #![allow(clippy::unnecessary_cast)]
 
 use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
@@ -43,19 +44,19 @@
 impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
 	// Storage: Maintenance Enabled (r:0 w:1)
 	fn enable() -> Weight {
-		Weight::from_ref_time(7_367_000)
-			.saturating_add(T::DbWeight::get().writes(1))
+		Weight::from_ref_time(10_860_000 as u64)
+			.saturating_add(T::DbWeight::get().writes(1 as u64))
 	}
 	// Storage: Maintenance Enabled (r:0 w:1)
 	fn disable() -> Weight {
-		Weight::from_ref_time(7_273_000)
-			.saturating_add(T::DbWeight::get().writes(1))
+		Weight::from_ref_time(10_871_000 as u64)
+			.saturating_add(T::DbWeight::get().writes(1 as u64))
 	}
-	// Storage: 
+	// Storage: Preimage StatusFor (r:1 w:0)
+	// Storage: Preimage PreimageFor (r:1 w:0)
 	fn execute_preimage() -> Weight {
-		Weight::from_ref_time(7_273_000)
-			.saturating_add(T::DbWeight::get().reads(2))
-			.saturating_add(T::DbWeight::get().writes(1))
+		Weight::from_ref_time(10_068_000 as u64)
+			.saturating_add(T::DbWeight::get().reads(2 as u64))
 	}
 }
 
@@ -63,18 +64,18 @@
 impl WeightInfo for () {
 	// Storage: Maintenance Enabled (r:0 w:1)
 	fn enable() -> Weight {
-		Weight::from_ref_time(7_367_000)
-			.saturating_add(RocksDbWeight::get().writes(1))
+		Weight::from_ref_time(10_860_000 as u64)
+			.saturating_add(RocksDbWeight::get().writes(1 as u64))
 	}
 	// Storage: Maintenance Enabled (r:0 w:1)
 	fn disable() -> Weight {
-		Weight::from_ref_time(7_273_000)
-			.saturating_add(RocksDbWeight::get().writes(1))
+		Weight::from_ref_time(10_871_000 as u64)
+			.saturating_add(RocksDbWeight::get().writes(1 as u64))
 	}
-	// Storage: 
+	// Storage: Preimage StatusFor (r:1 w:0)
+	// Storage: Preimage PreimageFor (r:1 w:0)
 	fn execute_preimage() -> Weight {
-		Weight::from_ref_time(7_273_000)
-			.saturating_add(RocksDbWeight::get().reads(2))
-			.saturating_add(RocksDbWeight::get().writes(1))
+		Weight::from_ref_time(10_068_000 as u64)
+			.saturating_add(RocksDbWeight::get().reads(2 as u64))
 	}
 }
modifiedruntime/common/maintenance.rsdiffbeforeafterboth
--- a/runtime/common/maintenance.rs
+++ b/runtime/common/maintenance.rs
@@ -86,9 +86,6 @@
 				| RuntimeCall::Session(_)
 				| RuntimeCall::Identity(_) => Err(TransactionValidityError::Invalid(InvalidTransaction::Call)),
 
-				#[cfg(feature = "preimage")]
-				RuntimeCall::Preimage(_) => Err(TransactionValidityError::Invalid(InvalidTransaction::Call)),
-
 				#[cfg(feature = "pallet-test-utils")]
 				RuntimeCall::TestUtils(_) => Err(TransactionValidityError::Invalid(InvalidTransaction::Call)),
 
modifiedruntime/common/runtime_apis.rsdiffbeforeafterboth
--- a/runtime/common/runtime_apis.rs
+++ b/runtime/common/runtime_apis.rs
@@ -568,6 +568,7 @@
                     #[cfg(feature = "foreign-assets")]
                     list_benchmark!(list, extra, pallet_foreign_assets, ForeignAssets);
 
+                    list_benchmark!(list, extra, pallet_maintenance, Maintenance);
 
                     // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);
 
@@ -632,6 +633,8 @@
                     #[cfg(feature = "foreign-assets")]
                     add_benchmark!(params, batches, pallet_foreign_assets, ForeignAssets);
 
+                    add_benchmark!(params, batches, pallet_maintenance, Maintenance);
+
                     // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);
 
                     if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }
modifiedtests/src/maintenance.seqtest.tsdiffbeforeafterboth
before · tests/src/maintenance.seqtest.ts
1// 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/>.1617import {IKeyringPair} from '@polkadot/types/types';18import {ApiPromise} from '@polkadot/api';19import {expect, itSched, itSub, Pallets, requirePalletsOrSkip, usingPlaygrounds} from './util';20import {itEth} from './eth/util';21import {UniqueHelper} from './util/playgrounds/unique';2223async function maintenanceEnabled(api: ApiPromise): Promise<boolean> {24  return (await api.query.maintenance.enabled()).toJSON() as boolean;25}2627describe('Integration Test: Maintenance Functionality', () => {28  let superuser: IKeyringPair;29  let donor: IKeyringPair;30  let bob: IKeyringPair;3132  before(async function() {33    await usingPlaygrounds(async (helper, privateKey) => {34      requirePalletsOrSkip(this, helper, [Pallets.Maintenance]);35      superuser = await privateKey('//Alice');36      donor = await privateKey({filename: __filename});37      [bob] = await helper.arrange.createAccounts([10000n], donor);3839    });40  });4142  describe('Maintenance Mode', () => {43    before(async function() {44      await usingPlaygrounds(async (helper) => {45        if (await maintenanceEnabled(helper.getApi())) {46          console.warn('\tMaintenance mode was left enabled BEFORE the test suite! Disabling it now.');47          await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', [])).to.be.fulfilled;48        }49      });50    });5152    itSub('Allows superuser to enable and disable maintenance mode - and disallows anyone else', async ({helper}) => {53      // Make sure non-sudo can't enable maintenance mode54      await expect(helper.executeExtrinsic(superuser, 'api.tx.maintenance.enable', []), 'on commoner enabling MM')55        .to.be.rejectedWith(/BadOrigin/);5657      // Set maintenance mode58      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);59      expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;6061      // Make sure non-sudo can't disable maintenance mode62      await expect(helper.executeExtrinsic(bob, 'api.tx.maintenance.disable', []), 'on commoner disabling MM')63        .to.be.rejectedWith(/BadOrigin/);6465      // Disable maintenance mode66      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);67      expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;68    });6970    itSub('MM blocks unique pallet calls', async ({helper}) => {71      // Can create an NFT collection before enabling the MM72      const nftCollection = await helper.nft.mintCollection(bob, {73        tokenPropertyPermissions: [{key: 'test', permission: {74          collectionAdmin: true,75          tokenOwner: true,76          mutable: true,77        }}],78      });7980      // Can mint an NFT before enabling the MM81      const nft = await nftCollection.mintToken(bob);8283      // Can create an FT collection before enabling the MM84      const ftCollection = await helper.ft.mintCollection(superuser);8586      // Can mint an FT before enabling the MM87      await expect(ftCollection.mint(superuser)).to.be.fulfilled;8889      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);90      expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;9192      // Unable to create a collection when the MM is enabled93      await expect(helper.nft.mintCollection(superuser), 'cudo forbidden stuff')94        .to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);9596      // Unable to set token properties when the MM is enabled97      await expect(nft.setProperties(98        bob,99        [{key: 'test', value: 'test-val'}],100      )).to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);101102      // Unable to mint an NFT when the MM is enabled103      await expect(nftCollection.mintToken(superuser))104        .to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);105106      // Unable to mint an FT when the MM is enabled107      await expect(ftCollection.mint(superuser))108        .to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);109110      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);111      expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;112113      // Can create a collection after disabling the MM114      await expect(helper.nft.mintCollection(bob), 'MM is disabled, the collection should be created').to.be.fulfilled;115116      // Can set token properties after disabling the MM117      await nft.setProperties(bob, [{key: 'test', value: 'test-val'}]);118119      // Can mint an NFT after disabling the MM120      await nftCollection.mintToken(bob);121122      // Can mint an FT after disabling the MM123      await ftCollection.mint(superuser);124    });125126    itSub.ifWithPallets('MM blocks unique pallet calls (Re-Fungible)', [Pallets.ReFungible], async ({helper}) => {127      // Can create an RFT collection before enabling the MM128      const rftCollection = await helper.rft.mintCollection(superuser);129130      // Can mint an RFT before enabling the MM131      await expect(rftCollection.mintToken(superuser)).to.be.fulfilled;132133      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);134      expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;135136      // Unable to mint an RFT when the MM is enabled137      await expect(rftCollection.mintToken(superuser))138        .to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);139140      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);141      expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;142143      // Can mint an RFT after disabling the MM144      await rftCollection.mintToken(superuser);145    });146147    itSub('MM allows native token transfers and RPC calls', async ({helper}) => {148      // We can use RPC before the MM is enabled149      const totalCount = await helper.collection.getTotalCount();150151      // We can transfer funds before the MM is enabled152      await expect(helper.balance.transferToSubstrate(superuser, bob.address, 2n)).to.be.fulfilled;153154      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);155      expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;156157      // RPCs work while in maintenance158      expect(await helper.collection.getTotalCount()).to.be.deep.equal(totalCount);159160      // We still able to transfer funds161      await expect(helper.balance.transferToSubstrate(bob, superuser.address, 1n)).to.be.fulfilled;162163      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);164      expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;165166      // RPCs work after maintenance167      expect(await helper.collection.getTotalCount()).to.be.deep.equal(totalCount);168169      // Transfers work after maintenance170      await expect(helper.balance.transferToSubstrate(bob, superuser.address, 1n)).to.be.fulfilled;171    });172173    itSched.ifWithPallets('MM blocks scheduled calls and the scheduler itself', [Pallets.Scheduler], async (scheduleKind, {helper}) => {174      const collection = await helper.nft.mintCollection(bob);175176      const nftBeforeMM = await collection.mintToken(bob);177      const nftDuringMM = await collection.mintToken(bob);178      const nftAfterMM = await collection.mintToken(bob);179180      const [181        scheduledIdBeforeMM,182        scheduledIdDuringMM,183        scheduledIdBunkerThroughMM,184        scheduledIdAttemptDuringMM,185        scheduledIdAfterMM,186      ] = scheduleKind == 'named'187        ? helper.arrange.makeScheduledIds(5)188        : new Array(5);189190      const blocksToWait = 6;191192      // Scheduling works before the maintenance193      await nftBeforeMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdBeforeMM})194        .transfer(bob, {Substrate: superuser.address});195196      await helper.wait.newBlocks(blocksToWait + 1);197      expect(await nftBeforeMM.getOwner()).to.be.deep.equal({Substrate: superuser.address});198199      // Schedule a transaction that should occur *during* the maintenance200      await nftDuringMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdDuringMM})201        .transfer(bob, {Substrate: superuser.address});202203      // Schedule a transaction that should occur *after* the maintenance204      await nftDuringMM.scheduleAfter(blocksToWait * 2, {scheduledId: scheduledIdBunkerThroughMM})205        .transfer(bob, {Substrate: superuser.address});206207      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);208      expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;209210      await helper.wait.newBlocks(blocksToWait + 1);211      // The owner should NOT change since the scheduled transaction should be rejected212      expect(await nftDuringMM.getOwner()).to.be.deep.equal({Substrate: bob.address});213214      // Any attempts to schedule a tx during the MM should be rejected215      await expect(nftDuringMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdAttemptDuringMM})216        .transfer(bob, {Substrate: superuser.address}))217        .to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);218219      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);220      expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;221222      // Scheduling works after the maintenance223      await nftAfterMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdAfterMM})224        .transfer(bob, {Substrate: superuser.address});225226      await helper.wait.newBlocks(blocksToWait + 1);227228      expect(await nftAfterMM.getOwner()).to.be.deep.equal({Substrate: superuser.address});229      // The owner of the token scheduled for transaction *before* maintenance should now change *after* maintenance230      expect(await nftDuringMM.getOwner()).to.be.deep.equal({Substrate: superuser.address});231    });232233    itEth('Disallows Ethereum transactions to execute while in maintenance', async ({helper}) => {234      const owner = await helper.eth.createAccountWithBalance(donor);235      const receiver = helper.eth.createAccount();236237      const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'A', 'B', 'C', '');238239      // Set maintenance mode240      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);241      expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;242243      const contract = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);244      const tokenId = await contract.methods.nextTokenId().call();245      expect(tokenId).to.be.equal('1');246247      await expect(contract.methods.mintWithTokenURI(receiver, 'Test URI').send())248        .to.be.rejectedWith(/Returned error: unknown error/);249250      await expect(contract.methods.ownerOf(tokenId).call()).rejectedWith(/token not found/);251252      // Disable maintenance mode253      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);254      expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;255    });256257    itSub('Allows to enable and disable MM repeatedly', async ({helper}) => {258      // Set maintenance mode259      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);260      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);261      expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;262263      // Disable maintenance mode264      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);265      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);266      expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;267    });268269    afterEach(async () => {270      await usingPlaygrounds(async helper => {271        if (helper.fetchMissingPalletNames([Pallets.Maintenance]).length != 0) return;272        if (await maintenanceEnabled(helper.getApi())) {273          console.warn('\tMaintenance mode was left enabled AFTER a test has finished! Be careful. Disabling it now.');274          await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);275        }276        expect(await maintenanceEnabled(helper.getApi()), 'Disastrous! Exited the test suite with maintenance mode on.').to.be.false;277      });278    });279  });280281  describe('Preimage Execution', () => {282    let preimageHash: string;283284    async function notePreimage(helper: UniqueHelper, preimage: any): Promise<string> {285      const result = await helper.preimage.notePreimage(bob, preimage);286      const events = result.result.events.filter(x => x.event.method === 'Noted' && x.event.section === 'preimage');287      const preimageHash = events[0].event.data[0].toHuman();288      return preimageHash;289    }290291    before(async function() {292      await usingPlaygrounds(async (helper) => {293        requirePalletsOrSkip(this, helper, [Pallets.Preimage, Pallets.Maintenance]);294295        // create a preimage to be operated with in the tests296        const randomAccounts = await helper.arrange.createCrowd(10, 0n, superuser);297        const randomIdentities = randomAccounts.map((acc, i) => [298          acc.address, {299            deposit: 0n,300            judgements: [],301            info: {302              display: {303                raw: `Random Account #${i}`,304              },305            },306          },307        ]);308        const preimage = helper.constructApiCall('api.tx.identity.forceInsertIdentities', [randomIdentities]).method.toHex();309        preimageHash = await notePreimage(helper, preimage);310      });311    });312313    itSub('Successfully executes call in a preimage', async ({helper}) => {314      const result = await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [315        preimageHash, null, {refTime: 10000000000, proofSize: 10000000000},316      ])).to.be.fulfilled;317318      // preimage is executed, and an appropriate event is present319      const events = result.result.events.filter((x: any) => x.event.method === 'IdentitiesInserted' && x.event.section === 'identity');320      expect(events.length).to.be.equal(1);321322      // the preimage goes back to being unrequested323      expect(await helper.preimage.getPreimageInfo(preimageHash)).to.have.property('unrequested');324    });325326    itSub('Does not allow execution of a preimage that would fail', async ({helper}) => {327      const [zeroAccount] = await helper.arrange.createAccounts([0n], superuser);328329      const preimage = helper.constructApiCall('api.tx.balances.forceTransfer', [330        {Id: zeroAccount.address}, {Id: superuser.address}, 1000n,331      ]).method.toHex();332      const preimageHash = await notePreimage(helper, preimage);333334      await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [335        preimageHash, null, {refTime: 100000000000, proofSize: 100000000000},336      ])).to.be.rejectedWith(/balances\.InsufficientBalance/);337    });338339    itSub('Does not allow preimage execution with non-root', async ({helper}) => {340      await expect(helper.executeExtrinsic(bob, 'api.tx.maintenance.executePreimage', [341        preimageHash, null, {refTime: 100000000000, proofSize: 100000000000},342      ])).to.be.rejectedWith(/BadOrigin/);343    });344345    itSub('Does not allow execution of non-existent preimages', async ({helper}) => {346      await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [347        '0x1010101010101010101010101010101010101010101010101010101010101010', null, {refTime: 100000000000, proofSize: 100000000000},348      ])).to.be.rejectedWith(/Unavailable/);349    });350351    itSub('Does not allow preimage execution with less than minimum weights', async ({helper}) => {352      await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [353        preimageHash, null, {refTime: 1000, proofSize: 1000},354      ])).to.be.rejectedWith(/Exhausted/);355    });356357    after(async function() {358      await usingPlaygrounds(async (helper) => {359        if (helper.fetchMissingPalletNames([Pallets.Preimage, Pallets.Maintenance]).length != 0) return;360361        await helper.preimage.unnotePreimage(bob, preimageHash);362      });363    });364  });365});
after · tests/src/maintenance.seqtest.ts
1// 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/>.1617import {IKeyringPair} from '@polkadot/types/types';18import {ApiPromise} from '@polkadot/api';19import {expect, itSched, itSub, Pallets, requirePalletsOrSkip, usingPlaygrounds} from './util';20import {itEth} from './eth/util';21import {UniqueHelper} from './util/playgrounds/unique';2223async function maintenanceEnabled(api: ApiPromise): Promise<boolean> {24  return (await api.query.maintenance.enabled()).toJSON() as boolean;25}2627describe('Integration Test: Maintenance Functionality', () => {28  let superuser: IKeyringPair;29  let donor: IKeyringPair;30  let bob: IKeyringPair;3132  before(async function() {33    await usingPlaygrounds(async (helper, privateKey) => {34      requirePalletsOrSkip(this, helper, [Pallets.Maintenance]);35      superuser = await privateKey('//Alice');36      donor = await privateKey({filename: __filename});37      [bob] = await helper.arrange.createAccounts([10000n], donor);3839    });40  });4142  describe('Maintenance Mode', () => {43    before(async function() {44      await usingPlaygrounds(async (helper) => {45        if (await maintenanceEnabled(helper.getApi())) {46          console.warn('\tMaintenance mode was left enabled BEFORE the test suite! Disabling it now.');47          await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', [])).to.be.fulfilled;48        }49      });50    });5152    itSub('Allows superuser to enable and disable maintenance mode - and disallows anyone else', async ({helper}) => {53      // Make sure non-sudo can't enable maintenance mode54      await expect(helper.executeExtrinsic(superuser, 'api.tx.maintenance.enable', []), 'on commoner enabling MM')55        .to.be.rejectedWith(/BadOrigin/);5657      // Set maintenance mode58      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);59      expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;6061      // Make sure non-sudo can't disable maintenance mode62      await expect(helper.executeExtrinsic(bob, 'api.tx.maintenance.disable', []), 'on commoner disabling MM')63        .to.be.rejectedWith(/BadOrigin/);6465      // Disable maintenance mode66      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);67      expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;68    });6970    itSub('MM blocks unique pallet calls', async ({helper}) => {71      // Can create an NFT collection before enabling the MM72      const nftCollection = await helper.nft.mintCollection(bob, {73        tokenPropertyPermissions: [{key: 'test', permission: {74          collectionAdmin: true,75          tokenOwner: true,76          mutable: true,77        }}],78      });7980      // Can mint an NFT before enabling the MM81      const nft = await nftCollection.mintToken(bob);8283      // Can create an FT collection before enabling the MM84      const ftCollection = await helper.ft.mintCollection(superuser);8586      // Can mint an FT before enabling the MM87      await expect(ftCollection.mint(superuser)).to.be.fulfilled;8889      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);90      expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;9192      // Unable to create a collection when the MM is enabled93      await expect(helper.nft.mintCollection(superuser), 'cudo forbidden stuff')94        .to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);9596      // Unable to set token properties when the MM is enabled97      await expect(nft.setProperties(98        bob,99        [{key: 'test', value: 'test-val'}],100      )).to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);101102      // Unable to mint an NFT when the MM is enabled103      await expect(nftCollection.mintToken(superuser))104        .to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);105106      // Unable to mint an FT when the MM is enabled107      await expect(ftCollection.mint(superuser))108        .to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);109110      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);111      expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;112113      // Can create a collection after disabling the MM114      await expect(helper.nft.mintCollection(bob), 'MM is disabled, the collection should be created').to.be.fulfilled;115116      // Can set token properties after disabling the MM117      await nft.setProperties(bob, [{key: 'test', value: 'test-val'}]);118119      // Can mint an NFT after disabling the MM120      await nftCollection.mintToken(bob);121122      // Can mint an FT after disabling the MM123      await ftCollection.mint(superuser);124    });125126    itSub.ifWithPallets('MM blocks unique pallet calls (Re-Fungible)', [Pallets.ReFungible], async ({helper}) => {127      // Can create an RFT collection before enabling the MM128      const rftCollection = await helper.rft.mintCollection(superuser);129130      // Can mint an RFT before enabling the MM131      await expect(rftCollection.mintToken(superuser)).to.be.fulfilled;132133      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);134      expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;135136      // Unable to mint an RFT when the MM is enabled137      await expect(rftCollection.mintToken(superuser))138        .to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);139140      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);141      expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;142143      // Can mint an RFT after disabling the MM144      await rftCollection.mintToken(superuser);145    });146147    itSub('MM allows native token transfers and RPC calls', async ({helper}) => {148      // We can use RPC before the MM is enabled149      const totalCount = await helper.collection.getTotalCount();150151      // We can transfer funds before the MM is enabled152      await expect(helper.balance.transferToSubstrate(superuser, bob.address, 2n)).to.be.fulfilled;153154      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);155      expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;156157      // RPCs work while in maintenance158      expect(await helper.collection.getTotalCount()).to.be.deep.equal(totalCount);159160      // We still able to transfer funds161      await expect(helper.balance.transferToSubstrate(bob, superuser.address, 1n)).to.be.fulfilled;162163      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);164      expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;165166      // RPCs work after maintenance167      expect(await helper.collection.getTotalCount()).to.be.deep.equal(totalCount);168169      // Transfers work after maintenance170      await expect(helper.balance.transferToSubstrate(bob, superuser.address, 1n)).to.be.fulfilled;171    });172173    itSched.ifWithPallets('MM blocks scheduled calls and the scheduler itself', [Pallets.Scheduler], async (scheduleKind, {helper}) => {174      const collection = await helper.nft.mintCollection(bob);175176      const nftBeforeMM = await collection.mintToken(bob);177      const nftDuringMM = await collection.mintToken(bob);178      const nftAfterMM = await collection.mintToken(bob);179180      const [181        scheduledIdBeforeMM,182        scheduledIdDuringMM,183        scheduledIdBunkerThroughMM,184        scheduledIdAttemptDuringMM,185        scheduledIdAfterMM,186      ] = scheduleKind == 'named'187        ? helper.arrange.makeScheduledIds(5)188        : new Array(5);189190      const blocksToWait = 6;191192      // Scheduling works before the maintenance193      await nftBeforeMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdBeforeMM})194        .transfer(bob, {Substrate: superuser.address});195196      await helper.wait.newBlocks(blocksToWait + 1);197      expect(await nftBeforeMM.getOwner()).to.be.deep.equal({Substrate: superuser.address});198199      // Schedule a transaction that should occur *during* the maintenance200      await nftDuringMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdDuringMM})201        .transfer(bob, {Substrate: superuser.address});202203      // Schedule a transaction that should occur *after* the maintenance204      await nftDuringMM.scheduleAfter(blocksToWait * 2, {scheduledId: scheduledIdBunkerThroughMM})205        .transfer(bob, {Substrate: superuser.address});206207      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);208      expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;209210      await helper.wait.newBlocks(blocksToWait + 1);211      // The owner should NOT change since the scheduled transaction should be rejected212      expect(await nftDuringMM.getOwner()).to.be.deep.equal({Substrate: bob.address});213214      // Any attempts to schedule a tx during the MM should be rejected215      await expect(nftDuringMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdAttemptDuringMM})216        .transfer(bob, {Substrate: superuser.address}))217        .to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);218219      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);220      expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;221222      // Scheduling works after the maintenance223      await nftAfterMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdAfterMM})224        .transfer(bob, {Substrate: superuser.address});225226      await helper.wait.newBlocks(blocksToWait + 1);227228      expect(await nftAfterMM.getOwner()).to.be.deep.equal({Substrate: superuser.address});229      // The owner of the token scheduled for transaction *before* maintenance should now change *after* maintenance230      expect(await nftDuringMM.getOwner()).to.be.deep.equal({Substrate: superuser.address});231    });232233    itEth('Disallows Ethereum transactions to execute while in maintenance', async ({helper}) => {234      const owner = await helper.eth.createAccountWithBalance(donor);235      const receiver = helper.eth.createAccount();236237      const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'A', 'B', 'C', '');238239      // Set maintenance mode240      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);241      expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;242243      const contract = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);244      const tokenId = await contract.methods.nextTokenId().call();245      expect(tokenId).to.be.equal('1');246247      await expect(contract.methods.mintWithTokenURI(receiver, 'Test URI').send())248        .to.be.rejectedWith(/Returned error: unknown error/);249250      await expect(contract.methods.ownerOf(tokenId).call()).rejectedWith(/token not found/);251252      // Disable maintenance mode253      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);254      expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;255    });256257    itSub('Allows to enable and disable MM repeatedly', async ({helper}) => {258      // Set maintenance mode259      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);260      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);261      expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;262263      // Disable maintenance mode264      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);265      await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);266      expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;267    });268269    afterEach(async () => {270      await usingPlaygrounds(async helper => {271        if (helper.fetchMissingPalletNames([Pallets.Maintenance]).length != 0) return;272        if (await maintenanceEnabled(helper.getApi())) {273          console.warn('\tMaintenance mode was left enabled AFTER a test has finished! Be careful. Disabling it now.');274          await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);275        }276        expect(await maintenanceEnabled(helper.getApi()), 'Disastrous! Exited the test suite with maintenance mode on.').to.be.false;277      });278    });279  });280281  describe('Preimage Execution', () => {282    const preimageHashes: string[] = [];283284    async function notePreimage(helper: UniqueHelper, preimage: any): Promise<string> {285      const result = await helper.preimage.notePreimage(bob, preimage);286      const events = result.result.events.filter(x => x.event.method === 'Noted' && x.event.section === 'preimage');287      const preimageHash = events[0].event.data[0].toHuman();288      return preimageHash;289    }290291    before(async function() {292      await usingPlaygrounds(async (helper) => {293        requirePalletsOrSkip(this, helper, [Pallets.Preimage, Pallets.Maintenance]);294295        // create a preimage to be operated with in the tests296        const randomAccounts = await helper.arrange.createCrowd(10, 0n, superuser);297        const randomIdentities = randomAccounts.map((acc, i) => [298          acc.address, {299            deposit: 0n,300            judgements: [],301            info: {302              display: {303                raw: `Random Account #${i}`,304              },305            },306          },307        ]);308        const preimage = helper.constructApiCall('api.tx.identity.forceInsertIdentities', [randomIdentities]).method.toHex();309        preimageHashes.push(await notePreimage(helper, preimage));310      });311    });312313    itSub('Successfully executes call in a preimage', async ({helper}) => {314      const result = await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [315        preimageHashes[0], {refTime: 10000000000, proofSize: 10000000000},316      ])).to.be.fulfilled;317318      // preimage is executed, and an appropriate event is present319      const events = result.result.events.filter((x: any) => x.event.method === 'IdentitiesInserted' && x.event.section === 'identity');320      expect(events.length).to.be.equal(1);321322      // the preimage goes back to being unrequested323      expect(await helper.preimage.getPreimageInfo(preimageHashes[0])).to.have.property('unrequested');324    });325326    itSub('Does not allow execution of a preimage that would fail', async ({helper}) => {327      const [zeroAccount] = await helper.arrange.createAccounts([0n], superuser);328329      const preimage = helper.constructApiCall('api.tx.balances.forceTransfer', [330        {Id: zeroAccount.address}, {Id: superuser.address}, 1000n,331      ]).method.toHex();332      const preimageHash = await notePreimage(helper, preimage);333      preimageHashes.push(preimageHash);334335      await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [336        preimageHash, {refTime: 100000000000, proofSize: 100000000000},337      ])).to.be.rejectedWith(/balances\.InsufficientBalance/);338    });339340    itSub('Does not allow preimage execution with non-root', async ({helper}) => {341      await expect(helper.executeExtrinsic(bob, 'api.tx.maintenance.executePreimage', [342        preimageHashes[0], {refTime: 100000000000, proofSize: 100000000000},343      ])).to.be.rejectedWith(/BadOrigin/);344    });345346    itSub('Does not allow execution of non-existent preimages', async ({helper}) => {347      await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [348        '0x1010101010101010101010101010101010101010101010101010101010101010', {refTime: 100000000000, proofSize: 100000000000},349      ])).to.be.rejectedWith(/Unavailable/);350    });351352    itSub('Does not allow preimage execution with less than minimum weights', async ({helper}) => {353      await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [354        preimageHashes[0], {refTime: 1000, proofSize: 1000},355      ])).to.be.rejectedWith(/Exhausted/);356    });357358    after(async function() {359      await usingPlaygrounds(async (helper) => {360        if (helper.fetchMissingPalletNames([Pallets.Preimage, Pallets.Maintenance]).length != 0) return;361362        for (const hash of preimageHashes) {363          await helper.preimage.unnotePreimage(bob, hash);364        }365      });366    });367  });368});