1234567891011121314151617import {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;404142const stop = async () => {43 await network?.stop();44};454647function delay(ms: number) {48 return new Promise(resolve => setTimeout(resolve, ms));49}505152async function waitWithTimer(time: number) {53 const secondsTotal = Math.ceil(time / 1000);54 for(let i = secondsTotal; i > 0; i--) {55 56 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}697071function getSpecVersion(api: ApiPromise): number {72 return (api.consts.system.version as any).specVersion.toNumber();73}747576function 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}868788async 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 111112113114115116117118119 120 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 127 if(networkConfig.settings.provider !== 'native') {128 throw new Error(`Oh no! Expected native network, got ${networkConfig.settings.provider}.`);129 }130131 await cryptoWaitReady();132133 134 network = await zombie.start(ZOMBIENET_CREDENTIALS, networkConfig, {silent: false});135136 137 138 139 140 141142 143 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 151 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 163 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 181 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 186 187 }188 }189190 console.log('\n🌗 All parachain collators restarted with the new binaries.');191 }192193 194 195 196 197 198199 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 209 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 224 relayInfo = getRelayInfo(helper.getApi());225 }, network.relay[0].wsUri);226227 if(relayOldVersion != relayInfo.specVersion) {228 229 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 236 relayUpgradeCompleted = true;237 }238239 if(NEW_PARA_WASM) {240 let codeValidationDelayBlocks = 0;241 const upgradingParas: {[id: string]: {version: number, upgraded: boolean}} = {};242 243 244 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 252 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 264 await toggleMaintenanceMode(true, para.nodes[0].wsUri);265 if(migration) {266 console.log('⭐️⭐️⭐️ Running pre-upgrade scripts... ⭐️⭐️⭐️');267 await migration.before();268 }269270 271 const code = fs.readFileSync(NEW_PARA_WASM);272 const codeHash = blake2AsHex(code);273 await usingPlaygrounds(async (helper, privateKey) => {274 const superuser = await privateKey(SUPERUSER_KEY);275276 upgradingParas[paraId] = {version: getSpecVersion(helper.getApi()), upgraded: false};277278 console.log('--- Authorizing the parachain runtime upgrade \t---');279 let result = await helper.executeExtrinsic(280 superuser,281 'api.tx.sudo.sudoUncheckedWeight',282 [helper.constructApiCall('api.tx.parachainSystem.authorizeUpgrade', [codeHash, false]), {}],283 );284285 if(result.status == 'Fail') {286 console.error('Failed to authorize the upgrade:', result);287 return;288 }289290 console.log('--- Enacting the parachain runtime upgrade \t---');291 result = await helper.executeExtrinsic(292 superuser,293 'api.tx.sudo.sudoUncheckedWeight',294 [helper.constructApiCall('api.tx.parachainSystem.enactAuthorizedUpgrade', [`0x${code.toString('hex')}`]), {}],295 );296297 if(result.status == 'Fail') {298 console.error('Failed to upgrade the runtime:', result);299 }300 }, para.nodes[0].wsUri);301 }302303 304 let firstPass = true;305 for(let attempt = 0; attempt < 3 && !paraUpgradeCompleted; attempt++) {306 if(firstPass) {307 console.log('\nCode validation delay:', codeValidationDelayBlocks, 'blocks');308 console.log('🚥 Waiting for the minimum code validation delay before the parachain can upgrade...');309 await waitWithTimer(relayInfo.blockTime * codeValidationDelayBlocks);310 firstPass = false;311 } else {312 console.log('\n🚥 Waiting for a few blocks more to verify that the parachain upgrades are successful...');313 await waitWithTimer(PARACHAIN_BLOCK_TIME * 3);314 }315316 317 let upgradeFailed = false;318 for(const paraId in network.paras) {319 if(upgradingParas[paraId].upgraded) continue;320321 const para = network.paras[paraId];322 323 await usingPlaygrounds(async (helper) => {324 const specVersion = getSpecVersion(helper.getApi());325326 if(specVersion != upgradingParas[paraId].version) {327 328 console.log(`\n\🛰️ Parachain ${paraId} has successfully upgraded from version ${upgradingParas[paraId].version} to ${specVersion}!`);329 upgradingParas[paraId].upgraded = true;330 } else {331 console.error(`\nParachain ${paraId} failed to upgrade from version ${upgradingParas[paraId].version}!`);332 upgradeFailed = true;333 }334 }, para.nodes[0].wsUri);335336 paraUpgradeCompleted = !upgradeFailed;337 }338 }339340 341 for(const paraId in network.paras) {342 343 if(migration) {344 console.log('⭐️⭐️⭐️ Running post-upgrade scripts... ⭐️⭐️⭐️');345 await migration.after();346 }347 await toggleMaintenanceMode(false, network.paras[paraId].nodes[0].wsUri);348 }349 } else {350 351 paraUpgradeCompleted = true;352 }353354 355356 if(isUpgradeTesting) {357 if(paraUpgradeCompleted && relayUpgradeCompleted) {358 console.log("\n🛸 PARACHAINS' RUNTIME UPGRADE TESTING COMPLETE 🛸");359 } else {360 console.error("\n🚧 PARACHAINS' RUNTIME UPGRADE TESTING FAILED 🚧");361 }362 } else {363 console.log('🚀 ZOMBIENET RAISED 🚀');364 }365};366367raiseZombienet().catch(async (e) => {368 console.error(e);369 await stop();370 process.exit(1);371});