quantus_cli/cli/
runtime.rs1use crate::{
3 chain::quantus_subxt, cli::progress_spinner::wait_for_tx_confirmation, error::QuantusError,
4 log_print, log_success, log_verbose, wallet::QuantumKeyPair,
5};
6use clap::Subcommand;
7use colored::Colorize;
8
9use crate::chain::client::ChainConfig;
10use std::{fs, path::PathBuf};
11use subxt::OnlineClient;
12
13#[derive(Subcommand, Debug)]
14pub enum RuntimeCommands {
15 Update {
17 #[arg(short, long)]
19 wasm_file: PathBuf,
20
21 #[arg(short, long)]
23 from: String,
24
25 #[arg(short, long)]
27 password: Option<String>,
28
29 #[arg(long)]
31 password_file: Option<String>,
32
33 #[arg(long)]
35 force: bool,
36 },
37
38 Compare {
40 #[arg(short, long)]
42 wasm_file: PathBuf,
43 },
44}
45
46pub async fn update_runtime(
48 quantus_client: &crate::chain::client::QuantusClient,
49 wasm_code: Vec<u8>,
50 from_keypair: &QuantumKeyPair,
51 force: bool,
52) -> crate::error::Result<subxt::utils::H256> {
53 log_verbose!("🔄 Updating runtime...");
54
55 log_print!("📋 Current runtime version:");
56 log_print!(" • Use 'quantus system --runtime' to see current version");
57
58 if !force {
60 log_print!("");
61 log_print!(
62 "⚠️ {} {}",
63 "WARNING:".bright_red().bold(),
64 "Runtime update is a critical operation!"
65 );
66 log_print!(" • This will update the blockchain runtime immediately");
67 log_print!(" • All nodes will need to upgrade to stay in sync");
68 log_print!(" • This operation cannot be easily reversed");
69 log_print!("");
70
71 print!("Do you want to proceed with the runtime update? (yes/no): ");
73 use std::io::{self, Write};
74 io::stdout().flush().unwrap();
75
76 let mut input = String::new();
77 io::stdin().read_line(&mut input).unwrap();
78
79 if input.trim().to_lowercase() != "yes" {
80 log_print!("❌ Runtime update cancelled");
81 return Err(QuantusError::Generic("Runtime update cancelled".to_string()));
82 }
83 }
84
85 let set_code_call =
87 quantus_subxt::api::Call::System(quantus_subxt::api::system::Call::set_code {
88 code: wasm_code,
89 });
90
91 let sudo_call = quantus_subxt::api::tx().sudo().sudo(set_code_call);
93
94 log_print!("📡 Submitting runtime update transaction...");
96 log_print!("⏳ This may take longer than usual due to WASM size...");
97
98 let tx_hash =
99 crate::cli::common::submit_transaction(quantus_client, from_keypair, sudo_call, None)
100 .await?;
101
102 log_success!(
103 "✅ SUCCESS Runtime update transaction submitted! Hash: 0x{}",
104 hex::encode(tx_hash)
105 );
106
107 wait_for_tx_confirmation(quantus_client.client(), tx_hash).await?;
109 log_success!("✅ 🎉 FINISHED Runtime update completed!");
110
111 Ok(tx_hash)
112}
113
114#[derive(Debug, Clone)]
116pub struct RuntimeVersionInfo {
117 pub spec_version: u32,
118 pub impl_version: u32,
119 pub transaction_version: u32,
120}
121
122pub async fn get_runtime_version(
124 client: &OnlineClient<ChainConfig>,
125) -> crate::error::Result<RuntimeVersionInfo> {
126 log_verbose!("🔍 Getting runtime version...");
127
128 let runtime_version = client.runtime_version();
129
130 Ok(RuntimeVersionInfo {
133 spec_version: runtime_version.spec_version,
134 impl_version: 1, transaction_version: runtime_version.transaction_version,
136 })
137}
138
139pub async fn calculate_wasm_hash(wasm_code: &[u8]) -> crate::error::Result<String> {
141 use sha2::{Digest, Sha256};
142 let mut hasher = Sha256::new();
143 hasher.update(wasm_code);
144 let local_hash = hasher.finalize();
145
146 Ok(format!("0x{}", hex::encode(local_hash)))
147}
148
149pub async fn handle_runtime_command(
151 command: RuntimeCommands,
152 node_url: &str,
153) -> crate::error::Result<()> {
154 let quantus_client = crate::chain::client::QuantusClient::new(node_url).await?;
155
156 match command {
157 RuntimeCommands::Update { wasm_file, from, password, password_file, force } => {
158 log_print!("🚀 Runtime Management");
159 log_print!("🔄 Runtime Update");
160 log_print!(" 📂 WASM file: {}", wasm_file.display().to_string().bright_cyan());
161 log_print!(" 🔑 Signed by: {}", from.bright_yellow());
162
163 if !wasm_file.exists() {
165 return Err(QuantusError::Generic(format!(
166 "WASM file not found: {}",
167 wasm_file.display()
168 )));
169 }
170
171 if let Some(ext) = wasm_file.extension() {
173 if ext != "wasm" {
174 log_print!("⚠️ Warning: File doesn't have .wasm extension");
175 }
176 }
177
178 let keypair = crate::wallet::load_keypair_from_wallet(&from, password, password_file)?;
180
181 log_verbose!("📖 Reading WASM file...");
183 let wasm_code = fs::read(&wasm_file)
184 .map_err(|e| QuantusError::Generic(format!("Failed to read WASM file: {e}")))?;
185
186 log_print!("📊 WASM file size: {} bytes", wasm_code.len());
187
188 update_runtime(&quantus_client, wasm_code, &keypair, force).await?;
190
191 log_success!("🎉 Runtime update completed!");
192 log_print!(
193 "💡 Note: It may take a few moments for the new runtime version to be reflected."
194 );
195 log_print!("💡 Use 'quantus runtime check-version' to verify the new version.");
196
197 Ok(())
198 },
199
200 RuntimeCommands::Compare { wasm_file } => {
201 log_print!("🚀 Runtime Management");
202 log_print!("🔍 Comparing WASM file with current runtime...");
203 log_print!(" 📂 Local file: {}", wasm_file.display().to_string().bright_cyan());
204
205 if !wasm_file.exists() {
207 return Err(QuantusError::Generic(format!(
208 "WASM file not found: {}",
209 wasm_file.display()
210 )));
211 }
212
213 let local_wasm = fs::read(&wasm_file)
215 .map_err(|e| QuantusError::Generic(format!("Failed to read WASM file: {e}")))?;
216
217 log_print!("📊 Local WASM size: {} bytes", local_wasm.len());
218
219 let current_version = get_runtime_version(quantus_client.client()).await?;
221 log_print!("📋 Current chain runtime:");
222 log_print!(" • Spec version: {}", current_version.spec_version);
223 log_print!(" • Impl version: {}", current_version.impl_version);
224 log_print!(" • Transaction version: {}", current_version.transaction_version);
225
226 let local_hash = calculate_wasm_hash(&local_wasm).await?;
228 log_print!("🔐 Local WASM SHA256: {}", local_hash.bright_blue());
229
230 if let Ok(Some(chain_runtime_hash)) = quantus_client.get_runtime_hash().await {
232 log_print!("🔐 Chain runtime hash: {}", chain_runtime_hash.bright_yellow());
233
234 if local_hash == chain_runtime_hash {
236 log_success!("✅ Runtime hashes match! The WASM file is identical to the current runtime.");
237 } else {
238 log_print!("⚠️ Runtime hashes differ. The WASM file is different from the current runtime.");
239 }
240 } else {
241 log_print!("💡 Chain runtime hash not available for comparison");
242 }
243
244 let filename = wasm_file.file_name().unwrap().to_string_lossy();
246 log_verbose!("🔍 Parsing filename: {}", filename);
247
248 if let Some(version_str) = filename.split('-').nth(2) {
249 log_verbose!("🔍 Version part: {}", version_str);
250 if let Some(version_num) = version_str.split('.').next() {
251 log_verbose!("🔍 Version number: {}", version_num);
252 let clean_version = version_num.trim_start_matches('v');
254 log_verbose!("🔍 Clean version: {}", clean_version);
255 if let Ok(wasm_version) = clean_version.parse::<u32>() {
256 log_print!("📋 Version comparison:");
257 log_print!(
258 " • Local WASM version: {}",
259 wasm_version.to_string().bright_green()
260 );
261 log_print!(
262 " • Chain runtime version: {}",
263 current_version.spec_version.to_string().bright_yellow()
264 );
265
266 match wasm_version.cmp(¤t_version.spec_version) {
267 std::cmp::Ordering::Equal => {
268 log_success!("✅ Versions match! The WASM file is compatible with the current runtime.");
269 },
270 std::cmp::Ordering::Greater => {
271 log_print!("🔄 The WASM file is newer than the current runtime.");
272 log_print!(" • This would be an upgrade");
273 },
274 std::cmp::Ordering::Less => {
275 log_print!("⚠️ The WASM file is older than the current runtime.");
276 log_print!(" • This would be a downgrade");
277 },
278 }
279 } else {
280 log_print!("⚠️ Could not parse version number from filename");
281 }
282 } else {
283 log_print!("⚠️ Could not extract version number from filename");
284 }
285 } else {
286 log_print!("⚠️ Could not extract version from filename format");
287 }
288
289 log_print!("💡 Use 'quantus system --runtime' for detailed runtime information");
290
291 Ok(())
292 },
293 }
294}