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) {89 await usingPlaygrounds(async (helper, privateKey) => {90 const superuser = await privateKey(SUPERUSER_KEY);91 try {92 const toggle = value ? 'enable' : 'disable';93 await helper.getSudo().executeExtrinsic(superuser, `api.tx.maintenance.${toggle}`, []);94 console.log(`Maintenance mode ${value ? 'engaged' : 'disengaged'}.`);95 } catch (e) {96 console.error('Couldn\'t set maintenance mode. The maintenance pallet probably does not exist. Log:', e);97 }98 }, wsUri);99}100101const raiseZombienet = async (): Promise<void> => {102 const isUpgradeTesting = !!NEW_RELAY_BIN || !!NEW_RELAY_WASM || !!NEW_PARA_BIN || !!NEW_PARA_WASM;103 104105106107108109110111112 113 process.env.PARA_DIR = PARA_DIR;114 process.env.RELAY_DIR = RELAY_DIR;115 process.env.REPLICA_FROM = REPLICA_FROM;116117 const configPath = resolve(NETWORK_CONFIG_FILE);118 const networkConfig = readNetworkConfig(configPath);119 120 if(networkConfig.settings.provider !== 'native') {121 throw new Error(`Oh no! Expected native network, got ${networkConfig.settings.provider}.`);122 }123124 await cryptoWaitReady();125126 127 network = await zombie.start(ZOMBIENET_CREDENTIALS, networkConfig, {silent: false});128129 130 131 132 133 134135 136 await network.relay[0].connectApi();137 let relayInfo = getRelayInfo((network.relay[0] as any).apiInstance!);138 await network.relay[0].apiInstance!.disconnect();139 if(isUpgradeTesting) {140 console.log('Relay stats:', relayInfo);141 }142143 144 const networkClient = (network.client as any);145146 if(NEW_RELAY_BIN) {147 console.log('\n🧶 Restarting relay nodes');148149 for(const [index, node] of network.relay.entries()) {150 await node.apiInstance?.disconnect();151152 console.log(`\n🚦 Starting timeout for the epoch change (node ${index + 1}/${network.relay.length})...`);153 await waitWithTimer(relayInfo.epochTime);154155 156 const cmd = networkClient.processMap[node.name].cmd[0].split(' ')[0];157 networkClient.processMap[node.name].cmd = networkClient.processMap[node.name].cmd.map((arg: string) => arg.replace(cmd, NEW_RELAY_BIN));158159 await node.restart();160 }161162 console.log('\n🌒 All relay nodes restarted with the new binaries.');163 }164165 if(NEW_PARA_BIN) {166 for(const paraId in network.paras) {167 const para = network.paras[paraId];168 console.log(`\n🧶 Restarting collator nodes of parachain ${paraId}`);169170 for(const [_index, node] of para.nodes.entries()) {171 await node.apiInstance?.disconnect();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_PARA_BIN));176177 await node.restart();178 179 180 }181 }182183 console.log('\n🌗 All parachain collators restarted with the new binaries.');184 }185186 187 188 189 190 191192 let relayUpgradeCompleted = false, paraUpgradeCompleted = false;193194 if(NEW_RELAY_WASM) {195 const relayOldVersion = relayInfo.specVersion;196 console.log('\n🚦 Starting timeout for the next epoch before upgrading the relay runtime code...');197 await waitWithTimer(relayInfo.epochTime);198199 console.log('--- Upgrading the relay chain runtime \t---');200201 202 const code = fs.readFileSync(NEW_RELAY_WASM).toString('hex');203 await usingPlaygrounds(async (helper, privateKey) => {204 const superuser = await privateKey(SUPERUSER_KEY);205206 const result = await helper.executeExtrinsic(207 superuser,208 'api.tx.sudo.sudoUncheckedWeight',209 [helper.constructApiCall('api.tx.system.setCode', [`0x${code}`]), {}],210 );211212 if(result.status == 'Fail') {213 console.error('Failed to upgrade the runtime:', result);214 }215216 217 relayInfo = getRelayInfo(helper.getApi());218 }, network.relay[0].wsUri);219220 if(relayOldVersion != relayInfo.specVersion) {221 222 console.log(`\n\🛰️ The relay has successfully upgraded from version ${relayOldVersion} to ${relayInfo.specVersion}!`);223 relayUpgradeCompleted = true;224 } else {225 console.error(`\nThe relay did not upgrade from version ${relayOldVersion}!`);226 }227 } else {228 229 relayUpgradeCompleted = true;230 }231232 if(NEW_PARA_WASM) {233 let codeValidationDelayBlocks = 0;234 const upgradingParas: {[id: string]: {version: number, upgraded: boolean}} = {};235 236 237 await usingPlaygrounds(async (helper) => {238 const {validationUpgradeDelay, minimumValidationUpgradeDelay} =239 (await helper.callRpc('api.query.configuration.activeConfig', [])).toJSON() as any;240241 codeValidationDelayBlocks = Math.max(validationUpgradeDelay ?? 0, minimumValidationUpgradeDelay ?? 0);242 }, network.relay[0].wsUri);243244 245 if(relayUpgradeCompleted && NEW_RELAY_WASM) {246 console.log('\n🚥 Starting timeout for the next epoch before upgrading the parachains code...');247 await waitWithTimer(relayInfo.epochTime);248 }249250 const migration = migrations[DESTINATION_SPEC_VERSION];251 console.log('⭐️⭐️⭐️ DESTINATION_SPEC_VERSION ⭐️⭐️⭐️', DESTINATION_SPEC_VERSION);252 for(const paraId in network.paras) {253 console.log(`\n--- Upgrading the runtime of parachain ${paraId} \t---`);254 const para = network.paras[paraId];255256 257 await toggleMaintenanceMode(true, para.nodes[0].wsUri);258 if(migration) {259 console.log('⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️');260 console.log('⭐️⭐️⭐️ Running pre-upgrade scripts... ⭐️⭐️⭐️');261 console.log('⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️');262 await migration.before();263 }264265 266 const code = fs.readFileSync(NEW_PARA_WASM);267 const codeHash = blake2AsHex(code);268 await usingPlaygrounds(async (helper, privateKey) => {269 const superuser = await privateKey(SUPERUSER_KEY);270271 upgradingParas[paraId] = {version: getSpecVersion(helper.getApi()), upgraded: false};272273 console.log('--- Authorizing the parachain runtime upgrade \t---');274 let result = await helper.executeExtrinsic(275 superuser,276 'api.tx.sudo.sudoUncheckedWeight',277 [helper.constructApiCall('api.tx.parachainSystem.authorizeUpgrade', [codeHash, false]), {}],278 );279280 if(result.status == 'Fail') {281 console.error('Failed to authorize the upgrade:', result);282 return;283 }284285 console.log('--- Enacting the parachain runtime upgrade \t---');286 result = await helper.executeExtrinsic(287 superuser,288 'api.tx.sudo.sudoUncheckedWeight',289 [helper.constructApiCall('api.tx.parachainSystem.enactAuthorizedUpgrade', [`0x${code.toString('hex')}`]), {}],290 );291292 if(result.status == 'Fail') {293 console.error('Failed to upgrade the runtime:', result);294 }295 }, para.nodes[0].wsUri);296 }297298 299 let firstPass = true;300 for(let attempt = 0; attempt < 3 && !paraUpgradeCompleted; attempt++) {301 if(firstPass) {302 console.log('\nCode validation delay:', codeValidationDelayBlocks, 'blocks');303 console.log('🚥 Waiting for the minimum code validation delay before the parachain can upgrade...');304 await waitWithTimer(relayInfo.blockTime * codeValidationDelayBlocks);305 firstPass = false;306 } else {307 console.log('\n🚥 Waiting for a few blocks more to verify that the parachain upgrades are successful...');308 await waitWithTimer(PARACHAIN_BLOCK_TIME * 3);309 }310311 312 let upgradeFailed = false;313 for(const paraId in network.paras) {314 if(upgradingParas[paraId].upgraded) continue;315316 const para = network.paras[paraId];317 318 await usingPlaygrounds(async (helper) => {319 const specVersion = getSpecVersion(helper.getApi());320321 if(specVersion != upgradingParas[paraId].version) {322 323 console.log(`\n\🛰️ Parachain ${paraId} has successfully upgraded from version ${upgradingParas[paraId].version} to ${specVersion}!`);324 upgradingParas[paraId].upgraded = true;325 } else {326 console.error(`\nParachain ${paraId} failed to upgrade from version ${upgradingParas[paraId].version}!`);327 upgradeFailed = true;328 }329 }, para.nodes[0].wsUri);330331 paraUpgradeCompleted = !upgradeFailed;332 }333 }334335 336 for(const paraId in network.paras) {337 338 if(migration) {339 console.log('⭐️⭐️⭐️ Running post-upgrade scripts... ⭐️⭐️⭐️');340 await migration.after();341 }342 await toggleMaintenanceMode(false, network.paras[paraId].nodes[0].wsUri);343 }344 } else {345 346 paraUpgradeCompleted = true;347 }348349 350351 if(isUpgradeTesting) {352 if(paraUpgradeCompleted && relayUpgradeCompleted) {353 console.log("\n🛸 PARACHAINS' RUNTIME UPGRADE TESTING COMPLETE 🛸");354 } else {355 console.error("\n🚧 PARACHAINS' RUNTIME UPGRADE TESTING FAILED 🚧");356 }357 } else {358 console.log('🚀 ZOMBIENET RAISED 🚀');359 }360};361362raiseZombienet().catch(async (e) => {363 console.error(e);364 await stop();365 process.exit(1);366});