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 fs from 'fs';2425const ZOMBIENET_CREDENTIALS = process.env.ZOMBIENET_CREDENTIALS || '../.env';26const NETWORK_CONFIG_FILE = process.argv[2] ?? '../launch-zombienet.toml';27const PARA_DIR = process.env.PARA_DIR || '../';28const RELAY_DIR = process.env.RELAY_DIR || '../../polkadot/';29const REPLICA_FROM = process.env.REPLICA_FROM || 'wss://ws-opal.unique.network:443';30const NEW_RELAY_BIN = process.env.NEW_RELAY_BIN;31const NEW_RELAY_WASM = process.env.NEW_RELAY_WASM;32const NEW_PARA_BIN = process.env.NEW_PARA_BIN;33const NEW_PARA_WASM = process.env.NEW_PARA_WASM;34const PARACHAIN_BLOCK_TIME = 12_000;3536let network: zombie.Network | undefined;373839const stop = async () => {40 await network?.stop();41};424344function delay(ms: number) {45 return new Promise(resolve => setTimeout(resolve, ms));46}474849async function waitWithTimer(time: number) {50 const secondsTotal = Math.ceil(time / 1000);51 for (let i = secondsTotal; i > 0; i--) {52 53 const seconds = i % 60;54 const text = `Time left: ${Math.floor(i / 60)}:${seconds < 10 ? '0' + seconds : seconds}`;55 if (process.stdout.isTTY)56 process.stdout.write(text);57 else if (seconds % 10 == 0)58 console.log(text);59 await delay(1000);60 if (process.stdout.isTTY) {61 process.stdout.clearLine(0);62 process.stdout.cursorTo(0);63 }64 }65}666768function getSpecVersion(api: ApiPromise): number {69 return (api.consts.system.version as any).specVersion.toNumber();70}717273function getRelayInfo(api: ApiPromise): {specVersion: number, epochBlockLength: number, blockTime: number, epochTime: number} {74 const info = {75 specVersion: getSpecVersion(api),76 epochBlockLength: (api.consts.babe.epochDuration as any).toNumber(),77 blockTime: (api.consts.babe.expectedBlockTime as any).toNumber(),78 epochTime: 0,79 };80 info.epochTime = info.epochBlockLength * info.blockTime;81 return info;82}838485async function toggleMaintenanceMode(value: boolean, wsUri: string) {86 await usingPlaygrounds(async (helper, privateKey) => {87 const superuser = await privateKey('//Alice');88 try {89 const toggle = value ? 'enable' : 'disable';90 await helper.getSudo().executeExtrinsic(superuser, `api.tx.maintenance.${toggle}`, []);91 console.log(`Maintenance mode ${value ? 'engaged' : 'disengaged'}.`);92 } catch (e) {93 console.error('Couldn\'t set maintenance mode. The maintenance pallet probably does not exist. Log:', e);94 }95 }, wsUri);96}9798const raiseZombienet = async (): Promise<void> => {99 const isUpgradeTesting = !!NEW_RELAY_BIN || !!NEW_RELAY_WASM || !!NEW_RELAY_BIN && !!NEW_PARA_WASM;100 101102103104105106107108109 110 process.env.PARA_DIR = PARA_DIR;111 process.env.RELAY_DIR = RELAY_DIR;112 process.env.REPLICA_FROM = REPLICA_FROM;113114 const configPath = resolve(NETWORK_CONFIG_FILE);115 const networkConfig = readNetworkConfig(configPath);116 117 if (networkConfig.settings.provider !== 'native') {118 throw new Error(`Oh no! Expected native network, got ${networkConfig.settings.provider}.`);119 }120121 await cryptoWaitReady();122123 124 125 126 127 128129 network = await zombie.start(ZOMBIENET_CREDENTIALS, networkConfig, {silent: false});130131 132 await network.relay[0].connectApi();133 let relayInfo = getRelayInfo(network.relay[0].apiInstance!);134 await network.relay[0].apiInstance?.disconnect();135 if (isUpgradeTesting) {136 console.log('Relay stats:', relayInfo);137 }138139 140 const networkClient = (network.client as any);141142 if (NEW_RELAY_BIN) {143 console.log('\n🧶 Restarting relay nodes');144145 for (const [index, node] of network.relay.entries()) {146 await node.apiInstance?.disconnect();147148 console.log(`\n🚦 Starting timeout for the epoch change (node ${index + 1}/${network.relay.length})...`);149 await waitWithTimer(relayInfo.epochTime);150151 152 const cmd = networkClient.processMap[node.name].cmd[0].split(' ')[0];153 networkClient.processMap[node.name].cmd = networkClient.processMap[node.name].cmd.map((arg: string) => arg.replace(cmd, NEW_RELAY_BIN));154155 await node.restart();156 }157158 console.log('\n🌒 All relay nodes restarted with the new binaries.');159 }160161 if (NEW_PARA_BIN) {162 for (const paraId in network.paras) {163 const para = network.paras[paraId];164 console.log(`\n🧶 Restarting collator nodes of parachain ${paraId}`);165166 for (const [_index, node] of para.nodes.entries()) {167 await node.apiInstance?.disconnect();168169 170 const cmd = networkClient.processMap[node.name].cmd[0].split(' ')[0];171 networkClient.processMap[node.name].cmd = networkClient.processMap[node.name].cmd.map((arg: string) => arg.replace(cmd, NEW_PARA_BIN));172173 await node.restart();174 175 }176 }177178 console.log('\n🌗 All parachain collators restarted with the new binaries.');179 }180181 182 183 184 185 186187 let relayUpgradeCompleted = false, paraUpgradeCompleted = false;188189 if (NEW_RELAY_WASM) {190 const relayOldVersion = relayInfo.specVersion;191 console.log('\n🚦 Starting timeout for the next epoch before upgrading the relay runtime code...');192 await waitWithTimer(relayInfo.epochTime);193194 console.log('--- Upgrading the relay chain runtime \t---');195196 197 const code = fs.readFileSync(NEW_RELAY_WASM).toString('hex');198 await usingPlaygrounds(async (helper, privateKey) => {199 const superuser = await privateKey('//Alice');200201 const result = await helper.executeExtrinsic(202 superuser,203 'api.tx.sudo.sudoUncheckedWeight',204 [helper.constructApiCall('api.tx.system.setCode', [`0x${code}`]), 0],205 );206207 if (result.status == 'Fail') {208 console.error('Failed to upgrade the runtime:', result);209 }210211 212 relayInfo = getRelayInfo(helper.getApi());213 }, network.relay[0].wsUri);214215 if (relayOldVersion != relayInfo.specVersion) {216 217 console.log(`\n\🛰️ The relay has successfully upgraded from version ${relayOldVersion} to ${relayInfo.specVersion}!`);218 relayUpgradeCompleted = true;219 } else {220 console.error(`\nThe relay did not upgrade from version ${relayOldVersion}!`);221 }222 } else {223 224 relayUpgradeCompleted = true;225 }226227 if (NEW_PARA_WASM) {228 let codeValidationDelayBlocks = 0;229 const upgradingParas: {[id: string]: {version: number, upgraded: boolean}} = {};230 231 232 await usingPlaygrounds(async (helper) => {233 const {validationUpgradeDelay, minimumValidationUpgradeDelay} =234 (await helper.callRpc('api.query.configuration.activeConfig', [])).toJSON() as any;235236 codeValidationDelayBlocks = Math.max(validationUpgradeDelay ?? 0, minimumValidationUpgradeDelay ?? 0);237 }, network.relay[0].wsUri);238239 240 241 console.log('\n🚥 Starting timeout for the next epoch before upgrading the parachains code...');242 await waitWithTimer(relayInfo.epochTime);243 244245 for (const paraId in network.paras) {246 console.log(`\n--- Upgrading the runtime of parachain ${paraId} \t---`);247 const para = network.paras[paraId];248249 250 await toggleMaintenanceMode(true, para.nodes[0].wsUri);251252 253 const code = fs.readFileSync(NEW_PARA_WASM);254 const codeHash = blake2AsHex(code);255 await usingPlaygrounds(async (helper, privateKey) => {256 const superuser = await privateKey('//Alice');257258 upgradingParas[paraId] = {version: getSpecVersion(helper.getApi()), upgraded: false};259260 console.log('--- Authorizing the parachain runtime upgrade \t---');261 let result = await helper.executeExtrinsic(262 superuser,263 'api.tx.sudo.sudoUncheckedWeight',264 [helper.constructApiCall('api.tx.parachainSystem.authorizeUpgrade', [codeHash]), 0],265 );266267 if (result.status == 'Fail') {268 console.error('Failed to authorize the upgrade:', result);269 return;270 }271272 console.log('--- Enacting the parachain runtime upgrade \t---');273 result = await helper.executeExtrinsic(274 superuser,275 'api.tx.sudo.sudoUncheckedWeight',276 [helper.constructApiCall('api.tx.parachainSystem.enactAuthorizedUpgrade', [`0x${code.toString('hex')}`]), 0],277 );278279 if (result.status == 'Fail') {280 console.error('Failed to upgrade the runtime:', result);281 }282 }, para.nodes[0].wsUri);283 }284285 286 let firstPass = true;287 for (let attempt = 0; attempt < 3 && !paraUpgradeCompleted; attempt++) {288 if (firstPass) {289 console.log('\nCode validation delay:', codeValidationDelayBlocks, 'blocks');290 console.log('🚥 Waiting for the minimum code validation delay before the parachain can upgrade...');291 await waitWithTimer(relayInfo.blockTime * codeValidationDelayBlocks);292 firstPass = false;293 } else {294 console.log('\n🚥 Waiting for a few blocks more to verify that the parachain upgrades are successful...');295 await waitWithTimer(PARACHAIN_BLOCK_TIME * 3);296 }297298 299 let upgradeFailed = false;300 for (const paraId in network.paras) {301 if (upgradingParas[paraId].upgraded) continue;302303 const para = network.paras[paraId];304 305 await usingPlaygrounds(async (helper) => {306 const specVersion = getSpecVersion(helper.getApi());307308 if (specVersion != upgradingParas[paraId].version) {309 310 console.log(`\n\🛰️ Parachain ${paraId} has successfully upgraded from version ${upgradingParas[paraId].version} to ${specVersion}!`);311 upgradingParas[paraId].upgraded = true;312 } else {313 console.error(`\nParachain ${paraId} failed to upgrade from version ${upgradingParas[paraId].version}!`);314 upgradeFailed = true;315 }316 }, para.nodes[0].wsUri);317318 paraUpgradeCompleted = !upgradeFailed;319 }320 }321322 323 for (const paraId in network.paras) {324 await toggleMaintenanceMode(false, network.paras[paraId].nodes[0].wsUri);325 }326 } else {327 328 paraUpgradeCompleted = true;329 }330331 332333 if (isUpgradeTesting) {334 if (paraUpgradeCompleted && relayUpgradeCompleted) {335 console.log("\n🛸 PARACHAINS' RUNTIME UPGRADE TESTING COMPLETE 🛸");336 } else {337 console.error("\n🚧 PARACHAINS' RUNTIME UPGRADE TESTING FAILED 🚧");338 }339 } else {340 console.log('🚀 ZOMBIENET RAISED 🚀');341 }342};343344raiseZombienet().catch(async (e) => {345 console.error(e);346 await stop();347 process.exit(1);348});