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 PARACHAIN_BLOCK_TIME = 12_000;36const SUPERUSER_KEY = '//Alice';3738let network: zombie.Network | undefined;394041const stop = async () => {42 await network?.stop();43};444546function delay(ms: number) {47 return new Promise(resolve => setTimeout(resolve, ms));48}495051async function waitWithTimer(time: number) {52 const secondsTotal = Math.ceil(time / 1000);53 for(let i = secondsTotal; i > 0; i--) {54 55 const seconds = i % 60;56 const text = `Time left: ${Math.floor(i / 60)}:${seconds < 10 ? '0' + seconds : seconds}`;57 if(process.stdout.isTTY)58 process.stdout.write(text);59 else if(seconds % 10 == 0)60 console.log(text);61 await delay(1000);62 if(process.stdout.isTTY) {63 process.stdout.clearLine(0);64 process.stdout.cursorTo(0);65 }66 }67}686970function getSpecVersion(api: ApiPromise): number {71 return (api.consts.system.version as any).specVersion.toNumber();72}737475function getRelayInfo(api: ApiPromise): {specVersion: number, epochBlockLength: number, blockTime: number, epochTime: number} {76 const info = {77 specVersion: getSpecVersion(api),78 epochBlockLength: (api.consts.babe.epochDuration as any).toNumber(),79 blockTime: (api.consts.babe.expectedBlockTime as any).toNumber(),80 epochTime: 0,81 };82 info.epochTime = info.epochBlockLength * info.blockTime;83 return info;84}858687async function toggleMaintenanceMode(value: boolean, wsUri: string) {88 await usingPlaygrounds(async (helper, privateKey) => {89 const superuser = await privateKey(SUPERUSER_KEY);90 try {91 const toggle = value ? 'enable' : 'disable';92 await helper.getSudo().executeExtrinsic(superuser, `api.tx.maintenance.${toggle}`, []);93 console.log(`Maintenance mode ${value ? 'engaged' : 'disengaged'}.`);94 } catch (e) {95 console.error('Couldn\'t set maintenance mode. The maintenance pallet probably does not exist. Log:', e);96 }97 }, wsUri);98}99100const raiseZombienet = async (): Promise<void> => {101 const isUpgradeTesting = !!NEW_RELAY_BIN || !!NEW_RELAY_WASM || !!NEW_PARA_BIN || !!NEW_PARA_WASM;102 103104105106107108109110111 112 process.env.PARA_DIR = PARA_DIR;113 process.env.RELAY_DIR = RELAY_DIR;114 process.env.REPLICA_FROM = REPLICA_FROM;115116 const configPath = resolve(NETWORK_CONFIG_FILE);117 const networkConfig = readNetworkConfig(configPath);118 119 if(networkConfig.settings.provider !== 'native') {120 throw new Error(`Oh no! Expected native network, got ${networkConfig.settings.provider}.`);121 }122123 await cryptoWaitReady();124125 126 network = await zombie.start(ZOMBIENET_CREDENTIALS, networkConfig, {silent: false});127128 129 130 131 132 133134 135 await network.relay[0].connectApi();136 let relayInfo = getRelayInfo((network.relay[0] as any).apiInstance!);137 await network.relay[0].apiInstance!.disconnect();138 if(isUpgradeTesting) {139 console.log('Relay stats:', relayInfo);140 }141142 143 const networkClient = (network.client as any);144145 if(NEW_RELAY_BIN) {146 console.log('\n🧶 Restarting relay nodes');147148 for(const [index, node] of network.relay.entries()) {149 await node.apiInstance?.disconnect();150151 console.log(`\n🚦 Starting timeout for the epoch change (node ${index + 1}/${network.relay.length})...`);152 await waitWithTimer(relayInfo.epochTime);153154 155 const cmd = networkClient.processMap[node.name].cmd[0].split(' ')[0];156 networkClient.processMap[node.name].cmd = networkClient.processMap[node.name].cmd.map((arg: string) => arg.replace(cmd, NEW_RELAY_BIN));157158 await node.restart();159 }160161 console.log('\n🌒 All relay nodes restarted with the new binaries.');162 }163164 if(NEW_PARA_BIN) {165 for(const paraId in network.paras) {166 const para = network.paras[paraId];167 console.log(`\n🧶 Restarting collator nodes of parachain ${paraId}`);168169 for(const [_index, node] of para.nodes.entries()) {170 await node.apiInstance?.disconnect();171172 173 const cmd = networkClient.processMap[node.name].cmd[0].split(' ')[0];174 networkClient.processMap[node.name].cmd = networkClient.processMap[node.name].cmd.map((arg: string) => arg.replace(cmd, NEW_PARA_BIN));175176 await node.restart();177 178 179 }180 }181182 console.log('\n🌗 All parachain collators restarted with the new binaries.');183 }184185 186 187 188 189 190191 let relayUpgradeCompleted = false, paraUpgradeCompleted = false;192193 if(NEW_RELAY_WASM) {194 const relayOldVersion = relayInfo.specVersion;195 console.log('\n🚦 Starting timeout for the next epoch before upgrading the relay runtime code...');196 await waitWithTimer(relayInfo.epochTime);197198 console.log('--- Upgrading the relay chain runtime \t---');199200 201 const code = fs.readFileSync(NEW_RELAY_WASM).toString('hex');202 await usingPlaygrounds(async (helper, privateKey) => {203 const superuser = await privateKey(SUPERUSER_KEY);204205 const result = await helper.executeExtrinsic(206 superuser,207 'api.tx.sudo.sudoUncheckedWeight',208 [helper.constructApiCall('api.tx.system.setCode', [`0x${code}`]), {}],209 );210211 if(result.status == 'Fail') {212 console.error('Failed to upgrade the runtime:', result);213 }214215 216 relayInfo = getRelayInfo(helper.getApi());217 }, network.relay[0].wsUri);218219 if(relayOldVersion != relayInfo.specVersion) {220 221 console.log(`\n\🛰️ The relay has successfully upgraded from version ${relayOldVersion} to ${relayInfo.specVersion}!`);222 relayUpgradeCompleted = true;223 } else {224 console.error(`\nThe relay did not upgrade from version ${relayOldVersion}!`);225 }226 } else {227 228 relayUpgradeCompleted = true;229 }230231 if(NEW_PARA_WASM) {232 let codeValidationDelayBlocks = 0;233 const upgradingParas: {[id: string]: {version: number, upgraded: boolean}} = {};234 235 236 await usingPlaygrounds(async (helper) => {237 const {validationUpgradeDelay, minimumValidationUpgradeDelay} =238 (await helper.callRpc('api.query.configuration.activeConfig', [])).toJSON() as any;239240 codeValidationDelayBlocks = Math.max(validationUpgradeDelay ?? 0, minimumValidationUpgradeDelay ?? 0);241 }, network.relay[0].wsUri);242243 244 if(relayUpgradeCompleted && NEW_RELAY_WASM) {245 console.log('\n🚥 Starting timeout for the next epoch before upgrading the parachains code...');246 await waitWithTimer(relayInfo.epochTime);247 }248249 const migration = migrations[process.env.DESTINATION_SPEC_VERSION!];250 console.log('⭐️⭐️⭐️ DESTINATION_SPEC_VERSION ⭐️⭐️⭐️', process.env.DESTINATION_SPEC_VERSION!);251 for(const paraId in network.paras) {252 console.log(`\n--- Upgrading the runtime of parachain ${paraId} \t---`);253 const para = network.paras[paraId];254255 256 await toggleMaintenanceMode(true, para.nodes[0].wsUri);257 if(migration) {258 console.log('⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️');259 console.log('⭐️⭐️⭐️ Running pre-upgrade scripts... ⭐️⭐️⭐️');260 console.log('⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️');261 await migration.before();262 }263264 265 const code = fs.readFileSync(NEW_PARA_WASM);266 const codeHash = blake2AsHex(code);267 await usingPlaygrounds(async (helper, privateKey) => {268 const superuser = await privateKey(SUPERUSER_KEY);269270 upgradingParas[paraId] = {version: getSpecVersion(helper.getApi()), upgraded: false};271272 console.log('--- Authorizing the parachain runtime upgrade \t---');273 let result = await helper.executeExtrinsic(274 superuser,275 'api.tx.sudo.sudoUncheckedWeight',276 [helper.constructApiCall('api.tx.parachainSystem.authorizeUpgrade', [codeHash, false]), {}],277 );278279 if(result.status == 'Fail') {280 console.error('Failed to authorize the upgrade:', result);281 return;282 }283284 console.log('--- Enacting the parachain runtime upgrade \t---');285 result = await helper.executeExtrinsic(286 superuser,287 'api.tx.sudo.sudoUncheckedWeight',288 [helper.constructApiCall('api.tx.parachainSystem.enactAuthorizedUpgrade', [`0x${code.toString('hex')}`]), {}],289 );290291 if(result.status == 'Fail') {292 console.error('Failed to upgrade the runtime:', result);293 }294 }, para.nodes[0].wsUri);295 }296297 298 let firstPass = true;299 for(let attempt = 0; attempt < 3 && !paraUpgradeCompleted; attempt++) {300 if(firstPass) {301 console.log('\nCode validation delay:', codeValidationDelayBlocks, 'blocks');302 console.log('🚥 Waiting for the minimum code validation delay before the parachain can upgrade...');303 await waitWithTimer(relayInfo.blockTime * codeValidationDelayBlocks);304 firstPass = false;305 } else {306 console.log('\n🚥 Waiting for a few blocks more to verify that the parachain upgrades are successful...');307 await waitWithTimer(PARACHAIN_BLOCK_TIME * 3);308 }309310 311 let upgradeFailed = false;312 for(const paraId in network.paras) {313 if(upgradingParas[paraId].upgraded) continue;314315 const para = network.paras[paraId];316 317 await usingPlaygrounds(async (helper) => {318 const specVersion = getSpecVersion(helper.getApi());319320 if(specVersion != upgradingParas[paraId].version) {321 322 console.log(`\n\🛰️ Parachain ${paraId} has successfully upgraded from version ${upgradingParas[paraId].version} to ${specVersion}!`);323 upgradingParas[paraId].upgraded = true;324 } else {325 console.error(`\nParachain ${paraId} failed to upgrade from version ${upgradingParas[paraId].version}!`);326 upgradeFailed = true;327 }328 }, para.nodes[0].wsUri);329330 paraUpgradeCompleted = !upgradeFailed;331 }332 }333334 335 for(const paraId in network.paras) {336 337 if(migration) {338 console.log('⭐️⭐️⭐️ Running post-upgrade scripts... ⭐️⭐️⭐️');339 await migration.after();340 }341 await toggleMaintenanceMode(false, network.paras[paraId].nodes[0].wsUri);342 }343 } else {344 345 paraUpgradeCompleted = true;346 }347348 349350 if(isUpgradeTesting) {351 if(paraUpgradeCompleted && relayUpgradeCompleted) {352 console.log("\n🛸 PARACHAINS' RUNTIME UPGRADE TESTING COMPLETE 🛸");353 } else {354 console.error("\n🚧 PARACHAINS' RUNTIME UPGRADE TESTING FAILED 🚧");355 }356 } else {357 console.log('🚀 ZOMBIENET RAISED 🚀');358 }359};360361raiseZombienet().catch(async (e) => {362 console.error(e);363 await stop();364 process.exit(1);365});