1use super::*;
18use std::{collections::HashSet, fs};
19
20use leo_ast::NetworkName;
21use leo_package::{Package, ProgramData, fetch_program_from_network};
22
23#[cfg(not(feature = "only_testnet"))]
24use snarkvm::prelude::{CanaryV0, MainnetV0};
25use snarkvm::{
26 ledger::query::Query as SnarkVMQuery,
27 prelude::{
28 Program,
29 TestnetV0,
30 VM,
31 store::{ConsensusStore, helpers::memory::ConsensusMemory},
32 },
33};
34
35use crate::cli::{check_transaction::TransactionStatus, commands::deploy::validate_deployment_limits};
36use aleo_std::StorageMode;
37use colored::*;
38use itertools::Itertools;
39use leo_span::Symbol;
40use snarkvm::{
41 prelude::{ConsensusVersion, ProgramID, Stack, store::helpers::memory::BlockMemory},
42 synthesizer::program::StackTrait,
43};
44use std::path::PathBuf;
45
46#[derive(Parser, Debug)]
48pub struct LeoUpgrade {
49 #[clap(flatten)]
50 pub(crate) fee_options: FeeOptions,
51 #[clap(flatten)]
52 pub(crate) action: TransactionAction,
53 #[clap(flatten)]
54 pub(crate) env_override: EnvOptions,
55 #[clap(flatten)]
56 pub(crate) extra: ExtraOptions,
57 #[clap(long, help = "Skips the upgrade of any program that contains one of the given substrings.")]
58 pub(crate) skip: Vec<String>,
59 #[clap(flatten)]
60 pub(crate) build_options: BuildOptions,
61}
62
63impl Command for LeoUpgrade {
64 type Input = Package;
65 type Output = ();
66
67 fn log_span(&self) -> Span {
68 tracing::span!(tracing::Level::INFO, "Leo")
69 }
70
71 fn prelude(&self, context: Context) -> Result<Self::Input> {
72 LeoBuild {
73 env_override: self.env_override.clone(),
74 options: {
75 let mut options = self.build_options.clone();
76 options.no_cache = true;
77 options
78 },
79 }
80 .execute(context)
81 }
82
83 fn apply(self, context: Context, input: Self::Input) -> Result<Self::Output> {
84 let network = get_network(&self.env_override.network)?;
86 match network {
88 NetworkName::TestnetV0 => handle_upgrade::<TestnetV0>(&self, context, network, input),
89 NetworkName::MainnetV0 => {
90 #[cfg(feature = "only_testnet")]
91 panic!("Mainnet chosen with only_testnet feature");
92 #[cfg(not(feature = "only_testnet"))]
93 handle_upgrade::<MainnetV0>(&self, context, network, input)
94 }
95 NetworkName::CanaryV0 => {
96 #[cfg(feature = "only_testnet")]
97 panic!("Canary chosen with only_testnet feature");
98 #[cfg(not(feature = "only_testnet"))]
99 handle_upgrade::<CanaryV0>(&self, context, network, input)
100 }
101 }
102 }
103}
104
105fn handle_upgrade<N: Network>(
107 command: &LeoUpgrade,
108 context: Context,
109 network: NetworkName,
110 package: Package,
111) -> Result<<LeoDeploy as Command>::Output> {
112 let private_key = get_private_key(&command.env_override.private_key)?;
114 let address =
115 Address::try_from(&private_key).map_err(|e| CliError::custom(format!("Failed to parse address: {e}")))?;
116
117 let endpoint = get_endpoint(&command.env_override.endpoint)?;
119
120 let is_devnet = get_is_devnet(command.env_override.devnet);
122
123 let consensus_heights =
125 command.env_override.consensus_heights.clone().unwrap_or_else(|| get_consensus_heights(network, is_devnet));
126 validate_consensus_heights(&consensus_heights)
128 .map_err(|e| CliError::custom(format!("Invalid consensus heights: {e}")))?;
129 let consensus_heights_string = consensus_heights.iter().format(",").to_string();
131 println!(
132 "\nš¢ Using the following consensus heights: {consensus_heights_string}\n To override, pass in `--consensus-heights` or override the environment variable `CONSENSUS_VERSION_HEIGHTS`.\n"
133 );
134
135 #[allow(unsafe_code)]
137 unsafe {
138 std::env::set_var("CONSENSUS_VERSION_HEIGHTS", consensus_heights_string);
145 }
146
147 let programs = package.programs.iter().filter(|program| !program.is_test).cloned();
149
150 let programs_and_bytecode: Vec<(leo_package::Program, String)> = programs
151 .into_iter()
152 .map(|program| {
153 let bytecode = match &program.data {
154 ProgramData::Bytecode(s) => s.clone(),
155 ProgramData::SourcePath { .. } => {
156 let aleo_name = format!("{}.aleo", program.name);
158 let aleo_path = if package.manifest.program == aleo_name {
159 package.build_directory().join("main.aleo")
162 } else {
163 package.imports_directory().join(aleo_name)
165 };
166 fs::read_to_string(aleo_path.clone())
167 .map_err(|e| CliError::custom(format!("Failed to read file {}: {e}", aleo_path.display())))?
168 }
169 };
170
171 Ok((program, bytecode))
172 })
173 .collect::<Result<_>>()?;
174
175 let fee_options = parse_fee_options(&private_key, &command.fee_options, programs_and_bytecode.len())?;
177
178 let tasks: Vec<Task<N>> = programs_and_bytecode
179 .into_iter()
180 .zip(fee_options)
181 .map(|((program, bytecode), (_base_fee, priority_fee, record))| {
182 let id_str = format!("{}.aleo", program.name);
183 let id =
184 id_str.parse().map_err(|e| CliError::custom(format!("Failed to parse program ID {id_str}: {e}")))?;
185 let bytecode = bytecode.parse().map_err(|e| CliError::custom(format!("Failed to parse program: {e}")))?;
186 Ok(Task {
187 id,
188 program: bytecode,
189 edition: program.edition,
190 is_local: program.is_local,
191 priority_fee,
192 record,
193 })
194 })
195 .collect::<Result<_>>()?;
196
197 let program_ids = tasks.iter().map(|task| task.id).collect::<Vec<_>>();
199
200 let (local, remote) = tasks.into_iter().partition::<Vec<_>, _>(|task| task.is_local);
202
203 let skipped: HashSet<ProgramID<N>> = local
205 .iter()
206 .filter_map(|task| {
207 let id_string = task.id.to_string();
208 command.skip.iter().any(|skip| id_string.contains(skip)).then_some(task.id)
209 })
210 .collect();
211
212 let consensus_version =
214 get_consensus_version(&command.extra.consensus_version, &endpoint, network, &consensus_heights, &context)?;
215
216 print_deployment_plan(
218 &private_key,
219 &address,
220 &endpoint,
221 &network,
222 &local,
223 &skipped,
224 &remote,
225 &check_tasks_for_warnings(&endpoint, network, &local, consensus_version, command),
226 consensus_version,
227 &command.into(),
228 );
229
230 if !confirm("Do you want to proceed with upgrade?", command.extra.yes)? {
232 println!("ā Upgrade aborted.");
233 return Ok(());
234 }
235
236 let rng = &mut rand::thread_rng();
238
239 let vm = VM::from(ConsensusStore::<N, ConsensusMemory<N>>::open(StorageMode::Production)?)?;
241
242 let programs_and_editions = program_ids
244 .iter()
245 .map(|id| {
246 let program = leo_package::Program::fetch(
248 Symbol::intern(&id.name().to_string()),
249 None,
250 context.home()?,
251 network,
252 &endpoint,
253 true,
254 )?;
255 let ProgramData::Bytecode(bytecode) = program.data else {
256 panic!("Expected bytecode when fetching a remote program");
257 };
258 let bytecode = Program::<N>::from_str(&bytecode)
260 .map_err(|e| CliError::custom(format!("Failed to parse program: {e}")))?;
261 Ok((bytecode, program.edition.unwrap_or(1)))
264 })
265 .collect::<Result<Vec<_>>>()?;
266 vm.process().write().add_programs_with_editions(&programs_and_editions)?;
267
268 println!("Loaded the following programs into the VM:");
270 for program_id in vm.process().read().program_ids() {
271 let edition = *vm.process().read().get_stack(program_id)?.program_edition();
272 if program_id.to_string() == "credits.aleo" {
273 println!(" - credits.aleo (default)");
274 } else {
275 println!(" - {program_id} (edition {edition})");
276 }
277 }
278 println!();
279
280 let re = regex::Regex::new(r"v\d+$").unwrap();
282 let query_endpoint = re.replace(&endpoint, "").to_string();
283
284 let query = SnarkVMQuery::<N, BlockMemory<N>>::from(
286 query_endpoint
287 .parse::<Uri>()
288 .map_err(|e| CliError::custom(format!("Failed to parse endpoint URI '{endpoint}': {e}")))?,
289 );
290
291 let mut transactions = Vec::new();
293 for Task { id, program, priority_fee, record, .. } in local {
294 if !skipped.contains(&id) {
296 println!("š¦ Creating deployment transaction for '{}'...\n", id.to_string().bold());
297 let transaction =
299 vm.deploy(&private_key, &program, record, priority_fee.unwrap_or(0), Some(&query), rng)
300 .map_err(|e| CliError::custom(format!("Failed to generate deployment transaction: {e}")))?;
301 let deployment = transaction.deployment().expect("Expected a deployment in the transaction");
303 print_deployment_stats(&vm, &id.to_string(), deployment, priority_fee, consensus_version)?;
305 validate_deployment_limits(deployment, &id, &network)?;
307 transactions.push((id, transaction));
309 }
310 vm.process().write().add_program(&program)?;
312 }
313
314 if command.action.print {
317 for (program_name, transaction) in transactions.iter() {
318 let transaction_json = serde_json::to_string_pretty(transaction)
320 .map_err(|e| CliError::custom(format!("Failed to serialize transaction: {e}")))?;
321 println!("šØļø Printing deployment for {program_name}\n{transaction_json}")
322 }
323 }
324
325 if let Some(path) = &command.action.save {
329 std::fs::create_dir_all(path).map_err(|e| CliError::custom(format!("Failed to create directory: {e}")))?;
331 for (program_name, transaction) in transactions.iter() {
332 let file_path = PathBuf::from(path).join(format!("{program_name}.deployment.json"));
334 println!("š¾ Saving deployment for {program_name} at {}", file_path.display());
335 let transaction_json = serde_json::to_string_pretty(transaction)
336 .map_err(|e| CliError::custom(format!("Failed to serialize transaction: {e}")))?;
337 std::fs::write(file_path, transaction_json)
338 .map_err(|e| CliError::custom(format!("Failed to write transaction to file: {e}")))?;
339 }
340 }
341
342 if command.action.broadcast {
344 for (i, (program_id, transaction)) in transactions.iter().enumerate() {
345 println!("š” Broadcasting upgrade for {program_id}...");
346 let fee = transaction.fee_transition().expect("Expected a fee in the transaction");
348 if !confirm_fee(&fee, &private_key, &address, &endpoint, network, &context, command.extra.yes)? {
349 println!("ā© Upgrade skipped.");
350 continue;
351 }
352 let fee_id = fee.id().to_string();
353 let id = transaction.id().to_string();
354 let height_before = check_transaction::current_height(&endpoint, network)?;
355 let (message, status) = handle_broadcast(
357 &format!("{endpoint}/{network}/transaction/broadcast"),
358 transaction,
359 &program_id.to_string(),
360 )?;
361
362 let fail_and_prompt = |msg| {
363 println!("ā Failed to upgrade program {program_id}: {msg}.");
364 let count = transactions.len() - i - 1;
365 if count > 0 {
367 confirm("Do you want to continue with the next upgrade?", command.extra.yes)
368 } else {
369 Ok(false)
370 }
371 };
372
373 match status {
374 200..=299 => {
375 let status = check_transaction::check_transaction_with_message(
376 &id,
377 Some(&fee_id),
378 &endpoint,
379 network,
380 height_before + 1,
381 command.extra.max_wait,
382 command.extra.blocks_to_check,
383 )?;
384 if status == Some(TransactionStatus::Accepted) {
385 println!("ā
Upgrade confirmed!");
386 } else if fail_and_prompt("could not find the transaction on the network")? {
387 continue;
388 } else {
389 return Ok(());
390 }
391 }
392 _ => {
393 if fail_and_prompt(&message)? {
394 continue;
395 } else {
396 return Ok(());
397 }
398 }
399 }
400 }
401 }
402
403 Ok(())
404}
405
406fn check_tasks_for_warnings<N: Network>(
413 endpoint: &str,
414 network: NetworkName,
415 tasks: &[Task<N>],
416 consensus_version: ConsensusVersion,
417 command: &LeoUpgrade,
418) -> Vec<String> {
419 let mut warnings = Vec::new();
420 for Task { id, program, is_local, .. } in tasks {
421 if !is_local || !command.action.broadcast {
422 continue;
423 }
424
425 if let Ok(remote_program) = fetch_program_from_network(&id.to_string(), endpoint, network) {
427 let remote_program = match Program::<N>::from_str(&remote_program) {
429 Ok(program) => program,
430 Err(e) => {
431 warnings.push(format!("Could not parse '{id}' from the network. Error: {e}",));
432 continue;
433 }
434 };
435 if remote_program.contains_constructor() {
437 if let Err(e) = Stack::check_upgrade_is_valid(&remote_program, program) {
438 warnings.push(format!(
439 "The program '{id}' is not a valid upgrade. The upgrade will likely fail. Error: {e}",
440 ));
441 }
442 } else if consensus_version >= ConsensusVersion::V8 {
443 warnings.push(format!("The program '{id}' can only ever be upgraded once and its contents cannot be changed. Otherwise, the upgrade will likely fail."));
444 } else {
445 warnings.push(format!("The program '{id}' does not have a constructor and is not eligible for a one-time upgrade (>= `ConsensusVersion::V8`). The upgrade will likely fail."));
446 }
447 } else {
448 warnings.push(format!("The program '{id}' does not exist on the network. The upgrade will likely fail.",));
449 }
450 if consensus_version >= ConsensusVersion::V7
452 && let Err(e) = program.check_program_naming_structure()
453 {
454 warnings.push(format!(
455 "The program '{id}' has an invalid naming scheme: {e}. The deployment will likely fail."
456 ));
457 }
458 if let Err(e) = program.check_restricted_keywords_for_consensus_version(consensus_version) {
460 warnings.push(format!(
461 "The program '{id}' contains restricted keywords for consensus version {}: {e}. The deployment will likely fail.",
462 consensus_version as u8
463 ));
464 }
465 if consensus_version < ConsensusVersion::V9 && program.contains_v9_syntax() {
467 warnings.push(format!("The program '{id}' uses V9 features but the consensus version is less than V9. The upgrade will likely fail"));
468 }
469 if consensus_version >= ConsensusVersion::V9 && !program.contains_constructor() {
471 warnings.push(format!("The program '{id}' does not contain a constructor. The upgrade will likely fail",));
472 }
473 if let Err(e) = check_consensus_version_mismatch(consensus_version, endpoint, network) {
475 warnings.push(format!("{e}. In some cases, the deployment may fail"));
476 }
477 }
478 warnings
479}
480
481impl From<&LeoUpgrade> for LeoDeploy {
483 fn from(upgrade: &LeoUpgrade) -> Self {
484 Self {
485 fee_options: upgrade.fee_options.clone(),
486 action: upgrade.action.clone(),
487 env_override: upgrade.env_override.clone(),
488 extra: upgrade.extra.clone(),
489 skip: upgrade.skip.clone(),
490 build_options: upgrade.build_options.clone(),
491 }
492 }
493}