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}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 122123124125126127128129130 131 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 138 if(networkConfig.settings.provider !== 'native') {139 throw new Error(`Oh no! Expected native network, got ${networkConfig.settings.provider}.`);140 }141142 await cryptoWaitReady();143144 145 network = await zombie.start(ZOMBIENET_CREDENTIALS, networkConfig, {silent: false});146147 148 149 150 151 152153 154 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 162 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 174 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 192 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 197 198 }199 }200201 console.log('\n🌗 All parachain collators restarted with the new binaries.');202 }203204 205 206 207 208 209210 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 220 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 235 relayInfo = getRelayInfo(helper.getApi());236 }, network.relay[0].wsUri);237238 if(relayOldVersion != relayInfo.specVersion) {239 240 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 247 relayUpgradeCompleted = true;248 }249250 if(NEW_PARA_WASM) {251 let codeValidationDelayBlocks = 0;252 const upgradingParas: {[id: string]: {version: number, upgraded: boolean}} = {};253 254 255 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 263 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 275 await toggleMaintenanceMode(true, para.nodes[0].wsUri);276 if(migration) {277 console.log('⭐️⭐️⭐️ Running pre-upgrade scripts... ⭐️⭐️⭐️');278 await migration.before();279 }280281 282 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 315 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 328 let upgradeFailed = false;329 for(const paraId in network.paras) {330 if(upgradingParas[paraId].upgraded) continue;331332 const para = network.paras[paraId];333 334 await usingPlaygrounds(async (helper) => {335 const specVersion = getSpecVersion(helper.getApi());336337 if(specVersion != upgradingParas[paraId].version) {338 339 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 352 for(const paraId in network.paras) {353 354 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 362 paraUpgradeCompleted = true;363 }364365 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().catch(async (e) => {379 console.error(e);380 await stop();381 process.exit(1);382});