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

difftreelog

Merge pull request #948 from UniqueNetwork/ci/locks-to-freezes

Yaroslav Bolyukin2023-06-13parents: #aec0c5d #307e69b.patch.diff
in: master

17 files changed

modified.docker/Dockerfile-parachain-upgrade-data.j2diffbeforeafterboth
--- a/.docker/Dockerfile-parachain-upgrade-data.j2
+++ b/.docker/Dockerfile-parachain-upgrade-data.j2
@@ -42,6 +42,7 @@
 
 ENV RELAY_CHAIN_TYPE={{ RELAY_CHAIN_TYPE }}
 ENV REPLICA_FROM={{ REPLICA_FROM }}
+ENV DESTINATION_SPEC_VERSION={{ DESTINATION_SPEC_VERSION }}
 ENV NEW_PARA_BIN=/unique-chain/target/release/unique-collator
 ENV NEW_PARA_WASM=/unique-chain/target/release/wbuild/{{ WASM_NAME }}-runtime/{{ WASM_NAME }}_runtime.compact.compressed.wasm
 
@@ -77,7 +78,7 @@
 EXPOSE 33144
 EXPOSE 33155
 
-CMD export NVM_DIR="$HOME/.nvm" PATH="$PATH:/chainql/target/release" REPLICA_FROM NEW_PARA_BIN NEW_PARA_WASM RELAY_CHAIN_TYPE && \
+CMD export NVM_DIR="$HOME/.nvm" PATH="$PATH:/chainql/target/release" REPLICA_FROM NEW_PARA_BIN NEW_PARA_WASM RELAY_CHAIN_TYPE DESTINATION_SPEC_VERSION && \
     [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" && \
     cd /unique-chain/tests && \
     npm install --global yarn && \
modified.docker/docker-compose.forkless-data.j2diffbeforeafterboth
--- a/.docker/docker-compose.forkless-data.j2
+++ b/.docker/docker-compose.forkless-data.j2
@@ -3,7 +3,7 @@
 services:
   forkless-data:
     image: uniquenetwork/ci-forkless-data-local:{{ NETWORK }}-{{ BUILD_TAG }}
-    container_name: forkless-data
+    container_name: forkless-data-{{ NETWORK }}
     expose:
       - 9944
       - 9933
modified.envdiffbeforeafterboth
--- a/.env
+++ b/.env
@@ -2,6 +2,7 @@
 POLKADOT_LAUNCH_BRANCH=unique-network
 RELAY_CHAIN_TYPE=westend
 CHAINQL=v0.4.1
+DESTINATION_SPEC_VERSION=v942057
 
 POLKADOT_MAINNET_BRANCH=release-v0.9.37
 STATEMINT_BUILD_BRANCH=release-parachains-v9370
@@ -16,12 +17,12 @@
 KARURA_BUILD_BRANCH=release-karura-2.17.0
 MOONRIVER_BUILD_BRANCH=runtime-2302
 SHIDEN_BUILD_BRANCH=v5.4.0
-QUARTZ_MAINNET_BRANCH=release-v941055
+QUARTZ_MAINNET_BRANCH=release-v941056
 QUARTZ_REPLICA_FROM=wss://ws-quartz.unique.network:443
 
 UNIQUEWEST_MAINNET_BRANCH=release-v0.9.42
 WESTMINT_BUILD_BRANCH=parachains-v9420
-OPAL_MAINNET_BRANCH=release-v941055
+OPAL_MAINNET_BRANCH=release-v942057
 OPAL_REPLICA_FROM=wss://ws-opal.unique.network:443
 
 UNIQUEEAST_MAINNET_BRANCH=release-v0.9.42
modified.github/workflows/forkless-update-data.ymldiffbeforeafterboth
--- a/.github/workflows/forkless-update-data.yml
+++ b/.github/workflows/forkless-update-data.yml
@@ -82,6 +82,7 @@
             MAINNET_BRANCH=${{ matrix.mainnet_branch }}
             WASM_NAME=${{ matrix.wasm_name }}
             RELAY_CHAIN_TYPE=${{ env.RELAY_CHAIN_TYPE }}
+            DESTINATION_SPEC_VERSION=${{ env.DESTINATION_SPEC_VERSION }}
             POLKADOT_BUILD_BRANCH=${{ matrix.relay_branch }}
             REPLICA_FROM=${{ matrix.replica_from_address }}
             CHAINQL=${{ env.CHAINQL }}
@@ -198,14 +199,14 @@
         run: |
           counter=160
           function check_container_status {
-                docker inspect -f {{.State.Running}} forkless-data
+                docker inspect -f {{.State.Running}} forkless-data-${{ matrix.network }}
           }
           function do_docker_logs {
-                docker logs --details forkless-data  2>&1
+                docker logs --details forkless-data-${{ matrix.network }}  2>&1
           }
           function is_started {
                 if [ "$(check_container_status)" == "true" ]; then
-                        echo "Container: forkless-data RUNNING";
+                        echo "Container: forkless-data-${{ matrix.network }} RUNNING";
                         echo "Check Docker logs"
                         DOCKER_LOGS=$(do_docker_logs)
                         if [[ ${DOCKER_LOGS} = *"🛸 PARACHAINS' RUNTIME UPGRADE TESTING COMPLETE 🛸"* ]];then
@@ -219,7 +220,7 @@
                                 return 1
                         fi
                 else
-                        echo "Container forkless-data not RUNNING"
+                        echo "Container forkless-data-${{ matrix.network }} not RUNNING"
                         echo "Halting all future checks"
                         exit 1
                 fi
@@ -249,7 +250,7 @@
 
       - name: Show Docker logs
         if: success() || failure()
-        run: cat './forkless-parachain-upgrade-data-logs.${{ matrix.network }}/forkless-data.log'
+        run: cat './forkless-parachain-upgrade-data-logs.${{ matrix.network }}/forkless-data-${{ matrix.network }}.log'
 
       - name: Stop running containers
         if: always()                   # run this step always
modifiedtests/package.jsondiffbeforeafterboth
--- a/tests/package.json
+++ b/tests/package.json
@@ -139,6 +139,7 @@
     "chai-like": "^1.1.1",
     "csv-writer": "^1.6.0",
     "find-process": "^1.4.7",
+    "lossless-json": "^2.0.9",
     "solc": "0.8.17",
     "web3": "1.10.0"
   },
addedtests/src/migrations/942057-appPromotion/README.mddiffbeforeafterboth
--- /dev/null
+++ b/tests/src/migrations/942057-appPromotion/README.md
@@ -0,0 +1,42 @@
+# Update Procedure
+
+- Enable maintenance mode
+- [Collect migration data using ChainQL](#stakers-data-loading)
+- ❗️❗️❗️ Initiate the runtime upgrade only at this point ❗️❗️❗️
+- Wait for the upgrade to complete
+- [Execute offchain migration](#execute-offchain-migration)
+- Disable maintenance mode
+
+## Stakers Data Loading
+
+Set the environment variable (WS_RPC). For example, ws://localhost:9944. Execute the following command:
+
+```sh
+chainql --tla-str=chainUrl=<WS_RPC> stakersParser.jsonnet > output.json
+```
+
+where `<WS_RPC>` - is the network address.
+
+Example for Opal:
+
+```sh
+chainql --tla-str=chainUrl=wss://eu-ws-opal.unique.network:443 stakersParser.jsonnet > output.json
+```
+
+To install chainql, execute the following command:
+
+```sh
+cargo install chainql
+```
+
+## Execute offchain migration
+
+To run, you need to set an environment variables:
+- `SUPERUSER_SEED` – the sudo key seed.
+- `WS_RPC` – the network address
+
+Run the migration by executing the following command:
+
+```sh
+npx ts-node --esm executeMigration.ts
+```
addedtests/src/migrations/942057-appPromotion/afterMaintenance.test.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/migrations/942057-appPromotion/afterMaintenance.test.ts
@@ -0,0 +1,75 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import {IKeyringPair} from '@polkadot/types/types';
+import {ApiPromise} from '@polkadot/api';
+import {expect, itSub, Pallets, requirePalletsOrSkip, usingPlaygrounds} from '../../util';
+import {main as testedScript} from './correctStateAfterMaintenance';
+
+async function maintenanceEnabled(api: ApiPromise): Promise<boolean> {
+  return (await api.query.maintenance.enabled()).toJSON() as boolean;
+}
+
+
+
+describe('Integration Test: Maintenance mode & App Promo', () => {
+  let superuser: IKeyringPair;
+
+  before(async function() {
+    await usingPlaygrounds(async (helper, privateKey) => {
+      requirePalletsOrSkip(this, helper, [Pallets.Maintenance]);
+      superuser = await privateKey('//Alice');
+    });
+  });
+
+  describe('Test AppPromo script for check state after Maintenance mode', () => {
+    before(async function () {
+      await usingPlaygrounds(async (helper) => {
+        if(await maintenanceEnabled(helper.getApi())) {
+          console.warn('\tMaintenance mode was left enabled BEFORE the test suite! Disabling it now.');
+          await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', [])).to.be.fulfilled;
+        }
+      });
+    });
+    itSub('Can find and fix inconsistent state', async({helper}) => {
+      const api = helper.getApi();
+
+      await helper.executeExtrinsic(superuser, 'api.tx.sudo.sudo', [api.tx.system.setStorage([
+        ['0x42b67acb8bd223c60d0c8f621ffefc0ae280fa2db99bd3827aac976de75af95f5153cb1f00942ff401000000',
+          '0x04d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d000010632d5ec76b0500000000000000'],
+        ['0x42b67acb8bd223c60d0c8f621ffefc0ae280fa2db99bd3827aac976de75af95f9eb2dcce60f37a2702000000',
+          '0x04d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d000010632d5ec76b0500000000000000'],
+        ['0xc2261276cc9d1f8598ea4b6a74b15c2fb1c0eb12e038e5c7f91e120ed4b7ebf1de1e86a9a8c739864cf3cc5ec2bea59fd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d',
+          '0x046170707374616b656170707374616b65000020c65abc8ed70a00000000000000'],
+      ])]);
+
+      // const pendingUnstaked = await helper.staking.getPendingUnstakePerBlock()
+      expect((await api.query.appPromotion.pendingUnstake(1)).toJSON()).to.be.deep.equal([[helper.address.normalizeSubstrateToChainFormat('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'), '0x00000000000000056bc75e2d63100000']]);
+      expect((await api.query.appPromotion.pendingUnstake(2)).toJSON()).to.be.deep.equal([[helper.address.normalizeSubstrateToChainFormat('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'), '0x00000000000000056bc75e2d63100000']]);
+      await testedScript();
+
+      expect((await api.query.appPromotion.pendingUnstake(1)).toJSON()).to.be.deep.equal([]);
+      expect((await api.query.appPromotion.pendingUnstake(2)).toJSON()).to.be.deep.equal([]);
+
+    });
+
+    itSub('(!negative test!) Only works when Maintenance mode is disabled', async({helper}) => {
+      await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', [])).to.be.fulfilled;
+      await expect(testedScript()).to.be.rejectedWith('The network is still in maintenance mode');
+      await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', [])).to.be.fulfilled;
+    });
+  });
+});
addedtests/src/migrations/942057-appPromotion/collectData.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/migrations/942057-appPromotion/collectData.ts
@@ -0,0 +1,12 @@
+import {exec} from 'child_process';
+import path from 'path';
+import {dirname} from 'path';
+import {fileURLToPath} from 'url';
+
+export const collectData = () => {
+  const dirName = dirname(fileURLToPath(import.meta.url));
+
+  const pathToScript = path.resolve(dirName, './stakersParser.jsonnet');
+  const outputPath = path.resolve(dirName, './output.json');
+  exec(`chainql --tla-str=chainUrl=ws://127.0.0.1:9944 ${pathToScript} > ${outputPath}`);
+};
addedtests/src/migrations/942057-appPromotion/correctStateAfterMaintenance.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/migrations/942057-appPromotion/correctStateAfterMaintenance.ts
@@ -0,0 +1,72 @@
+import {usingPlaygrounds} from '../../util';
+
+
+
+const WS_ENDPOINT = 'ws://localhost:9944';
+const DONOR_SEED = '//Alice';
+
+export const main = async(options: { wsEndpoint: string; donorSeed: string } = {
+  wsEndpoint: WS_ENDPOINT,
+  donorSeed: DONOR_SEED,
+}) => {
+  await usingPlaygrounds(async (helper, privateKey) => {
+    const api = helper.getApi();
+
+    if((await api.query.maintenance.enabled()).valueOf()) {
+      throw Error('The network is still in maintenance mode');
+    }
+
+    const pendingBlocks = (
+      await api.query.appPromotion.pendingUnstake.entries()
+    ).map(([k, _v]) =>
+      k.args[0]);
+
+    const currentBlock = await api.query.system.number();
+
+    const filteredBlocks = pendingBlocks.filter((b) => currentBlock.gt(b));
+
+    if(filteredBlocks.length != 0) {
+      console.log(
+        'During maintenance mode, %d block(s) were not processed',
+        filteredBlocks.length,
+      );
+    } else {
+      console.log('Nothing to change');
+      return;
+    }
+
+    const skippedBlocks = chunk(filteredBlocks, 10);
+
+    const signer = await privateKey(options.donorSeed);
+
+    const txs = skippedBlocks.map((b) =>
+      api.tx.sudo.sudo(api.tx.appPromotion.forceUnstake(b)));
+
+
+    const promises = txs.map((tx) => () => helper.signTransaction(signer, tx));
+
+    await Promise.allSettled(promises.map((p) => p()));
+
+    const failedBlocks: bigint[] = [];
+    let isSuccess = true;
+
+    for(const b of filteredBlocks) {
+      if(((await api.query.appPromotion.pendingUnstake(b)).toJSON() as any[]).length != 0) {
+        failedBlocks.push(b.toBigInt());
+        isSuccess = false;
+      }
+    }
+
+    if(isSuccess) {
+      console.log('Done. %d block(s) were processed.', filteredBlocks.length);
+    } else {
+      throw new Error(`Something went wrong. Block(s) have not been processed: ${failedBlocks}`);
+    }
+
+
+  }, options.wsEndpoint);
+};
+
+const chunk = <T>(arr: T[], size: number) =>
+  Array.from({length: Math.ceil(arr.length / size)}, (_: any, i: number) =>
+    arr.slice(i * size, i * size + size));
\ No newline at end of file
addedtests/src/migrations/942057-appPromotion/executeMigration.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/migrations/942057-appPromotion/executeMigration.ts
@@ -0,0 +1,11 @@
+import {migrateLockedToFreeze} from './lockedToFreeze';
+
+
+const WS_RPC = process.env.WS_RPC || 'wss://ws-opal.unique.network:443';
+const SUPERUSER_SEED = process.env.SUPERUSER_SEED || '';
+
+migrateLockedToFreeze({
+  wsEndpoint: WS_RPC,
+  donorSeed: SUPERUSER_SEED,
+})
+  .catch(console.error);
\ No newline at end of file
addedtests/src/migrations/942057-appPromotion/index.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/migrations/942057-appPromotion/index.ts
@@ -0,0 +1,12 @@
+import {Migration} from '../../util/frankensteinMigrate';
+import {collectData} from './collectData';
+import {migrateLockedToFreeze} from './lockedToFreeze';
+
+export const migration: Migration = {
+  async before() {
+    await collectData();
+  },
+  async after() {
+    await migrateLockedToFreeze();
+  },
+};
addedtests/src/migrations/942057-appPromotion/lockedToFreeze.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/migrations/942057-appPromotion/lockedToFreeze.ts
@@ -0,0 +1,258 @@
+// import { usingApi, privateKey, onlySign } from "./../../load/lib";
+import * as fs from 'fs';
+import {usingPlaygrounds} from '../../util';
+import path, {dirname} from 'path';
+import {isInteger, parse} from 'lossless-json';
+import {fileURLToPath} from 'url';
+
+
+const WS_ENDPOINT = 'ws://localhost:9944';
+const DONOR_SEED = '//Alice';
+const UPDATE_IF_VERSION = 942057;
+
+export function customNumberParser(value: any) {
+  return isInteger(value) ? BigInt(value) : parseFloat(value);
+}
+
+export const migrateLockedToFreeze = async(options: { wsEndpoint: string; donorSeed: string } = {
+  wsEndpoint: WS_ENDPOINT,
+  donorSeed: DONOR_SEED,
+}) => {
+  await usingPlaygrounds(async (helper, privateKey) => {
+    const api = helper.getApi();
+    // 1. Check version equal 942057 or skip
+    console.log((api.consts.system.version as any).specVersion.toNumber());
+    if((api.consts.system.version as any).specVersion.toNumber() != UPDATE_IF_VERSION) {
+      console.log("Version isn't 942057.");
+      return;
+    }
+
+    // 2. Get sudo signer
+    const signer = await privateKey(options.donorSeed);
+    console.log('2. Getting sudo:', signer.address);
+
+    // 3. Parse data to migrate
+    console.log('3. Parsing chainql results...');
+    const dirName = dirname(fileURLToPath(import.meta.url));
+    const parsingResult = parse(fs.readFileSync(path.resolve(dirName, 'output.json'), 'utf-8'), undefined, customNumberParser);
+
+    const chainqlImportData = parsingResult as {
+      address: string;
+      balance: string;
+      account: {
+        fee_frozen: string,
+        free: string,
+        misc_frozen: string,
+        reserved: string,
+      },
+      locks: {
+        amount: string,
+        id: string,
+      }[],
+      stakes: object,
+      unstakes: object,
+    }[];
+    testChainqlData(chainqlImportData);
+
+    const stakers = chainqlImportData.map((i) => i.address);
+
+    // 3.1 Split into chunks by 100
+    console.log('3.1 Splitting into chunks...');
+    const stakersChunks = chunk(stakers, 100);
+    console.log('3.1 Done, total chunks:', stakersChunks.length);
+
+    // 4. Get signer/sudo nonce
+    console.log('4. Getting sudo nonce...');
+    const signerAccount = (
+        await api.query.system.account(signer.address)
+      ).toJSON() as any;
+
+    let nonce: number = signerAccount.nonce;
+    console.log('4. Sudo nonce is:', nonce);
+
+    // 5. Only sign upgradeAccounts-transactions for each chunk
+    console.log('5. Signing transactions...');
+    const signedTxs = [];
+    for(const chunk of stakersChunks) {
+      const tx = api.tx.sudo.sudo(api.tx.appPromotion.upgradeAccounts(chunk));
+      const signed = tx.sign(signer, {
+        blockHash: api.genesisHash,
+        genesisHash: api.genesisHash,
+        runtimeVersion: api.runtimeVersion,
+        nonce: nonce++,
+      });
+      signedTxs.push(signed);
+    }
+
+    // 6. Send all signed transactions
+    console.log('6. Sending transactions...');
+    const promises = signedTxs.map((tx) => api.rpc.author.submitAndWatchExtrinsic(tx));
+    // 6.1 Wait all transactions settled
+    console.log('6.1 Waiting all transactions settled...');
+    const res = await Promise.allSettled(promises);
+
+    console.log('Wait 5 blocks for transactions to be included in a block...');
+    await helper.wait.newBlocks(5);
+    // 6.2 Filter failed transactions
+    console.log('6.2 Getting failed transactions...');
+    const failedTx = res.filter((r) => r.status == 'rejected') as PromiseRejectedResult[];
+    console.log('6.2. total failedTxs:', failedTx.length);
+
+    // 6.3 Log the reasons of failed tx
+    for(const tx of failedTx) {
+      console.log(tx.reason);
+    }
+
+    // 7. Check balances for 10 blocks:
+    console.log('7. Check balances...');
+    let blocksLeft = 10;
+    let notMigrated = stakers;
+    const suspiciousAccounts = [];
+    do {
+      console.log('blocks left:', blocksLeft);
+      const _notMigrated: string[] = [];
+      console.log('accounts to migrate...', notMigrated.length);
+      for(const accountToMigrate of notMigrated) {
+        let accountMigrated = true;
+        // 7.0 get data from chainql:
+        const oldAccount = chainqlImportData.find(acc => acc.address === accountToMigrate);
+        if(!oldAccount) {
+          console.log('Cannot find old account data for', accountMigrated);
+          accountMigrated = false;
+          _notMigrated.push(accountToMigrate);
+          continue;
+        }
+
+        // 7.1 system.account
+        const balance = await api.query.system.account(accountToMigrate) as any;
+        // new balances
+        const free = balance.data.free;
+        const reserved = balance.data.reserved;
+        const frozen = balance.data.frozen;
+        // old balances
+        const oldFree = oldAccount.account.free;
+        const oldReserved = oldAccount.account.reserved;
+        const oldFrozen = oldAccount.account.fee_frozen;
+        // asserts new = old
+        if(oldFree.toString() !== free.toString()) {
+          console.log('Old free !== New free, which is probably not a problem', oldFree.toString(), free.toString());
+          suspiciousAccounts.push(accountToMigrate);
+        }
+        if(oldFrozen.toString() !== frozen.toString()) {
+          console.log('Old frozen !== New frozen, which is probably not a problem', oldFrozen.toString(), frozen.toString());
+          suspiciousAccounts.push(accountToMigrate);
+        }
+        if(oldReserved.toString() !== reserved.toString()) {
+          console.log('Old reserved !== New reserved, which is probably not a problem', oldReserved.toString(), reserved.toString());
+          suspiciousAccounts.push(accountToMigrate);
+        }
+
+        // 7.2 balances.locks: no id appstake
+        const locks = await helper.balance.getLocked(accountToMigrate);
+        const appPromoLocks = locks.filter(lock => lock.id === 'appstake');
+        if(appPromoLocks.length !== 0) {
+          console.log('Account still has app-promo lock');
+          accountMigrated = false;
+        }
+
+        // 7.3 balances.freezes set...
+        let freezes = await api.query.balances.freezes(accountToMigrate) as any;
+        freezes = freezes.map((freez: any) => ({id: freez.id.toString(), amount: freez.amount.toString()}));
+        if(!freezes) {
+          console.log('Account does not have freezes');
+          accountMigrated = false;
+        } else {
+          const oldAppPromoLocks = oldAccount.locks.filter(l => l.id === '0x6170707374616b65'); // get app promo locks
+          // should be only one freez for each account
+          if(freezes.length !== 1) {
+            console.log('freezes.length !== 1 and old appPromoLocks.length', freezes.length, oldAppPromoLocks.length);
+            accountMigrated = false;
+          } else {
+            const appPromoFreez = freezes[0];
+            // freez-amount should be equal to migrated lock amount
+            if(appPromoFreez.amount.toString() !== oldAppPromoLocks[0].amount.toString()) {
+              console.log('freezes amount !== old appPromoLocks amount', appPromoFreez.amount.toString(), oldAppPromoLocks[0].amount.toString());
+              accountMigrated = false;
+            }
+            // freez id should be correct
+            if(appPromoFreez.id !== '0x6170707374616b656170707374616b65') {
+              console.log('Got freez with incorrect id:', appPromoFreez.id);
+              accountMigrated = false;
+            }
+          }
+        }
+
+        // 7.4 Stakes number the same
+        const stakesNumber = await helper.staking.getStakesNumber({Substrate: accountToMigrate});
+        const oldStakesNumber = oldAccount.stakes ? Object.keys(oldAccount.stakes).length : 0;
+        if(stakesNumber.toString() !== oldStakesNumber.toString()) {
+          console.log('Old stakes number !== New stakes number', oldStakesNumber, stakesNumber);
+          accountMigrated = false;
+        }
+
+        // 7.5 Total pendingUnstake + total staked = old locked
+        const pendingUnstakes = await helper.staking.getPendingUnstake({Substrate: accountToMigrate});
+        const totalStaked = await helper.staking.getTotalStaked({Substrate: accountToMigrate});
+        const totalBalanceInAppPromo = pendingUnstakes + totalStaked;
+        if(totalBalanceInAppPromo.toString() !== oldAccount.balance.toString()) {
+          console.log('totalBalanceInAppPromo !== old locked in app promo', totalBalanceInAppPromo.toString(), oldAccount.balance.toString());
+          accountMigrated = false;
+        }
+
+        // 8 Add to not-migrated
+        if(!accountMigrated) {
+          console.log('Add to not migrated:', accountToMigrate);
+          _notMigrated.push(accountToMigrate);
+        }
+      }
+
+      blocksLeft--;
+      notMigrated = _notMigrated;
+      await helper.wait.newBlocks(1);
+    } while(blocksLeft > 0 && notMigrated.length !== 0);
+
+    console.log('Not migrated accounts...', notMigrated.length);
+    if(suspiciousAccounts.length > 0) {
+      console.log('Saving suspicious accounts to suspicious.json:');
+      fs.writeFileSync('./suspicious.json', JSON.stringify(suspiciousAccounts));
+    }
+    if(notMigrated.length > 0) {
+      console.log('Saving not migrated list to failed.json:');
+      notMigrated.forEach(console.log);
+      fs.writeFileSync('./failed.json', JSON.stringify(notMigrated));
+      process.exit(1);
+    } else {
+      console.log('Migration success');
+    }
+  }, options.wsEndpoint);
+};
+
+const chunk = <T>(arr: T[], size: number) =>
+  Array.from({length: Math.ceil(arr.length / size)}, (_: any, i: number) =>
+    arr.slice(i * size, i * size + size));
+
+const testChainqlData = (data: any) => {
+  const wrongData = [];
+  for(const account of data) {
+    try {
+      if(account.address == null) throw Error('no address in data');
+      if(account.balance == null) throw Error('no balance in data');
+      if(account.account == null) throw Error('no account in data');
+      if(account.account.fee_frozen == null) throw Error('no account.fee_frozen in data');
+      if(account.account.misc_frozen == null) throw Error('no account.misc_frozen in data');
+      if(account.account.free == null) throw Error('no account.free in data');
+      if(account.account.reserved == null) throw Error('no account.reserved in data');
+      if(account.locks == null) throw Error('no locks in data');
+      if(account.locks[0].amount == null) throw Error('no locks.amount in data');
+      if(account.locks[0].id == null) throw Error('no locks.id in data');
+    } catch (error) {
+      wrongData.push(account.address);
+      console.log((error as Error).message, account.address);
+    }
+    if(wrongData.length > 0) {
+      console.log(data);
+      throw Error('Chainql data not correct');
+    }
+  }
+  console.log('Chainql data correct');
+};
addedtests/src/migrations/942057-appPromotion/runCheckState.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/migrations/942057-appPromotion/runCheckState.ts
@@ -0,0 +1,13 @@
+import {main} from './correctStateAfterMaintenance';
+
+
+
+
+main({
+  wsEndpoint: process.env.WS_RPC!,
+  donorSeed: process.env.SUPERUSER_SEED!,
+}).then(() => process.exit(0))
+  .catch((e) => {
+    console.error(e);
+    process.exit(1);
+  });
\ No newline at end of file
addedtests/src/migrations/942057-appPromotion/stakersParser.jsonnetdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/migrations/942057-appPromotion/stakersParser.jsonnet
@@ -0,0 +1,29 @@
+function(chainUrl)
+
+  local
+    state = cql.chain(chainUrl).latest,
+    locked_balances = state.Balances.Locks._preloadKeys,
+    accountsRaw = state.System.Account._preloadKeys,
+    stakers = state.AppPromotion.Staked._preloadKeys,
+    unstakes = state.AppPromotion.PendingUnstake._preloadKeys,
+    locks = [
+      { [k]: std.filter(function(l) l.id == '0x6170707374616b65', locked_balances[k]) }
+      for k in std.objectFields(locked_balances)
+    ],
+    unstakersData = [
+      { [pair[0]]: { block: block, value: pair[1] } }
+
+      for block in std.objectFields(unstakes)
+      for pair in unstakes[block]
+    ],
+    non_empty_locks = std.prune(locks)
+  ;
+
+  std.map(function(a) {
+    address: std.objectFields(a)[0],
+    balance: a[std.objectFields(a)[0]][0].amount,
+    account: accountsRaw[std.objectFields(a)[0]].data,
+    locks: locked_balances[std.objectFields(a)[0]],
+    stakes: if std.objectHas(stakers, std.objectFields(a)[0]) then stakers[std.objectFields(a)[0]] else null,
+    unstakes: std.filterMap(function(b) std.objectHas(b, std.objectFields(a)[0]), function(c) std.objectValues(c)[0], unstakersData),
+  }, non_empty_locks)
modifiedtests/src/util/frankenstein.tsdiffbeforeafterboth
before · tests/src/util/frankenstein.ts
1// Copyright 2019-2023 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 {ApiPromise} from '@polkadot/api';18import {blake2AsHex, cryptoWaitReady} from '@polkadot/util-crypto';19import zombie from '@zombienet/orchestrator/dist';20import {readNetworkConfig} from '@zombienet/utils/dist';21import {resolve} from 'path';22import {usingPlaygrounds} from '.';23import fs from 'fs';2425const ZOMBIENET_CREDENTIALS = process.env.ZOMBIENET_CREDENTIALS || '../.env';26const NETWORK_CONFIG_FILE = process.argv[2] ?? '../launch-zombienet.toml';27const PARA_DIR = process.env.PARA_DIR || '../';28const RELAY_DIR = process.env.RELAY_DIR || '../../polkadot/';29const REPLICA_FROM = process.env.REPLICA_FROM || 'wss://ws-opal.unique.network:443';30const NEW_RELAY_BIN = process.env.NEW_RELAY_BIN;31const NEW_RELAY_WASM = process.env.NEW_RELAY_WASM;32const NEW_PARA_BIN = process.env.NEW_PARA_BIN;33const NEW_PARA_WASM = process.env.NEW_PARA_WASM;34const PARACHAIN_BLOCK_TIME = 12_000;35const SUPERUSER_KEY = '//Alice';3637let network: zombie.Network | undefined;3839// Stop the network if it is running40const stop = async () => {41  await network?.stop();42};4344// Promise of a timeout45function delay(ms: number) {46  return new Promise(resolve => setTimeout(resolve, ms));47}4849// Countdown with time left on display50async function waitWithTimer(time: number) {51  const secondsTotal = Math.ceil(time / 1000);52  for(let i = secondsTotal; i > 0; i--) {53    // could also introduce hours, but wth54    const seconds = i % 60;55    const text = `Time left: ${Math.floor(i / 60)}:${seconds < 10 ? '0' + seconds : seconds}`;56    if(process.stdout.isTTY)57      process.stdout.write(text);58    else if(seconds % 10 == 0)59      console.log(text);60    await delay(1000);61    if(process.stdout.isTTY) {62      process.stdout.clearLine(0);63      process.stdout.cursorTo(0);64    }65  }66}6768// Get the runtime's current version69function getSpecVersion(api: ApiPromise): number {70  return (api.consts.system.version as any).specVersion.toNumber();71}7273// Get the required information on the relay chain74function getRelayInfo(api: ApiPromise): {specVersion: number, epochBlockLength: number, blockTime: number, epochTime: number} {75  const info = {76    specVersion: getSpecVersion(api),77    epochBlockLength: (api.consts.babe.epochDuration as any).toNumber(),78    blockTime: (api.consts.babe.expectedBlockTime as any).toNumber(),79    epochTime: 0,80  };81  info.epochTime = info.epochBlockLength * info.blockTime;82  return info;83}8485// Enable or disable maintenance mode if present on the chain86async function toggleMaintenanceMode(value: boolean, wsUri: string) {87  await usingPlaygrounds(async (helper, privateKey) => {88    const superuser = await privateKey(SUPERUSER_KEY);89    try {90      const toggle = value ? 'enable' : 'disable';91      await helper.getSudo().executeExtrinsic(superuser, `api.tx.maintenance.${toggle}`, []);92      console.log(`Maintenance mode ${value ? 'engaged' : 'disengaged'}.`);93    } catch (e) {94      console.error('Couldn\'t set maintenance mode. The maintenance pallet probably does not exist. Log:', e);95    }96  }, wsUri);97}9899const raiseZombienet = async (): Promise<void> => {100  const isUpgradeTesting = !!NEW_RELAY_BIN || !!NEW_RELAY_WASM || !!NEW_PARA_BIN || !!NEW_PARA_WASM;101  /*102  // If there is nothing to upgrade, what is the point103  if (!isUpgradeTesting) {104    console.warn('\nNeither the relay nor the parachain were selected for an upgrade! ' +105      'Please pass environment vars `NEW_RELAY_BIN`, `NEW_RELAY_WASM`, `NEW_PARA_BIN`, `NEW_PARA_WASM`.');106    process.exit(1);107  }108  */109110  // an unsavory practice, but very convenient, mwahahah111  process.env.PARA_DIR = PARA_DIR;112  process.env.RELAY_DIR = RELAY_DIR;113  process.env.REPLICA_FROM = REPLICA_FROM;114115  const configPath = resolve(NETWORK_CONFIG_FILE);116  const networkConfig = readNetworkConfig(configPath);117  // console.log(networkConfig);118  if(networkConfig.settings.provider !== 'native') {119    throw new Error(`Oh no! Expected native network, got ${networkConfig.settings.provider}.`);120  }121122  await cryptoWaitReady();123124  // Launch Zombienet!125  network = await zombie.start(ZOMBIENET_CREDENTIALS, networkConfig, {silent: false});126127  // Get the relay chain info like the epoch length and spec version128  // Then restart each parachain's binaries129  // // Stop and restart each node130  // // Send specified keys to parachain nodes in case the parachain requires it131  // If it is not needed to upgrade runtimes themselves, the job is done!132133  // Record some required information regarding the relay chain134  await network.relay[0].connectApi();135  let relayInfo = getRelayInfo((network.relay[0] as any).apiInstance!);136  await network.relay[0].apiInstance!.disconnect();137  if(isUpgradeTesting) {138    console.log('Relay stats:', relayInfo);139  }140141  // non-exported functionality of NativeClient142  const networkClient = (network.client as any);143144  if(NEW_RELAY_BIN) {145    console.log('\n🧶 Restarting relay nodes');146147    for(const [index, node] of network.relay.entries()) {148      await node.apiInstance?.disconnect();149150      console.log(`\n🚦 Starting timeout for the epoch change (node ${index + 1}/${network.relay.length})...`);151      await waitWithTimer(relayInfo.epochTime);152153      // Replace the node-starting command with the new binary154      const cmd = networkClient.processMap[node.name].cmd[0].split(' ')[0];155      networkClient.processMap[node.name].cmd = networkClient.processMap[node.name].cmd.map((arg: string) => arg.replace(cmd, NEW_RELAY_BIN));156157      await node.restart();158    }159160    console.log('\n🌒 All relay nodes restarted with the new binaries.');161  }162163  if(NEW_PARA_BIN) {164    for(const paraId in network.paras) {165      const para = network.paras[paraId];166      console.log(`\n🧶 Restarting collator nodes of parachain ${paraId}`);167168      for(const [_index, node] of para.nodes.entries()) {169        await node.apiInstance?.disconnect();170171        // Replace the node-starting command with the new binary172        const cmd = networkClient.processMap[node.name].cmd[0].split(' ')[0];173        networkClient.processMap[node.name].cmd = networkClient.processMap[node.name].cmd.map((arg: string) => arg.replace(cmd, NEW_PARA_BIN));174175        await node.restart();176        // applyaurakey?177        // Zombienet handles it on first-time node creation178      }179    }180181    console.log('\n🌗 All parachain collators restarted with the new binaries.');182  }183184  // Re-establish connection to the relay node and get the runtime upgrade validation delay for parachains185  // For the relay, connect and set the new runtime code186  // For each parachain, connect, authorize and upgrade its runtime187  // Ping the the chains for the runtime upgrade after the minimal time and then every few blocks188  // // For each parachain, re-connect and verify that the runtime upgrade is successful189190  let relayUpgradeCompleted = false, paraUpgradeCompleted = false;191192  if(NEW_RELAY_WASM) {193    const relayOldVersion = relayInfo.specVersion;194    console.log('\n🚦 Starting timeout for the next epoch before upgrading the relay runtime code...');195    await waitWithTimer(relayInfo.epochTime);196197    console.log('--- Upgrading the relay chain runtime \t---');198199    // Read the new WASM code and set it as the relay's new code200    const code = fs.readFileSync(NEW_RELAY_WASM).toString('hex');201    await usingPlaygrounds(async (helper, privateKey) => {202      const superuser = await privateKey(SUPERUSER_KEY);203204      const result = await helper.executeExtrinsic(205        superuser,206        'api.tx.sudo.sudoUncheckedWeight',207        [helper.constructApiCall('api.tx.system.setCode', [`0x${code}`]), {}],208      );209210      if(result.status == 'Fail') {211        console.error('Failed to upgrade the runtime:', result);212      }213214      // Get the updated information from the relay's new runtime215      relayInfo = getRelayInfo(helper.getApi());216    }, network.relay[0].wsUri);217218    if(relayOldVersion != relayInfo.specVersion) {219      // eslint-disable-next-line no-useless-escape220      console.log(`\n\🛰️ The relay has successfully upgraded from version ${relayOldVersion} to ${relayInfo.specVersion}!`);221      relayUpgradeCompleted = true;222    } else {223      console.error(`\nThe relay did not upgrade from version ${relayOldVersion}!`);224    }225  } else {226    // If the relay did not need to be upgraded, it's already technically completed227    relayUpgradeCompleted = true;228  }229230  if(NEW_PARA_WASM) {231    let codeValidationDelayBlocks = 0;232    const upgradingParas: {[id: string]: {version: number, upgraded: boolean}} = {};233    // Calculate the code validation delay of the relay chain,234    // so that we know how much to wait before the parachains can be upgraded after the extrinsic235    await usingPlaygrounds(async (helper) => {236      const {validationUpgradeDelay, minimumValidationUpgradeDelay} =237        (await helper.callRpc('api.query.configuration.activeConfig', [])).toJSON() as any;238239      codeValidationDelayBlocks = Math.max(validationUpgradeDelay ?? 0, minimumValidationUpgradeDelay ?? 0);240    }, network.relay[0].wsUri);241242    // Wait for the next epoch so that the parachains will start cooperating with the relay243    if(relayUpgradeCompleted && NEW_RELAY_WASM) {244      console.log('\n🚥 Starting timeout for the next epoch before upgrading the parachains code...');245      await waitWithTimer(relayInfo.epochTime);246    }247248    for(const paraId in network.paras) {249      console.log(`\n--- Upgrading the runtime of parachain ${paraId} \t---`);250      const para = network.paras[paraId];251252      // Enable maintenance mode if present253      await toggleMaintenanceMode(true, para.nodes[0].wsUri);254255      // Read the WASM code and authorize the upgrade with its hash and set it as the new runtime256      const code = fs.readFileSync(NEW_PARA_WASM);257      const codeHash = blake2AsHex(code);258      await usingPlaygrounds(async (helper, privateKey) => {259        const superuser = await privateKey(SUPERUSER_KEY);260261        upgradingParas[paraId] = {version: getSpecVersion(helper.getApi()), upgraded: false};262263        console.log('--- Authorizing the parachain runtime upgrade \t---');264        let result = await helper.executeExtrinsic(265          superuser,266          'api.tx.sudo.sudoUncheckedWeight',267          [helper.constructApiCall('api.tx.parachainSystem.authorizeUpgrade', [codeHash, false]), {}],268        );269270        if(result.status == 'Fail') {271          console.error('Failed to authorize the upgrade:', result);272          return;273        }274275        console.log('--- Enacting the parachain runtime upgrade \t---');276        result = await helper.executeExtrinsic(277          superuser,278          'api.tx.sudo.sudoUncheckedWeight',279          [helper.constructApiCall('api.tx.parachainSystem.enactAuthorizedUpgrade', [`0x${code.toString('hex')}`]), {}],280        );281282        if(result.status == 'Fail') {283          console.error('Failed to upgrade the runtime:', result);284        }285      }, para.nodes[0].wsUri);286    }287288    // Check the upgrades of the parachains, first after the minimum code validation delay, and then after some block time increments289    let firstPass = true;290    for(let attempt = 0; attempt < 3 && !paraUpgradeCompleted; attempt++) {291      if(firstPass) {292        console.log('\nCode validation delay:', codeValidationDelayBlocks, 'blocks');293        console.log('🚥 Waiting for the minimum code validation delay before the parachain can upgrade...');294        await waitWithTimer(relayInfo.blockTime * codeValidationDelayBlocks);295        firstPass = false;296      } else {297        console.log('\n🚥 Waiting for a few blocks more to verify that the parachain upgrades are successful...');298        await waitWithTimer(PARACHAIN_BLOCK_TIME * 3);299      }300301      // Ping the parachains' nodes for new runtime versions302      let upgradeFailed = false;303      for(const paraId in network.paras) {304        if(upgradingParas[paraId].upgraded) continue;305306        const para = network.paras[paraId];307        // eslint-disable-next-line require-await308        await usingPlaygrounds(async (helper) => {309          const specVersion = getSpecVersion(helper.getApi());310311          if(specVersion != upgradingParas[paraId].version) {312            // eslint-disable-next-line no-useless-escape313            console.log(`\n\🛰️  Parachain ${paraId} has successfully upgraded from version ${upgradingParas[paraId].version} to ${specVersion}!`);314            upgradingParas[paraId].upgraded = true;315          } else {316            console.error(`\nParachain ${paraId} failed to upgrade from version ${upgradingParas[paraId].version}!`);317            upgradeFailed = true;318          }319        }, para.nodes[0].wsUri);320321        paraUpgradeCompleted = !upgradeFailed;322      }323    }324325    // Disable maintenance mode if present326    for(const paraId in network.paras) {327      await toggleMaintenanceMode(false, network.paras[paraId].nodes[0].wsUri);328    }329  } else {330    // If the relay did not need to be upgraded, it's already technically completed331    paraUpgradeCompleted = true;332  }333334  // await network.stop();335336  if(isUpgradeTesting) {337    if(paraUpgradeCompleted && relayUpgradeCompleted) {338      console.log("\n🛸 PARACHAINS' RUNTIME UPGRADE TESTING COMPLETE 🛸");339    } else {340      console.error("\n🚧 PARACHAINS' RUNTIME UPGRADE TESTING FAILED 🚧");341    }342  } else {343    console.log('🚀 ZOMBIENET RAISED 🚀');344  }345};346347raiseZombienet()/*.then(async () => await stop())*/.catch(async (e) => {348  console.error(e);349  await stop();350  process.exit(1);351});
after · tests/src/util/frankenstein.ts
1// Copyright 2019-2023 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 {ApiPromise} from '@polkadot/api';18import {blake2AsHex, cryptoWaitReady} from '@polkadot/util-crypto';19import zombie from '@zombienet/orchestrator/dist';20import {readNetworkConfig} from '@zombienet/utils/dist';21import {resolve} from 'path';22import {usingPlaygrounds} from '.';23import {migrations} from './frankensteinMigrate';24import fs from 'fs';2526const ZOMBIENET_CREDENTIALS = process.env.ZOMBIENET_CREDENTIALS || '../.env';27const NETWORK_CONFIG_FILE = process.argv[2] ?? '../launch-zombienet.toml';28const PARA_DIR = process.env.PARA_DIR || '../';29const RELAY_DIR = process.env.RELAY_DIR || '../../polkadot/';30const REPLICA_FROM = process.env.REPLICA_FROM || 'wss://ws-opal.unique.network:443';31const NEW_RELAY_BIN = process.env.NEW_RELAY_BIN;32const NEW_RELAY_WASM = process.env.NEW_RELAY_WASM;33const NEW_PARA_BIN = process.env.NEW_PARA_BIN;34const NEW_PARA_WASM = process.env.NEW_PARA_WASM;35const DESTINATION_SPEC_VERSION = process.env.DESTINATION_SPEC_VERSION!;36const PARACHAIN_BLOCK_TIME = 12_000;37const SUPERUSER_KEY = '//Alice';3839let network: zombie.Network | undefined;4041// Stop the network if it is running42const stop = async () => {43  await network?.stop();44};4546// Promise of a timeout47function delay(ms: number) {48  return new Promise(resolve => setTimeout(resolve, ms));49}5051// Countdown with time left on display52async function waitWithTimer(time: number) {53  const secondsTotal = Math.ceil(time / 1000);54  for(let i = secondsTotal; i > 0; i--) {55    // could also introduce hours, but wth56    const seconds = i % 60;57    const text = `Time left: ${Math.floor(i / 60)}:${seconds < 10 ? '0' + seconds : seconds}`;58    if(process.stdout.isTTY)59      process.stdout.write(text);60    else if(seconds % 10 == 0)61      console.log(text);62    await delay(1000);63    if(process.stdout.isTTY) {64      process.stdout.clearLine(0);65      process.stdout.cursorTo(0);66    }67  }68}6970// Get the runtime's current version71function getSpecVersion(api: ApiPromise): number {72  return (api.consts.system.version as any).specVersion.toNumber();73}7475// Get the required information on the relay chain76function getRelayInfo(api: ApiPromise): {specVersion: number, epochBlockLength: number, blockTime: number, epochTime: number} {77  const info = {78    specVersion: getSpecVersion(api),79    epochBlockLength: (api.consts.babe.epochDuration as any).toNumber(),80    blockTime: (api.consts.babe.expectedBlockTime as any).toNumber(),81    epochTime: 0,82  };83  info.epochTime = info.epochBlockLength * info.blockTime;84  return info;85}8687// Enable or disable maintenance mode if present on the chain88async function toggleMaintenanceMode(value: boolean, wsUri: string, retries = 5) {89  try {90    await usingPlaygrounds(async (helper, privateKey) => {91      const superuser = await privateKey(SUPERUSER_KEY);92      try {93        const toggle = value ? 'enable' : 'disable';94        await helper.getSudo().executeExtrinsic(superuser, `api.tx.maintenance.${toggle}`, []);95        console.log(`Maintenance mode ${value ? 'engaged' : 'disengaged'}.`);96      } catch (e) {97        console.error('Couldn\'t set maintenance mode. The maintenance pallet probably does not exist. Log:', e);98      }99    }, wsUri);100  } catch (error) {101    console.error(error);102    console.log('Trying for retry toggle maintanence mode');103    await delay(12_000);104    await toggleMaintenanceMode(value, wsUri, retries - 1);105  }106}107108async function skipIfAlreadyUpgraded() {109  await usingPlaygrounds(async (helper) => {110    const specVersion = await getSpecVersion(helper.getApi());111    if(`v${specVersion}` === DESTINATION_SPEC_VERSION) {112      console.log('\n🛸 Current version equal DESTINATION_SPEC_VERSION 🛸');113      console.log("\n🛸 PARACHAINS' RUNTIME UPGRADE TESTING COMPLETE 🛸");114    }115  }, REPLICA_FROM);116}117118const raiseZombienet = async (): Promise<void> => {119  await skipIfAlreadyUpgraded();120  const isUpgradeTesting = !!NEW_RELAY_BIN || !!NEW_RELAY_WASM || !!NEW_PARA_BIN || !!NEW_PARA_WASM;121  /*122  // If there is nothing to upgrade, what is the point123  if (!isUpgradeTesting) {124    console.warn('\nNeither the relay nor the parachain were selected for an upgrade! ' +125      'Please pass environment vars `NEW_RELAY_BIN`, `NEW_RELAY_WASM`, `NEW_PARA_BIN`, `NEW_PARA_WASM`.');126    process.exit(1);127  }128  */129130  // an unsavory practice, but very convenient, mwahahah131  process.env.PARA_DIR = PARA_DIR;132  process.env.RELAY_DIR = RELAY_DIR;133  process.env.REPLICA_FROM = REPLICA_FROM;134135  const configPath = resolve(NETWORK_CONFIG_FILE);136  const networkConfig = readNetworkConfig(configPath);137  // console.log(networkConfig);138  if(networkConfig.settings.provider !== 'native') {139    throw new Error(`Oh no! Expected native network, got ${networkConfig.settings.provider}.`);140  }141142  await cryptoWaitReady();143144  // Launch Zombienet!145  network = await zombie.start(ZOMBIENET_CREDENTIALS, networkConfig, {silent: false});146147  // Get the relay chain info like the epoch length and spec version148  // Then restart each parachain's binaries149  // // Stop and restart each node150  // // Send specified keys to parachain nodes in case the parachain requires it151  // If it is not needed to upgrade runtimes themselves, the job is done!152153  // Record some required information regarding the relay chain154  await network.relay[0].connectApi();155  let relayInfo = getRelayInfo((network.relay[0] as any).apiInstance!);156  await network.relay[0].apiInstance!.disconnect();157  if(isUpgradeTesting) {158    console.log('Relay stats:', relayInfo);159  }160161  // non-exported functionality of NativeClient162  const networkClient = (network.client as any);163164  if(NEW_RELAY_BIN) {165    console.log('\n🧶 Restarting relay nodes');166167    for(const [index, node] of network.relay.entries()) {168      await node.apiInstance?.disconnect();169170      console.log(`\n🚦 Starting timeout for the epoch change (node ${index + 1}/${network.relay.length})...`);171      await waitWithTimer(relayInfo.epochTime);172173      // Replace the node-starting command with the new binary174      const cmd = networkClient.processMap[node.name].cmd[0].split(' ')[0];175      networkClient.processMap[node.name].cmd = networkClient.processMap[node.name].cmd.map((arg: string) => arg.replace(cmd, NEW_RELAY_BIN));176177      await node.restart();178    }179180    console.log('\n🌒 All relay nodes restarted with the new binaries.');181  }182183  if(NEW_PARA_BIN) {184    for(const paraId in network.paras) {185      const para = network.paras[paraId];186      console.log(`\n🧶 Restarting collator nodes of parachain ${paraId}`);187188      for(const [_index, node] of para.nodes.entries()) {189        await node.apiInstance?.disconnect();190191        // Replace the node-starting command with the new binary192        const cmd = networkClient.processMap[node.name].cmd[0].split(' ')[0];193        networkClient.processMap[node.name].cmd = networkClient.processMap[node.name].cmd.map((arg: string) => arg.replace(cmd, NEW_PARA_BIN));194195        await node.restart();196        // applyaurakey?197        // Zombienet handles it on first-time node creation198      }199    }200201    console.log('\n🌗 All parachain collators restarted with the new binaries.');202  }203204  // Re-establish connection to the relay node and get the runtime upgrade validation delay for parachains205  // For the relay, connect and set the new runtime code206  // For each parachain, connect, authorize and upgrade its runtime207  // Ping the the chains for the runtime upgrade after the minimal time and then every few blocks208  // // For each parachain, re-connect and verify that the runtime upgrade is successful209210  let relayUpgradeCompleted = false, paraUpgradeCompleted = false;211212  if(NEW_RELAY_WASM) {213    const relayOldVersion = relayInfo.specVersion;214    console.log('\n🚦 Starting timeout for the next epoch before upgrading the relay runtime code...');215    await waitWithTimer(relayInfo.epochTime);216217    console.log('--- Upgrading the relay chain runtime \t---');218219    // Read the new WASM code and set it as the relay's new code220    const code = fs.readFileSync(NEW_RELAY_WASM).toString('hex');221    await usingPlaygrounds(async (helper, privateKey) => {222      const superuser = await privateKey(SUPERUSER_KEY);223224      const result = await helper.executeExtrinsic(225        superuser,226        'api.tx.sudo.sudoUncheckedWeight',227        [helper.constructApiCall('api.tx.system.setCode', [`0x${code}`]), {}],228      );229230      if(result.status == 'Fail') {231        console.error('Failed to upgrade the runtime:', result);232      }233234      // Get the updated information from the relay's new runtime235      relayInfo = getRelayInfo(helper.getApi());236    }, network.relay[0].wsUri);237238    if(relayOldVersion != relayInfo.specVersion) {239      // eslint-disable-next-line no-useless-escape240      console.log(`\n\🛰️ The relay has successfully upgraded from version ${relayOldVersion} to ${relayInfo.specVersion}!`);241      relayUpgradeCompleted = true;242    } else {243      console.error(`\nThe relay did not upgrade from version ${relayOldVersion}!`);244    }245  } else {246    // If the relay did not need to be upgraded, it's already technically completed247    relayUpgradeCompleted = true;248  }249250  if(NEW_PARA_WASM) {251    let codeValidationDelayBlocks = 0;252    const upgradingParas: {[id: string]: {version: number, upgraded: boolean}} = {};253    // Calculate the code validation delay of the relay chain,254    // so that we know how much to wait before the parachains can be upgraded after the extrinsic255    await usingPlaygrounds(async (helper) => {256      const {validationUpgradeDelay, minimumValidationUpgradeDelay} =257        (await helper.callRpc('api.query.configuration.activeConfig', [])).toJSON() as any;258259      codeValidationDelayBlocks = Math.max(validationUpgradeDelay ?? 0, minimumValidationUpgradeDelay ?? 0);260    }, network.relay[0].wsUri);261262    // Wait for the next epoch so that the parachains will start cooperating with the relay263    if(relayUpgradeCompleted && NEW_RELAY_WASM) {264      console.log('\n🚥 Starting timeout for the next epoch before upgrading the parachains code...');265      await waitWithTimer(relayInfo.epochTime);266    }267268    const migration = migrations[DESTINATION_SPEC_VERSION];269    console.log('⭐️⭐️⭐️ DESTINATION_SPEC_VERSION ⭐️⭐️⭐️', DESTINATION_SPEC_VERSION);270    for(const paraId in network.paras) {271      console.log(`\n--- Upgrading the runtime of parachain ${paraId} \t---`);272      const para = network.paras[paraId];273274      // Enable maintenance mode if present275      await toggleMaintenanceMode(true, para.nodes[0].wsUri);276      if(migration) {277        console.log('⭐️⭐️⭐️ Running pre-upgrade scripts... ⭐️⭐️⭐️');278        await migration.before();279      }280281      // Read the WASM code and authorize the upgrade with its hash and set it as the new runtime282      const code = fs.readFileSync(NEW_PARA_WASM);283      const codeHash = blake2AsHex(code);284      await usingPlaygrounds(async (helper, privateKey) => {285        const superuser = await privateKey(SUPERUSER_KEY);286287        upgradingParas[paraId] = {version: getSpecVersion(helper.getApi()), upgraded: false};288289        console.log('--- Authorizing the parachain runtime upgrade \t---');290        let result = await helper.executeExtrinsic(291          superuser,292          'api.tx.sudo.sudoUncheckedWeight',293          [helper.constructApiCall('api.tx.parachainSystem.authorizeUpgrade', [codeHash, false]), {}],294        );295296        if(result.status == 'Fail') {297          console.error('Failed to authorize the upgrade:', result);298          return;299        }300301        console.log('--- Enacting the parachain runtime upgrade \t---');302        result = await helper.executeExtrinsic(303          superuser,304          'api.tx.sudo.sudoUncheckedWeight',305          [helper.constructApiCall('api.tx.parachainSystem.enactAuthorizedUpgrade', [`0x${code.toString('hex')}`]), {}],306        );307308        if(result.status == 'Fail') {309          console.error('Failed to upgrade the runtime:', result);310        }311      }, para.nodes[0].wsUri);312    }313314    // Check the upgrades of the parachains, first after the minimum code validation delay, and then after some block time increments315    let firstPass = true;316    for(let attempt = 0; attempt < 3 && !paraUpgradeCompleted; attempt++) {317      if(firstPass) {318        console.log('\nCode validation delay:', codeValidationDelayBlocks, 'blocks');319        console.log('🚥 Waiting for the minimum code validation delay before the parachain can upgrade...');320        await waitWithTimer(relayInfo.blockTime * codeValidationDelayBlocks);321        firstPass = false;322      } else {323        console.log('\n🚥 Waiting for a few blocks more to verify that the parachain upgrades are successful...');324        await waitWithTimer(PARACHAIN_BLOCK_TIME * 3);325      }326327      // Ping the parachains' nodes for new runtime versions328      let upgradeFailed = false;329      for(const paraId in network.paras) {330        if(upgradingParas[paraId].upgraded) continue;331332        const para = network.paras[paraId];333        // eslint-disable-next-line require-await334        await usingPlaygrounds(async (helper) => {335          const specVersion = getSpecVersion(helper.getApi());336337          if(specVersion != upgradingParas[paraId].version) {338            // eslint-disable-next-line no-useless-escape339            console.log(`\n\🛰️  Parachain ${paraId} has successfully upgraded from version ${upgradingParas[paraId].version} to ${specVersion}!`);340            upgradingParas[paraId].upgraded = true;341          } else {342            console.error(`\nParachain ${paraId} failed to upgrade from version ${upgradingParas[paraId].version}!`);343            upgradeFailed = true;344          }345        }, para.nodes[0].wsUri);346347        paraUpgradeCompleted = !upgradeFailed;348      }349    }350351    // Disable maintenance mode if present352    for(const paraId in network.paras) {353      // TODO only if our parachain354      if(migration) {355        console.log('⭐️⭐️⭐️ Running post-upgrade scripts... ⭐️⭐️⭐️');356        await migration.after();357      }358      await toggleMaintenanceMode(false, network.paras[paraId].nodes[0].wsUri);359    }360  } else {361    // If the relay did not need to be upgraded, it's already technically completed362    paraUpgradeCompleted = true;363  }364365  // await network.stop();366367  if(isUpgradeTesting) {368    if(paraUpgradeCompleted && relayUpgradeCompleted) {369      console.log("\n🛸 PARACHAINS' RUNTIME UPGRADE TESTING COMPLETE 🛸");370    } else {371      console.error("\n🚧 PARACHAINS' RUNTIME UPGRADE TESTING FAILED 🚧");372    }373  } else {374    console.log('🚀 ZOMBIENET RAISED 🚀');375  }376};377378raiseZombienet()/*.then(async () => await stop())*/.catch(async (e) => {379  console.error(e);380  await stop();381  process.exit(1);382});
addedtests/src/util/frankensteinMigrate.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/util/frankensteinMigrate.ts
@@ -0,0 +1,9 @@
+import {migration as locksToFreezesMigration} from '../migrations/942057-appPromotion';
+export interface Migration {
+  before: () => Promise<void>,
+  after: () => Promise<void>,
+}
+
+export const migrations: {[key: string]: Migration} = {
+  'v942057': locksToFreezesMigration,
+};
modifiedtests/yarn.lockdiffbeforeafterboth
--- a/tests/yarn.lock
+++ b/tests/yarn.lock
@@ -3406,6 +3406,11 @@
   resolved "https://registry.yarnpkg.com/long/-/long-4.0.0.tgz#9a7b71cfb7d361a194ea555241c92f7468d5bf28"
   integrity sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA==
 
+lossless-json@^2.0.9:
+  version "2.0.9"
+  resolved "https://registry.yarnpkg.com/lossless-json/-/lossless-json-2.0.9.tgz#2e9a71a3dcbc6c59dee565e537b9084107b7fe37"
+  integrity sha512-PUfJ5foxULG1x/dXpSckmt0woBDqyq/WFoI885vEqjGwuP41K2EBYh2IT3zYx9dWqcTLIfXiCE5AjhF1jk9Sbg==
+
 loupe@^2.3.1:
   version "2.3.6"
   resolved "https://registry.yarnpkg.com/loupe/-/loupe-2.3.6.tgz#76e4af498103c532d1ecc9be102036a21f787b53"