1234567891011121314151617import {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 {main as correctState} from './migrations/correctStateAfterMaintenance';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({url: import.meta.url});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 54 await expect(helper.executeExtrinsic(superuser, 'api.tx.maintenance.enable', []), 'on commoner enabling MM')55 .to.be.rejectedWith(/BadOrigin/);5657 58 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 62 await expect(helper.executeExtrinsic(bob, 'api.tx.maintenance.disable', []), 'on commoner disabling MM')63 .to.be.rejectedWith(/BadOrigin/);6465 66 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 72 const nftCollection = await helper.nft.mintCollection(bob, {73 tokenPropertyPermissions: [{74 key: 'test', permission: {75 collectionAdmin: true,76 tokenOwner: true,77 mutable: true,78 },79 }],80 });8182 83 const nft = await nftCollection.mintToken(bob);8485 86 const ftCollection = await helper.ft.mintCollection(superuser);8788 89 await expect(ftCollection.mint(superuser)).to.be.fulfilled;9091 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);92 expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;9394 95 await expect(helper.nft.mintCollection(superuser), 'cudo forbidden stuff')96 .to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);9798 99 await expect(nft.setProperties(100 bob,101 [{key: 'test', value: 'test-val'}],102 )).to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);103104 105 await expect(nftCollection.mintToken(superuser))106 .to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);107108 109 await expect(ftCollection.mint(superuser))110 .to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);111112 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);113 expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;114115 116 await expect(helper.nft.mintCollection(bob), 'MM is disabled, the collection should be created').to.be.fulfilled;117118 119 await nft.setProperties(bob, [{key: 'test', value: 'test-val'}]);120121 122 await nftCollection.mintToken(bob);123124 125 await ftCollection.mint(superuser);126 });127128 itSub.ifWithPallets('MM blocks unique pallet calls (Re-Fungible)', [Pallets.ReFungible], async ({helper}) => {129 130 const rftCollection = await helper.rft.mintCollection(superuser);131132 133 await expect(rftCollection.mintToken(superuser)).to.be.fulfilled;134135 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);136 expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;137138 139 await expect(rftCollection.mintToken(superuser))140 .to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);141142 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);143 expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;144145 146 await rftCollection.mintToken(superuser);147 });148149 itSub('MM allows native token transfers and RPC calls', async ({helper}) => {150 151 const totalCount = await helper.collection.getTotalCount();152153 154 await expect(helper.balance.transferToSubstrate(superuser, bob.address, 2n)).to.be.fulfilled;155156 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);157 expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;158159 160 expect(await helper.collection.getTotalCount()).to.be.deep.equal(totalCount);161162 163 await expect(helper.balance.transferToSubstrate(bob, superuser.address, 1n)).to.be.fulfilled;164165 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);166 expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;167168 169 expect(await helper.collection.getTotalCount()).to.be.deep.equal(totalCount);170171 172 await expect(helper.balance.transferToSubstrate(bob, superuser.address, 1n)).to.be.fulfilled;173 });174175 itSched.ifWithPallets('MM blocks scheduled calls and the scheduler itself', [Pallets.UniqueScheduler], async (scheduleKind, {helper}) => {176 const collection = await helper.nft.mintCollection(bob);177178 const nftBeforeMM = await collection.mintToken(bob);179 const nftDuringMM = await collection.mintToken(bob);180 const nftAfterMM = await collection.mintToken(bob);181182 const [183 scheduledIdBeforeMM,184 scheduledIdDuringMM,185 scheduledIdBunkerThroughMM,186 scheduledIdAttemptDuringMM,187 scheduledIdAfterMM,188 ] = scheduleKind == 'named'189 ? helper.arrange.makeScheduledIds(5)190 : new Array(5);191192 const blocksToWait = 6;193194 195 await nftBeforeMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdBeforeMM})196 .transfer(bob, {Substrate: superuser.address});197198 await helper.wait.newBlocks(blocksToWait + 1);199 expect(await nftBeforeMM.getOwner()).to.be.deep.equal({Substrate: superuser.address});200201 202 await nftDuringMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdDuringMM})203 .transfer(bob, {Substrate: superuser.address});204205 206 await nftDuringMM.scheduleAfter(blocksToWait * 2, {scheduledId: scheduledIdBunkerThroughMM})207 .transfer(bob, {Substrate: superuser.address});208209 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);210 expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;211212 await helper.wait.newBlocks(blocksToWait + 1);213 214 expect(await nftDuringMM.getOwner()).to.be.deep.equal({Substrate: bob.address});215216 217 await expect(nftDuringMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdAttemptDuringMM})218 .transfer(bob, {Substrate: superuser.address}))219 .to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);220221 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);222 expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;223224 225 await nftAfterMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdAfterMM})226 .transfer(bob, {Substrate: superuser.address});227228 await helper.wait.newBlocks(blocksToWait + 1);229230 expect(await nftAfterMM.getOwner()).to.be.deep.equal({Substrate: superuser.address});231 232 expect(await nftDuringMM.getOwner()).to.be.deep.equal({Substrate: superuser.address});233 });234235 itEth('Disallows Ethereum transactions to execute while in maintenance', async ({helper}) => {236 const owner = await helper.eth.createAccountWithBalance(donor);237 const receiver = helper.eth.createAccount();238239 const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'A', 'B', 'C', '');240241 242 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);243 expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;244245 const contract = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);246 const tokenId = await contract.methods.nextTokenId().call();247 expect(tokenId).to.be.equal('1');248249 await expect(contract.methods.mintWithTokenURI(receiver, 'Test URI').send())250 .to.be.rejectedWith(/Returned error: unknown error/);251252 await expect(contract.methods.ownerOf(tokenId).call()).rejectedWith(/token not found/);253254 255 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);256 expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;257 });258259 itSub('Allows to enable and disable MM repeatedly', async ({helper}) => {260 261 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);262 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);263 expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;264265 266 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);267 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);268 expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;269 });270271 afterEach(async () => {272 await usingPlaygrounds(async helper => {273 if(helper.fetchMissingPalletNames([Pallets.Maintenance]).length != 0) return;274 if(await maintenanceEnabled(helper.getApi())) {275 console.warn('\tMaintenance mode was left enabled AFTER a test has finished! Be careful. Disabling it now.');276 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);277 }278 expect(await maintenanceEnabled(helper.getApi()), 'Disastrous! Exited the test suite with maintenance mode on.').to.be.false;279 });280 });281 });282283 describe('Preimage Execution', () => {284 const preimageHashes: string[] = [];285286 before(async function() {287 await usingPlaygrounds(async (helper) => {288 requirePalletsOrSkip(this, helper, [Pallets.Preimage, Pallets.Maintenance]);289290 291 const randomAccounts = await helper.arrange.createCrowd(10, 0n, superuser);292 const randomIdentities = randomAccounts.map((acc, i) => [293 acc.address, {294 deposit: 0n,295 judgements: [],296 info: {297 display: {298 raw: `Random Account #${i}`,299 },300 },301 },302 ]);303 const preimage = helper.constructApiCall('api.tx.identity.forceInsertIdentities', [randomIdentities]).method.toHex();304 preimageHashes.push(await helper.preimage.notePreimage(bob, preimage, true));305 });306 });307308 itSub('Successfully executes call in a preimage', async ({helper}) => {309 const result = await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [310 preimageHashes[0], {refTime: 10000000000, proofSize: 10000},311 ])).to.be.fulfilled;312313 314 const events = result.result.events.filter((x: any) => x.event.method === 'IdentitiesInserted' && x.event.section === 'identity');315 expect(events.length).to.be.equal(1);316317 318 expect(await helper.preimage.getPreimageInfo(preimageHashes[0])).to.have.property('unrequested');319 });320321 itSub('Does not allow execution of a preimage that would fail', async ({helper}) => {322 const [zeroAccount] = await helper.arrange.createAccounts([0n], superuser);323324 const preimage = helper.constructApiCall('api.tx.balances.forceTransfer', [325 {Id: zeroAccount.address}, {Id: superuser.address}, 1000n,326 ]).method.toHex();327 const preimageHash = await helper.preimage.notePreimage(bob, preimage, true);328 preimageHashes.push(preimageHash);329330 await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [331 preimageHash, {refTime: 10000000000, proofSize: 10000},332 ])).to.be.rejectedWith(/^Token: FundsUnavailable$/);333 });334335 itSub('Does not allow preimage execution with non-root', async ({helper}) => {336 await expect(helper.executeExtrinsic(bob, 'api.tx.maintenance.executePreimage', [337 preimageHashes[0], {refTime: 10000000000, proofSize: 10000},338 ])).to.be.rejectedWith(/^Misc: BadOrigin$/);339 });340341 itSub('Does not allow execution of non-existent preimages', async ({helper}) => {342 await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [343 '0x1010101010101010101010101010101010101010101010101010101010101010', {refTime: 10000000000, proofSize: 10000},344 ])).to.be.rejectedWith(/^Misc: Unavailable$/);345 });346347 itSub('Does not allow preimage execution with less than minimum weights', async ({helper}) => {348 await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [349 preimageHashes[0], {refTime: 1000, proofSize: 100},350 ])).to.be.rejectedWith(/^Misc: Exhausted$/);351 });352353 after(async function() {354 await usingPlaygrounds(async (helper) => {355 if(helper.fetchMissingPalletNames([Pallets.Preimage, Pallets.Maintenance]).length != 0) return;356357 for(const hash of preimageHashes) {358 await helper.preimage.unnotePreimage(bob, hash);359 }360 });361 });362 });363364 describe('Integration Test: Maintenance mode & App Promo', () => {365 let superuser: IKeyringPair;366367 before(async function() {368 await usingPlaygrounds(async (helper, privateKey) => {369 requirePalletsOrSkip(this, helper, [Pallets.Maintenance]);370 superuser = await privateKey('//Alice');371 });372 });373374 describe('Test AppPromo script for check state after Maintenance mode', () => {375 before(async function () {376 await usingPlaygrounds(async (helper) => {377 if(await maintenanceEnabled(helper.getApi())) {378 console.warn('\tMaintenance mode was left enabled BEFORE the test suite! Disabling it now.');379 await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', [])).to.be.fulfilled;380 }381 });382 });383 itSub('Can find and fix inconsistent state', async ({helper}) => {384 const api = helper.getApi();385386 await helper.executeExtrinsic(superuser, 'api.tx.sudo.sudo', [api.tx.system.setStorage([387 388 ['0x42b67acb8bd223c60d0c8f621ffefc0ae280fa2db99bd3827aac976de75af95f5153cb1f00942ff401000000',389 '0x04d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d000010632d5ec76b0500000000000000'],390 391 ['0x42b67acb8bd223c60d0c8f621ffefc0ae280fa2db99bd3827aac976de75af95f9eb2dcce60f37a2702000000',392 '0x04d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d000010632d5ec76b0500000000000000'],393 394 ['0xc2261276cc9d1f8598ea4b6a74b15c2fb1c0eb12e038e5c7f91e120ed4b7ebf1de1e86a9a8c739864cf3cc5ec2bea59fd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d',395 '0x046170707374616b656170707374616b65000020c65abc8ed70a00000000000000'],396 ])]);397398 expect((await api.query.appPromotion.pendingUnstake(1)).toJSON()).to.be.deep.equal([[superuser.address, '0x00000000000000056bc75e2d63100000']]);399 expect((await api.query.appPromotion.pendingUnstake(2)).toJSON()).to.be.deep.equal([[superuser.address, '0x00000000000000056bc75e2d63100000']]);400 expect((await api.query.balances.freezes(superuser.address))401 .map(lock => ({id: lock.id.toUtf8(), amount: lock.amount.toBigInt()})))402 .to.be.deep.equal([{id: 'appstakeappstake', amount: 200000000000000000000n}]);403 await correctState();404405 expect((await api.query.appPromotion.pendingUnstake(1)).toJSON()).to.be.deep.equal([]);406 expect((await api.query.appPromotion.pendingUnstake(2)).toJSON()).to.be.deep.equal([]);407 expect((await api.query.balances.freezes(superuser.address)).toJSON()).to.be.deep.equal([]);408409 });410411 itSub('(!negative test!) Only works when Maintenance mode is disabled', async({helper}) => {412 await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', [])).to.be.fulfilled;413 await expect(correctState()).to.be.rejectedWith('The network is still in maintenance mode');414 await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', [])).to.be.fulfilled;415 });416 });417 });418419 after(async () => {420 await usingPlaygrounds(async(helper) => {421 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);422 });423 });424});