git.delta.rocks / unique-network / refs/commits / 45fd3eb4b8bb

difftreelog

source

tests/src/util/frankenstein.ts13.2 KiBsourcehistory
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;3536let network: zombie.Network | undefined;3738// Stop the network if it is running39const stop = async () => {40  await network?.stop();41};4243// Promise of a timeout44function delay(ms: number) {45  return new Promise(resolve => setTimeout(resolve, ms));46}4748// Countdown with time left on display49async function waitWithTimer(time: number) {50  const secondsTotal = Math.ceil(time / 1000);51  for (let i = secondsTotal; i > 0; i--) {52    // could also introduce hours, but wth53    const seconds = i % 60;54    const text = `Time left: ${Math.floor(i / 60)}:${seconds < 10 ? '0' + seconds : seconds}`;55    if (process.stdout.isTTY)56      process.stdout.write(text);57    else if (seconds % 10 == 0)58      console.log(text);59    await delay(1000);60    if (process.stdout.isTTY) {61      process.stdout.clearLine(0);62      process.stdout.cursorTo(0);63    }64  }65}6667// Get the runtime's current version68function getSpecVersion(api: ApiPromise): number {69  return (api.consts.system.version as any).specVersion.toNumber();70}7172// Get the required information on the relay chain73function getRelayInfo(api: ApiPromise): {specVersion: number, epochBlockLength: number, blockTime: number, epochTime: number} {74  const info = {75    specVersion: getSpecVersion(api),76    epochBlockLength: (api.consts.babe.epochDuration as any).toNumber(),77    blockTime: (api.consts.babe.expectedBlockTime as any).toNumber(),78    epochTime: 0,79  };80  info.epochTime = info.epochBlockLength * info.blockTime;81  return info;82}8384// Enable or disable maintenance mode if present on the chain85async function toggleMaintenanceMode(value: boolean, wsUri: string) {86  await usingPlaygrounds(async (helper, privateKey) => {87    const superuser = await privateKey('//Alice');88    try {89      const toggle = value ? 'enable' : 'disable';90      await helper.getSudo().executeExtrinsic(superuser, `api.tx.maintenance.${toggle}`, []);91      console.log(`Maintenance mode ${value ? 'engaged' : 'disengaged'}.`);92    } catch (_) {93      console.error('Couldn\'t set maintenance mode. The maintenance pallet probably does not exist.');94    }95  }, wsUri);96}9798const raiseZombienet = async (): Promise<void> => {99  const upgradeTesting = !!NEW_RELAY_BIN || !!NEW_RELAY_WASM || !!NEW_RELAY_BIN && !!NEW_PARA_WASM;100  /*101  // If there is nothing to upgrade, what is the point102  if (!upgradeTesting) {103    console.warn('\nNeither the relay nor the parachain were selected for an upgrade! ' +104      'Please pass environment vars `NEW_RELAY_BIN`, `NEW_RELAY_WASM`, `NEW_PARA_BIN`, `NEW_PARA_WASM`.');105    process.exit(1);106  }107  */108109  // an unsavory practice, but very convenient, mwahahah110  process.env.PARA_DIR = PARA_DIR;111  process.env.RELAY_DIR = RELAY_DIR;112  process.env.REPLICA_FROM = REPLICA_FROM;113114  const configPath = resolve(NETWORK_CONFIG_FILE);115  const networkConfig = readNetworkConfig(configPath);116  // console.log(networkConfig);117  if (networkConfig.settings.provider !== 'native') {118    throw new Error(`Oh no! Expected native network, got ${networkConfig.settings.provider}.`);119  }120121  await cryptoWaitReady();122123  // Get the relay chain info like the epoch length and spec version124  // Then restart each parachain's binaries125  // // Stop and restart each node126  // // Send specified keys to parachain nodes in case the parachain requires it127  // If it is not needed to upgrade runtimes themselves, the job is done!128129  network = await zombie.start(ZOMBIENET_CREDENTIALS, networkConfig, {silent: false});130131  // Record some required information regarding the relay chain132  await network.relay[0].connectApi();133  let relayInfo = getRelayInfo(network.relay[0].apiInstance!);134  await network.relay[0].apiInstance?.disconnect();135  console.log(relayInfo);136137  // non-exported functionality of NativeClient138  const networkClient = (network.client as any);139140  if (NEW_RELAY_BIN) {141    console.log('\n🧶 Restarting relay nodes');142143    for (const [index, node] of network.relay.entries()) {144      await node.apiInstance?.disconnect();145146      console.log(`\n🚦 Starting timeout for the epoch change (node ${index + 1}/${network.relay.length})...`);147      await waitWithTimer(relayInfo.epochTime);148149      // Replace the node-starting command with the new binary150      const cmd = networkClient.processMap[node.name].cmd[0].split(' ')[0];151      networkClient.processMap[node.name].cmd = networkClient.processMap[node.name].cmd.map((arg: string) => arg.replace(cmd, NEW_RELAY_BIN));152153      await node.restart();154    }155156    console.log('\n🌒 All relay nodes restarted with the new binaries.');157  }158159  if (NEW_PARA_BIN) {160    for (const paraId in network.paras) {161      const para = network.paras[paraId];162      console.log(`\n🧶 Restarting collator nodes of parachain ${paraId}`);163164      for (const [_index, node] of para.nodes.entries()) {165        await node.apiInstance?.disconnect();166167        // Replace the node-starting command with the new binary168        const cmd = networkClient.processMap[node.name].cmd[0].split(' ')[0];169        networkClient.processMap[node.name].cmd = networkClient.processMap[node.name].cmd.map((arg: string) => arg.replace(cmd, NEW_PARA_BIN));170171        await node.restart();172        // applyaurakey?173      }174    }175176    console.log('\n🌗 All parachain collators restarted with the new binaries.');177  }178179  // Re-establish connection to the relay node and get the runtime upgrade validation delay for parachains180  // For the relay, connect and set the new runtime code181  // For each parachain, connect, authorize and upgrade its runtime182  // Ping the the chains for the runtime upgrade after the minimal time and then every few blocks183  // // For each parachain, re-connect and verify that the runtime upgrade is successful184185  let relayUpgradeCompleted = false, paraUpgradeCompleted = false;186187  if (NEW_RELAY_WASM) {188    const relayOldVersion = relayInfo.specVersion;189    console.log('\n🚦 Starting timeout for the next epoch before upgrading the relay runtime code...');190    await waitWithTimer(relayInfo.epochTime);191192    console.log('--- Upgrading the relay chain runtime \t---');193194    // Read the new WASM code and set it as the relay's new code195    const code = fs.readFileSync(NEW_RELAY_WASM).toString('hex');196    await usingPlaygrounds(async (helper, privateKey) => {197      const superuser = await privateKey('//Alice');198199      await helper.executeExtrinsic(200        superuser,201        'api.tx.sudo.sudoUncheckedWeight',202        [helper.constructApiCall('api.tx.system.setCode', [`0x${code}`]), 0],203      );204205      // Get the updated information from the relay's new runtime206      relayInfo = getRelayInfo(helper.getApi());207    }, network.relay[0].wsUri);208209    if (relayOldVersion != relayInfo.specVersion) {210      // eslint-disable-next-line no-useless-escape211      console.log(`\n\🛰️ The relay has successfully upgraded from version ${relayOldVersion} to ${relayInfo.specVersion}!`);212      relayUpgradeCompleted = true;213    } else {214      console.error(`\nThe relay did not upgrade from version ${relayOldVersion}!`);215    }216  } else {217    // If the relay did not need to be upgraded, it's already technically completed218    relayUpgradeCompleted = true;219  }220221  if (NEW_PARA_WASM) {222    let codeValidationDelayBlocks = 0;223    const upgradingParas: {[id: string]: {version: number, upgraded: boolean}} = {};224    // Calculate the code validation delay of the relay chain,225    // so that we know how much to wait before the parachains can be upgraded after the extrinsic226    await usingPlaygrounds(async (helper) => {227      const {validationUpgradeDelay, minimumValidationUpgradeDelay} =228        (await helper.callRpc('api.query.configuration.activeConfig', [])).toJSON() as any;229230      codeValidationDelayBlocks = Math.max(validationUpgradeDelay ?? 0, minimumValidationUpgradeDelay ?? 0);231    }, network.relay[0].wsUri);232233    // Wait for the next epoch so that the parachains will start cooperating with the relay234    //if (relayUpgradeCompleted) {235    console.log('\n🚥 Starting timeout for the next epoch before upgrading the parachains code...');236    await waitWithTimer(relayInfo.epochTime);237    //}238239    for (const paraId in network.paras) {240      console.log(`\n--- Upgrading the runtime of parachain ${paraId} \t---`);241      const para = network.paras[paraId];242243      // Enable maintenance mode if present244      await toggleMaintenanceMode(true, para.nodes[0].wsUri);245246      // Read the WASM code and authorize the upgrade with its hash and set it as the new runtime247      const code = fs.readFileSync(NEW_PARA_WASM);248      const codeHash = blake2AsHex(code);249      await usingPlaygrounds(async (helper, privateKey) => {250        const superuser = await privateKey('//Alice');251252        upgradingParas[paraId] = {version: getSpecVersion(helper.getApi()), upgraded: false};253254        console.log('--- Authorizing the parachain runtime upgrade \t---');255        await helper.executeExtrinsic(256          superuser,257          'api.tx.sudo.sudoUncheckedWeight',258          [helper.constructApiCall('api.tx.parachainSystem.authorizeUpgrade', [codeHash]), 0],259        );260261        console.log('--- Enacting the parachain runtime upgrade \t---');262        await helper.executeExtrinsic(263          superuser,264          'api.tx.sudo.sudoUncheckedWeight',265          [helper.constructApiCall('api.tx.parachainSystem.enactAuthorizedUpgrade', [`0x${code.toString('hex')}`]), 0],266        );267      }, para.nodes[0].wsUri);268    }269270    // Check the upgrades of the parachains, first after the minimum code validation delay, and then after some block time increments271    let firstPass = true;272    for (let attempt = 0; attempt < 3 && !paraUpgradeCompleted; attempt++) {273      if (firstPass) {274        console.log('\nCode validation delay:', codeValidationDelayBlocks, 'blocks');275        console.log('🚥 Waiting for the minimum code validation delay before the parachain can upgrade...');276        await waitWithTimer(relayInfo.blockTime * codeValidationDelayBlocks);277        firstPass = false;278      } else {279        console.log('\n🚥 Waiting for a few blocks more to verify that the parachain upgrades are successful...');280        await waitWithTimer(PARACHAIN_BLOCK_TIME * 3);281      }282283      // Ping the parachains' nodes for new runtime versions284      let upgradeFailed = false;285      for (const paraId in network.paras) {286        if (upgradingParas[paraId].upgraded) continue;287288        const para = network.paras[paraId];289        // eslint-disable-next-line require-await290        await usingPlaygrounds(async (helper) => {291          const specVersion = getSpecVersion(helper.getApi());292293          if (specVersion != upgradingParas[paraId].version) {294            // eslint-disable-next-line no-useless-escape295            console.log(`\n\🛰️  Parachain ${paraId} has successfully upgraded from version ${upgradingParas[paraId].version} to ${specVersion}!`);296            upgradingParas[paraId].upgraded = true;297          } else {298            console.error(`\nParachain ${paraId} failed to upgrade from version ${upgradingParas[paraId].version}!`);299            upgradeFailed = true;300          }301        }, para.nodes[0].wsUri);302303        paraUpgradeCompleted = !upgradeFailed;304      }305    }306307    // Disable maintenance mode if present308    for (const paraId in network.paras) {309      await toggleMaintenanceMode(false, network.paras[paraId].nodes[0].wsUri);310    }311  } else {312    // If the relay did not need to be upgraded, it's already technically completed313    paraUpgradeCompleted = true;314  }315316  // await network.stop();317318  if (upgradeTesting) {319    if (paraUpgradeCompleted && relayUpgradeCompleted) {320      console.log("\n🛸 PARACHAINS' RUNTIME UPGRADE TESTING COMPLETE 🛸");321    } else {322      console.error("\n🚧 PARACHAINS' RUNTIME UPGRADE TESTING FAILED 🚧");323    }324  }325};326327raiseZombienet()/*.then(async () => await stop())*/.catch(async (e) => {328  console.error(e);329  await stop();330  process.exit(1);331});