git.delta.rocks / unique-network / refs/commits / fc3f880a9eee

difftreelog

source

tests/src/util/frankenstein.ts15.1 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 {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}107108const raiseZombienet = async (): Promise<void> => {109  const isUpgradeTesting = !!NEW_RELAY_BIN || !!NEW_RELAY_WASM || !!NEW_PARA_BIN || !!NEW_PARA_WASM;110  /*111  // If there is nothing to upgrade, what is the point112  if (!isUpgradeTesting) {113    console.warn('\nNeither the relay nor the parachain were selected for an upgrade! ' +114      'Please pass environment vars `NEW_RELAY_BIN`, `NEW_RELAY_WASM`, `NEW_PARA_BIN`, `NEW_PARA_WASM`.');115    process.exit(1);116  }117  */118119  // an unsavory practice, but very convenient, mwahahah120  process.env.PARA_DIR = PARA_DIR;121  process.env.RELAY_DIR = RELAY_DIR;122  process.env.REPLICA_FROM = REPLICA_FROM;123124  const configPath = resolve(NETWORK_CONFIG_FILE);125  const networkConfig = readNetworkConfig(configPath);126  // console.log(networkConfig);127  if(networkConfig.settings.provider !== 'native') {128    throw new Error(`Oh no! Expected native network, got ${networkConfig.settings.provider}.`);129  }130131  await cryptoWaitReady();132133  // Launch Zombienet!134  network = await zombie.start(ZOMBIENET_CREDENTIALS, networkConfig, {silent: false});135136  // Get the relay chain info like the epoch length and spec version137  // Then restart each parachain's binaries138  // // Stop and restart each node139  // // Send specified keys to parachain nodes in case the parachain requires it140  // If it is not needed to upgrade runtimes themselves, the job is done!141142  // Record some required information regarding the relay chain143  await network.relay[0].connectApi();144  let relayInfo = getRelayInfo((network.relay[0] as any).apiInstance!);145  await network.relay[0].apiInstance!.disconnect();146  if(isUpgradeTesting) {147    console.log('Relay stats:', relayInfo);148  }149150  // non-exported functionality of NativeClient151  const networkClient = (network.client as any);152153  if(NEW_RELAY_BIN) {154    console.log('\n🧶 Restarting relay nodes');155156    for(const [index, node] of network.relay.entries()) {157      await node.apiInstance?.disconnect();158159      console.log(`\n🚦 Starting timeout for the epoch change (node ${index + 1}/${network.relay.length})...`);160      await waitWithTimer(relayInfo.epochTime);161162      // Replace the node-starting command with the new binary163      const cmd = networkClient.processMap[node.name].cmd[0].split(' ')[0];164      networkClient.processMap[node.name].cmd = networkClient.processMap[node.name].cmd.map((arg: string) => arg.replace(cmd, NEW_RELAY_BIN));165166      await node.restart();167    }168169    console.log('\n🌒 All relay nodes restarted with the new binaries.');170  }171172  if(NEW_PARA_BIN) {173    for(const paraId in network.paras) {174      const para = network.paras[paraId];175      console.log(`\n🧶 Restarting collator nodes of parachain ${paraId}`);176177      for(const [_index, node] of para.nodes.entries()) {178        await node.apiInstance?.disconnect();179180        // Replace the node-starting command with the new binary181        const cmd = networkClient.processMap[node.name].cmd[0].split(' ')[0];182        networkClient.processMap[node.name].cmd = networkClient.processMap[node.name].cmd.map((arg: string) => arg.replace(cmd, NEW_PARA_BIN));183184        await node.restart();185        // applyaurakey?186        // Zombienet handles it on first-time node creation187      }188    }189190    console.log('\n🌗 All parachain collators restarted with the new binaries.');191  }192193  // Re-establish connection to the relay node and get the runtime upgrade validation delay for parachains194  // For the relay, connect and set the new runtime code195  // For each parachain, connect, authorize and upgrade its runtime196  // Ping the the chains for the runtime upgrade after the minimal time and then every few blocks197  // // For each parachain, re-connect and verify that the runtime upgrade is successful198199  let relayUpgradeCompleted = false, paraUpgradeCompleted = false;200201  if(NEW_RELAY_WASM) {202    const relayOldVersion = relayInfo.specVersion;203    console.log('\n🚦 Starting timeout for the next epoch before upgrading the relay runtime code...');204    await waitWithTimer(relayInfo.epochTime);205206    console.log('--- Upgrading the relay chain runtime \t---');207208    // Read the new WASM code and set it as the relay's new code209    const code = fs.readFileSync(NEW_RELAY_WASM).toString('hex');210    await usingPlaygrounds(async (helper, privateKey) => {211      const superuser = await privateKey(SUPERUSER_KEY);212213      const result = await helper.executeExtrinsic(214        superuser,215        'api.tx.sudo.sudoUncheckedWeight',216        [helper.constructApiCall('api.tx.system.setCode', [`0x${code}`]), {}],217      );218219      if(result.status == 'Fail') {220        console.error('Failed to upgrade the runtime:', result);221      }222223      // Get the updated information from the relay's new runtime224      relayInfo = getRelayInfo(helper.getApi());225    }, network.relay[0].wsUri);226227    if(relayOldVersion != relayInfo.specVersion) {228      // eslint-disable-next-line no-useless-escape229      console.log(`\n\🛰️ The relay has successfully upgraded from version ${relayOldVersion} to ${relayInfo.specVersion}!`);230      relayUpgradeCompleted = true;231    } else {232      console.error(`\nThe relay did not upgrade from version ${relayOldVersion}!`);233    }234  } else {235    // If the relay did not need to be upgraded, it's already technically completed236    relayUpgradeCompleted = true;237  }238239  if(NEW_PARA_WASM) {240    let codeValidationDelayBlocks = 0;241    const upgradingParas: {[id: string]: {version: number, upgraded: boolean}} = {};242    // Calculate the code validation delay of the relay chain,243    // so that we know how much to wait before the parachains can be upgraded after the extrinsic244    await usingPlaygrounds(async (helper) => {245      const {validationUpgradeDelay, minimumValidationUpgradeDelay} =246        (await helper.callRpc('api.query.configuration.activeConfig', [])).toJSON() as any;247248      codeValidationDelayBlocks = Math.max(validationUpgradeDelay ?? 0, minimumValidationUpgradeDelay ?? 0);249    }, network.relay[0].wsUri);250251    // Wait for the next epoch so that the parachains will start cooperating with the relay252    if(relayUpgradeCompleted && NEW_RELAY_WASM) {253      console.log('\n🚥 Starting timeout for the next epoch before upgrading the parachains code...');254      await waitWithTimer(relayInfo.epochTime);255    }256257    const migration = migrations[DESTINATION_SPEC_VERSION];258    console.log('⭐️⭐️⭐️ DESTINATION_SPEC_VERSION ⭐️⭐️⭐️', DESTINATION_SPEC_VERSION);259    for(const paraId in network.paras) {260      console.log(`\n--- Upgrading the runtime of parachain ${paraId} \t---`);261      const para = network.paras[paraId];262263      // Enable maintenance mode if present264      await toggleMaintenanceMode(true, para.nodes[0].wsUri);265      if(migration) {266        console.log('⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️');267        console.log('⭐️⭐️⭐️ Running pre-upgrade scripts... ⭐️⭐️⭐️');268        console.log('⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️');269        await migration.before();270      }271272      // Read the WASM code and authorize the upgrade with its hash and set it as the new runtime273      const code = fs.readFileSync(NEW_PARA_WASM);274      const codeHash = blake2AsHex(code);275      await usingPlaygrounds(async (helper, privateKey) => {276        const superuser = await privateKey(SUPERUSER_KEY);277278        upgradingParas[paraId] = {version: getSpecVersion(helper.getApi()), upgraded: false};279280        console.log('--- Authorizing the parachain runtime upgrade \t---');281        let result = await helper.executeExtrinsic(282          superuser,283          'api.tx.sudo.sudoUncheckedWeight',284          [helper.constructApiCall('api.tx.parachainSystem.authorizeUpgrade', [codeHash, false]), {}],285        );286287        if(result.status == 'Fail') {288          console.error('Failed to authorize the upgrade:', result);289          return;290        }291292        console.log('--- Enacting the parachain runtime upgrade \t---');293        result = await helper.executeExtrinsic(294          superuser,295          'api.tx.sudo.sudoUncheckedWeight',296          [helper.constructApiCall('api.tx.parachainSystem.enactAuthorizedUpgrade', [`0x${code.toString('hex')}`]), {}],297        );298299        if(result.status == 'Fail') {300          console.error('Failed to upgrade the runtime:', result);301        }302      }, para.nodes[0].wsUri);303    }304305    // Check the upgrades of the parachains, first after the minimum code validation delay, and then after some block time increments306    let firstPass = true;307    for(let attempt = 0; attempt < 3 && !paraUpgradeCompleted; attempt++) {308      if(firstPass) {309        console.log('\nCode validation delay:', codeValidationDelayBlocks, 'blocks');310        console.log('🚥 Waiting for the minimum code validation delay before the parachain can upgrade...');311        await waitWithTimer(relayInfo.blockTime * codeValidationDelayBlocks);312        firstPass = false;313      } else {314        console.log('\n🚥 Waiting for a few blocks more to verify that the parachain upgrades are successful...');315        await waitWithTimer(PARACHAIN_BLOCK_TIME * 3);316      }317318      // Ping the parachains' nodes for new runtime versions319      let upgradeFailed = false;320      for(const paraId in network.paras) {321        if(upgradingParas[paraId].upgraded) continue;322323        const para = network.paras[paraId];324        // eslint-disable-next-line require-await325        await usingPlaygrounds(async (helper) => {326          const specVersion = getSpecVersion(helper.getApi());327328          if(specVersion != upgradingParas[paraId].version) {329            // eslint-disable-next-line no-useless-escape330            console.log(`\n\🛰️  Parachain ${paraId} has successfully upgraded from version ${upgradingParas[paraId].version} to ${specVersion}!`);331            upgradingParas[paraId].upgraded = true;332          } else {333            console.error(`\nParachain ${paraId} failed to upgrade from version ${upgradingParas[paraId].version}!`);334            upgradeFailed = true;335          }336        }, para.nodes[0].wsUri);337338        paraUpgradeCompleted = !upgradeFailed;339      }340    }341342    // Disable maintenance mode if present343    for(const paraId in network.paras) {344      // TODO only if our parachain345      if(migration) {346        console.log('⭐️⭐️⭐️ Running post-upgrade scripts... ⭐️⭐️⭐️');347        await migration.after();348      }349      await toggleMaintenanceMode(false, network.paras[paraId].nodes[0].wsUri);350    }351  } else {352    // If the relay did not need to be upgraded, it's already technically completed353    paraUpgradeCompleted = true;354  }355356  // await network.stop();357358  if(isUpgradeTesting) {359    if(paraUpgradeCompleted && relayUpgradeCompleted) {360      console.log("\n🛸 PARACHAINS' RUNTIME UPGRADE TESTING COMPLETE 🛸");361    } else {362      console.error("\n🚧 PARACHAINS' RUNTIME UPGRADE TESTING FAILED 🚧");363    }364  } else {365    console.log('🚀 ZOMBIENET RAISED 🚀');366  }367};368369raiseZombienet()/*.then(async () => await stop())*/.catch(async (e) => {370  console.error(e);371  await stop();372  process.exit(1);373});