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('⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️');267 console.log('⭐️⭐️⭐️ Running pre-upgrade scripts... ⭐️⭐️⭐️');268 console.log('⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️');269 await migration.before();270 }271272 273 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 306 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 319 let upgradeFailed = false;320 for(const paraId in network.paras) {321 if(upgradingParas[paraId].upgraded) continue;322323 const para = network.paras[paraId];324 325 await usingPlaygrounds(async (helper) => {326 const specVersion = getSpecVersion(helper.getApi());327328 if(specVersion != upgradingParas[paraId].version) {329 330 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 343 for(const paraId in network.paras) {344 345 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 353 paraUpgradeCompleted = true;354 }355356 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().catch(async (e) => {370 console.error(e);371 await stop();372 process.exit(1);373});