quantus_cli/cli/
runtime.rs1use crate::{
3 chain::quantus_subxt, error::QuantusError, log_print, log_success, log_verbose,
4 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 = crate::cli::common::submit_transaction_with_finalization(
99 quantus_client,
100 from_keypair,
101 sudo_call,
102 None,
103 true,
104 )
105 .await?;
106
107 log_success!(
108 "✅ SUCCESS Runtime update transaction submitted! Hash: 0x{}",
109 hex::encode(tx_hash)
110 );
111
112 Ok(tx_hash)
113}
114
115#[derive(Debug, Clone)]
117pub struct RuntimeVersionInfo {
118 pub spec_version: u32,
119 pub impl_version: u32,
120 pub transaction_version: u32,
121}
122
123pub async fn get_runtime_version(
125 client: &OnlineClient<ChainConfig>,
126) -> crate::error::Result<RuntimeVersionInfo> {
127 log_verbose!("🔍 Getting runtime version...");
128
129 let runtime_version = client.runtime_version();
130
131 Ok(RuntimeVersionInfo {
134 spec_version: runtime_version.spec_version,
135 impl_version: 1, transaction_version: runtime_version.transaction_version,
137 })
138}
139
140pub async fn calculate_wasm_hash(wasm_code: &[u8]) -> crate::error::Result<String> {
142 use sha2::{Digest, Sha256};
143 let mut hasher = Sha256::new();
144 hasher.update(wasm_code);
145 let local_hash = hasher.finalize();
146
147 Ok(format!("0x{}", hex::encode(local_hash)))
148}
149
150pub async fn handle_runtime_command(
152 command: RuntimeCommands,
153 node_url: &str,
154) -> crate::error::Result<()> {
155 let quantus_client = crate::chain::client::QuantusClient::new(node_url).await?;
156
157 match command {
158 RuntimeCommands::Update { wasm_file, from, password, password_file, force } => {
159 log_print!("🚀 Runtime Management");
160 log_print!("🔄 Runtime Update");
161 log_print!(" 📂 WASM file: {}", wasm_file.display().to_string().bright_cyan());
162 log_print!(" 🔑 Signed by: {}", from.bright_yellow());
163
164 if !wasm_file.exists() {
166 return Err(QuantusError::Generic(format!(
167 "WASM file not found: {}",
168 wasm_file.display()
169 )));
170 }
171
172 if let Some(ext) = wasm_file.extension() {
174 if ext != "wasm" {
175 log_print!("⚠️ Warning: File doesn't have .wasm extension");
176 }
177 }
178
179 let keypair = crate::wallet::load_keypair_from_wallet(&from, password, password_file)?;
181
182 log_verbose!("📖 Reading WASM file...");
184 let wasm_code = fs::read(&wasm_file)
185 .map_err(|e| QuantusError::Generic(format!("Failed to read WASM file: {e}")))?;
186
187 log_print!("📊 WASM file size: {} bytes", wasm_code.len());
188
189 update_runtime(&quantus_client, wasm_code, &keypair, force).await?;
191
192 log_success!("🎉 Runtime update completed!");
193 log_print!(
194 "💡 Note: It may take a few moments for the new runtime version to be reflected."
195 );
196 log_print!("💡 Use 'quantus runtime check-version' to verify the new version.");
197
198 Ok(())
199 },
200
201 RuntimeCommands::Compare { wasm_file } => {
202 log_print!("🚀 Runtime Management");
203 log_print!("🔍 Comparing WASM file with current runtime...");
204 log_print!(" 📂 Local file: {}", wasm_file.display().to_string().bright_cyan());
205
206 if !wasm_file.exists() {
208 return Err(QuantusError::Generic(format!(
209 "WASM file not found: {}",
210 wasm_file.display()
211 )));
212 }
213
214 let local_wasm = fs::read(&wasm_file)
216 .map_err(|e| QuantusError::Generic(format!("Failed to read WASM file: {e}")))?;
217
218 log_print!("📊 Local WASM size: {} bytes", local_wasm.len());
219
220 let current_version = get_runtime_version(quantus_client.client()).await?;
222 log_print!("📋 Current chain runtime:");
223 log_print!(" • Spec version: {}", current_version.spec_version);
224 log_print!(" • Impl version: {}", current_version.impl_version);
225 log_print!(" • Transaction version: {}", current_version.transaction_version);
226
227 let local_hash = calculate_wasm_hash(&local_wasm).await?;
229 log_print!("🔐 Local WASM SHA256: {}", local_hash.bright_blue());
230
231 if let Ok(Some(chain_runtime_hash)) = quantus_client.get_runtime_hash().await {
233 log_print!("🔐 Chain runtime hash: {}", chain_runtime_hash.bright_yellow());
234
235 if local_hash == chain_runtime_hash {
237 log_success!("✅ Runtime hashes match! The WASM file is identical to the current runtime.");
238 } else {
239 log_print!("⚠️ Runtime hashes differ. The WASM file is different from the current runtime.");
240 }
241 } else {
242 log_print!("💡 Chain runtime hash not available for comparison");
243 }
244
245 let filename = wasm_file.file_name().unwrap().to_string_lossy();
247 log_verbose!("🔍 Parsing filename: {}", filename);
248
249 if let Some(version_str) = filename.split('-').nth(2) {
250 log_verbose!("🔍 Version part: {}", version_str);
251 if let Some(version_num) = version_str.split('.').next() {
252 log_verbose!("🔍 Version number: {}", version_num);
253 let clean_version = version_num.trim_start_matches('v');
255 log_verbose!("🔍 Clean version: {}", clean_version);
256 if let Ok(wasm_version) = clean_version.parse::<u32>() {
257 log_print!("📋 Version comparison:");
258 log_print!(
259 " • Local WASM version: {}",
260 wasm_version.to_string().bright_green()
261 );
262 log_print!(
263 " • Chain runtime version: {}",
264 current_version.spec_version.to_string().bright_yellow()
265 );
266
267 match wasm_version.cmp(¤t_version.spec_version) {
268 std::cmp::Ordering::Equal => {
269 log_success!("✅ Versions match! The WASM file is compatible with the current runtime.");
270 },
271 std::cmp::Ordering::Greater => {
272 log_print!("🔄 The WASM file is newer than the current runtime.");
273 log_print!(" • This would be an upgrade");
274 },
275 std::cmp::Ordering::Less => {
276 log_print!("⚠️ The WASM file is older than the current runtime.");
277 log_print!(" • This would be a downgrade");
278 },
279 }
280 } else {
281 log_print!("⚠️ Could not parse version number from filename");
282 }
283 } else {
284 log_print!("⚠️ Could not extract version number from filename");
285 }
286 } else {
287 log_print!("⚠️ Could not extract version from filename format");
288 }
289
290 log_print!("💡 Use 'quantus system --runtime' for detailed runtime information");
291
292 Ok(())
293 },
294 }
295}