leo-lang 4.4.0

The Leo programming language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
// Copyright (C) 2019-2026 Provable Inc.
// This file is part of the Leo library.

// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.

#![forbid(unsafe_op_in_unsafe_fn)]

mod child_manager;
use child_manager::*;

#[cfg(windows)]
mod windows_kill_tree;

mod shutdown;
use shutdown::*;

mod utilities;
use utilities::*;

use anyhow::{Context as AnyhowContext, Result as AnyhowResult, anyhow, bail, ensure};
use chrono::Local;
use clap::Parser;
use dunce::canonicalize;
use itertools::Itertools;
use parking_lot::Mutex;
use std::{
    env,
    path::{Path, PathBuf},
    process::{Child, Command as StdCommand, Stdio},
    sync::Arc,
    time::Duration,
};
use tracing::{self, Span};

#[cfg(unix)]
use {libc::setsid, std::os::unix::process::CommandExt};

use super::*;
use leo_ast::NetworkName;

/// A high REST RPS (requests per second) for snarkOS devnets.
const REST_RPS: &str = "999999999";

/// Launch and manage a local devnet (validators + clients) using snarkOS.
#[derive(Parser, Debug)]
pub struct LeoDevnet {
    #[clap(long, help = "Number of validators", default_value = "4")]
    pub(crate) num_validators: usize,
    #[clap(long, help = "Number of clients", default_value = "2")]
    pub(crate) num_clients: usize,
    #[clap(short = 'n', long, help = "Network (mainnet=0, testnet=1, canary=2)", default_value = "testnet")]
    pub(crate) network: NetworkName,
    #[clap(short = 's', long, help = "Ledger / log root directory", default_value = "./")]
    pub(crate) storage: PathBuf,
    #[clap(long, help = "Path to snarkOS binary. If it does not exist, set `--install` to build it at this path.")]
    pub(crate) snarkos: Option<PathBuf>,
    #[clap(long, help = "Required features for snarkOS (e.g. `test_network`)", value_delimiter = ',')]
    pub(crate) snarkos_features: Vec<String>,
    #[clap(long, help = "Required version for snarkOS (e.g. `4.1.0`). Defaults to latest version on `crates.io`.")]
    pub(crate) snarkos_version: Option<String>,
    #[clap(long, help = "(Re)install snarkOS at the provided `--snarkos` path with the given `--snarkos-features`")]
    pub(crate) install: bool,
    #[clap(
        long,
        help = "Optional consensus heights to use. The `test_network` feature must be enabled for this to work.",
        value_delimiter = ',',
        env = "CONSENSUS_VERSION_HEIGHTS"
    )]
    pub(crate) consensus_heights: Option<Vec<u32>>,
    #[clap(long, help = "Run nodes in tmux (only available on Unix)")]
    pub(crate) tmux: bool,
    #[clap(short = 'v', long, help = "snarkOS verbosity (0-4)", default_value = "1")]
    pub(crate) verbosity: u8,
    #[clap(long, short = 'y', help = "Skip confirmation prompts and proceed with the devnet startup")]
    pub(crate) yes: bool,
    #[clap(long, help = "Base REST port (each node uses base + dev_index)")]
    pub(crate) rest_port: Option<u16>,
    #[clap(long, help = "Base node port (each node uses base + dev_index)")]
    pub(crate) node_port: Option<u16>,
    #[clap(long, help = "Base BFT port (each node uses base + dev_index)")]
    pub(crate) bft_port: Option<u16>,
    #[clap(long, help = "Base metrics port (each validator uses base + dev_index)")]
    pub(crate) metrics_port: Option<u16>,
    #[clap(short = 'c', long, help = "Remove existing devnet storage before starting")]
    pub(crate) clear_storage: bool,
    #[clap(long, help = "Only clean devnet storage (ledgers, node data, logs) without starting")]
    pub(crate) clean_only: bool,
}

impl Command for LeoDevnet {
    type Input = ();
    type Output = ();

    fn log_span(&self) -> Span {
        tracing::span!(tracing::Level::INFO, "LeoDevnet")
    }

    fn prelude(&self, _: Context) -> Result<Self::Input> {
        Ok(())
    }

    fn apply(self, _cx: Context, _: Self::Input) -> Result<Self::Output> {
        self.handle_apply().map_err(|e| crate::errors::custom(format!("Failed to run devnet command: {e}")).into())
    }
}

impl LeoDevnet {
    /// Handle the actual devnet logic.
    fn handle_apply(&self) -> AnyhowResult<()> {
        //โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        // Clean-only mode: just remove storage artifacts and exit.
        //โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        if self.clean_only {
            return self.handle_clean();
        }

        //โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        // 0. Guard rails
        //โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        let snarkos_path = self.snarkos.as_ref().ok_or_else(|| {
            anyhow!(
                "The `--snarkos` flag is required when starting a devnet. Use `--clean-only` to only clean storage."
            )
        })?;

        if cfg!(windows) && self.tmux {
            bail!("tmux mode is not available on Windows โ€“ remove `--tmux`.");
        }
        if self.tmux && std::env::var("TMUX").is_ok() {
            bail!("Nested tmux session detected.  Unset $TMUX and retry.");
        }

        // If the devnet heights are provided, ensure the `test_network` feature is enabled, and validate the heights.
        if let Some(ref heights) = self.consensus_heights {
            if !self.snarkos_features.contains(&"test_network".to_string()) {
                bail!("The `test_network` feature must be enabled on snarkOS to use `--consensus-heights`.");
            }
            validate_consensus_heights(heights.as_slice())?;
        }

        // Validate the number of validators.
        if self.num_validators < 4 {
            bail!("The number of validators must be at least 4.");
        }

        // Validate port ranges won't overflow with the number of nodes.
        let total_nodes = self.num_validators + self.num_clients;
        Self::validate_port_range("--rest-port", self.rest_port, total_nodes)?;
        Self::validate_port_range("--node-port", self.node_port, total_nodes)?;
        Self::validate_port_range("--bft-port", self.bft_port, total_nodes)?;
        Self::validate_port_range("--metrics-port", self.metrics_port, self.num_validators)?;

        // Resolve the snarkOS path to its canonical form.
        if self.install {
            // If installing, make sure we can write to a file at the path.
            if let Some(parent) = snarkos_path.parent()
                && !parent.exists()
            {
                std::fs::create_dir_all(parent)
                    .with_context(|| format!("Failed to create directory for binary: {}", parent.display()))?;
            }
            std::fs::write(snarkos_path, [0u8]).with_context(|| {
                format!("Failed to write to path {} for snarkos installation", snarkos_path.display())
            })?;
        } else {
            // If not installing, ensure the snarkOS binary exists at the provided path.
            if !snarkos_path.exists() {
                bail!(
                    "The snarkOS binary at `{}` does not exist. Please provide a valid path or use `--install`.",
                    snarkos_path.display()
                );
            }
        };
        let snarkos = canonicalize(snarkos_path)
            .with_context(|| format!("Failed to resolve snarkOS path: {}", snarkos_path.display()))?;

        // Confirm with the user the options they provided.
        println!("๐Ÿ”ง  Starting devnet with the following options:");
        println!("  โ€ข Network: {}", self.network);
        println!("  โ€ข Validators: {}", self.num_validators);
        println!("  โ€ข Clients: {}", self.num_clients);
        println!("  โ€ข Storage: {}", self.storage.display());
        if self.install {
            println!("  โ€ข Installing snarkOS at: {}", snarkos.display());
            if let Some(ref version) = self.snarkos_version {
                println!("  โ€ข version: {version}");
            }
            if !self.snarkos_features.is_empty() {
                println!("  โ€ข features: {}", self.snarkos_features.iter().format(","));
            }
        } else {
            println!("  โ€ข Using snarkOS binary at: {}", snarkos.display());
        }
        if let Some(heights) = &self.consensus_heights {
            println!("  โ€ข Consensus heights: {}", heights.iter().format(","));
        } else {
            println!("  โ€ข Consensus heights: default (based on your snarkOS binary)");
        }
        println!("  โ€ข Clear storage: {}", if self.clear_storage { "yes" } else { "no" });
        println!("  โ€ข Verbosity: {}", self.verbosity);
        println!("  โ€ข tmux: {}", if self.tmux { "yes" } else { "no" });

        //โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        // 1. Child-manager & shutdown listener (no race!)
        //โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        let manager = Arc::new(Mutex::new(ChildManager::new()));

        // Install the listener to catch any early shutdown signals.
        let (tx_shutdown, rx_shutdown) = crossbeam_channel::bounded::<()>(1);
        let _signal_thread =
            install_shutdown_listener(tx_shutdown.clone()).context("Failed to install shutdown listener")?;

        //โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        // 2. snarkOS binary  (+ optional build)
        //โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        let snarkos = if self.install {
            if !confirm("\nProceed with snarkOS installation?", self.yes)? {
                println!("โŒ Installation aborted.");
                return Ok(());
            }
            install_snarkos(&snarkos, self.snarkos_version.as_deref(), &self.snarkos_features)?
        } else {
            snarkos
        };

        // Run `snarkOS --version` and confirm with the user that they'd like to proceed.
        let version_output = StdCommand::new(&snarkos)
            .arg("--version")
            .output()
            .context(format!("Failed to run `{}`", snarkos.display()))?;
        if !version_output.status.success() {
            bail!("Failed to run `{}`: {}", snarkos.display(), String::from_utf8_lossy(&version_output.stderr));
        }

        // Print the version output.
        let version_str = String::from_utf8_lossy(&version_output.stdout);
        println!("๐Ÿ”  Detected: {version_str}");

        // The version string has the following form:
        // "snarkos refs/heads/staging ace765a42551092fbb47799c2651d6b6df30e49a features=[default,snarkos_node_metrics,test_network]"
        // Parse the features and see if it matches the expected features.
        let features_str = version_str
            .trim()
            .split("features=[")
            .nth(1)
            .and_then(|s| s.split(']').next())
            .ok_or_else(|| anyhow!("Failed to parse snarkOS features from version string: {version_str}"))?;
        let found_features: Vec<String> = features_str.split(',').map(|s| s.trim().to_string()).collect();
        for feature in &self.snarkos_features {
            if !found_features.contains(feature) {
                println!("โš ๏ธ  Warning: snarkOS does not have the required feature `{feature}` enabled.");
            }
        }

        if !confirm("\nProceed with devnet startup?", self.yes)? {
            println!("โŒ Devnet aborted.");
            return Ok(());
        }

        //โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        // 3. Resolve storage & create log dir
        //โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        // Create the storage directory if it does not exist.
        if !self.storage.exists() {
            std::fs::create_dir_all(&self.storage)
                .context(format!("Failed to create storage directory: {}", self.storage.display()))?;
        } else if !self.storage.is_dir() {
            bail!("The storage path `{}` is not a directory.", self.storage.display());
        }
        // Resolve the storage directory to its canonical form.
        let storage = canonicalize(&self.storage)
            .with_context(|| format!("Failed to resolve storage path: {}", self.storage.display()))?;

        // Optionally clear previous devnet artifacts before starting.
        if self.clear_storage {
            println!("๐Ÿงน  Cleaning ledgers โ€ฆ");
            let mut cleaners = Vec::new();
            for idx in 0..self.num_validators {
                cleaners.push(clean_snarkos(
                    &snarkos,
                    self.network as usize,
                    idx,
                    &storage.join(format!("node-{idx}")),
                    &storage.join(format!("node-data-{idx}")),
                )?);
            }
            for idx in 0..self.num_clients {
                let dev_idx = idx + self.num_validators;
                cleaners.push(clean_snarkos(
                    &snarkos,
                    self.network as usize,
                    dev_idx,
                    &storage.join(format!("node-{dev_idx}")),
                    &storage.join(format!("node-data-{dev_idx}")),
                )?);
            }
            for mut c in cleaners {
                c.wait()?;
            }
        }

        // Create the log directory inside the storage directory.
        let log_dir = {
            let ts = Local::now().format(".logs-%Y-%m-%d-%H-%M-%S").to_string();
            let p = storage.join(ts);
            std::fs::create_dir_all(&p)?;
            p
        };

        //โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        // 4. Spawn nodes (tmux **or** background)
        //โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

        #[allow(clippy::too_many_arguments)]
        fn build_args(
            role: &str,
            verbosity: u8,
            network: usize,
            num_validators: usize,
            num_nodes: usize,
            idx: usize,
            log_file: &Path,
            storage: &Path,
            rest_port: Option<u16>,
            node_port: Option<u16>,
            bft_port: Option<u16>,
            metrics_port: Option<u16>,
        ) -> Vec<String> {
            let idx_u16 = idx as u16;
            let mut base = vec![
                "start".to_string(),
                "--nodisplay".to_string(),
                "--network".to_string(),
                network.to_string(),
                "--dev".to_string(),
                idx.to_string(),
                "--dev-num-validators".to_string(),
                num_validators.to_string(),
                "--rest-rps".to_string(),
                REST_RPS.to_string(),
                "--logfile".to_string(),
                log_file.to_str().expect("log path is valid UTF-8").to_string(),
                "--verbosity".to_string(),
                verbosity.to_string(),
                "--ledger-storage".to_string(),
                storage.join(format!("node-{idx}")).to_str().expect("storage path is valid UTF-8").to_string(),
                "--node-data-storage".to_string(),
                storage.join(format!("node-data-{idx}")).to_str().expect("node-data path is valid UTF-8").to_string(),
            ];
            if let Some(port) = rest_port {
                // Port overflow is validated upfront in handle_apply.
                base.extend(["--rest".into(), format!("0.0.0.0:{}", port + idx_u16)]);
            }
            if let Some(port) = node_port {
                base.extend(["--node".into(), format!("0.0.0.0:{}", port + idx_u16)]);
                // In dev mode, snarkOS auto-generates --peers using default port offsets (4130+N).
                // When custom node ports are used, we must provide --peers explicitly so nodes
                // can discover each other at the correct addresses.
                let peers: String =
                    (0..num_nodes).map(|i| format!("127.0.0.1:{}", port + i as u16)).collect::<Vec<_>>().join(",");
                base.extend(["--peers".into(), peers]);
            }
            if let Some(port) = bft_port {
                base.extend(["--bft".into(), format!("0.0.0.0:{}", port + idx_u16)]);
                // In dev mode, snarkOS auto-generates --validators using default BFT port offsets
                // (5000+N). When custom BFT ports are used, provide --validators explicitly so
                // the BFT layer can discover peers at the correct addresses.
                let validators: String =
                    (0..num_validators).map(|i| format!("127.0.0.1:{}", port + i as u16)).collect::<Vec<_>>().join(",");
                base.extend(["--validators".into(), validators]);
            }
            match role {
                "validator" => {
                    base.extend(
                        ["--allow-external-peers", "--validator", "--no-dev-txs"].into_iter().map(String::from),
                    );
                    if let Some(port) = metrics_port {
                        base.extend(["--metrics".into(), "--metrics-ip".into(), format!("0.0.0.0:{}", port + idx_u16)]);
                    }
                }
                "client" => base.push("--client".into()),
                _ => unreachable!(),
            }
            base
        }

        // Set the environment variable for the consensus heights if provided.
        // These are used by all child processes.
        if let Some(ref heights) = self.consensus_heights {
            let heights = heights.iter().join(",");
            println!("๐Ÿ”ง  Setting consensus heights: {heights}");
            #[allow(unsafe_code)]
            unsafe {
                // SAFETY:
                //  - `CONSENSUS_VERSION_HEIGHTS` is only set once and is only read in `snarkvm::prelude::load_consensus_heights`.
                //  - There are no concurrent threads running at this point in the execution.
                // WHY:
                //  - This is needed because there is no way to set the desired consensus heights for a particular `VM` instance in a node
                //    without using the environment variable `CONSENSUS_VERSION_HEIGHTS`. Which is itself read once, and stored in a `OnceLock`.
                env::set_var("CONSENSUS_VERSION_HEIGHTS", heights);
            }
        }

        //โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ tmux branch โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        if self.tmux {
            // Create session.
            let mut args: Vec<String> =
                vec!["new-session", "-d", "-s", "devnet", "-n", "validator-0"].into_iter().map(Into::into).collect();

            // If a tmux server is already running, the new session will inherit the environment
            // variables of the server. As such, we need to explicitly set the CONSENSUS_VERSION_HEIGHTS
            // env var in the new session we are creatomg.
            if let Some(ref heights) = self.consensus_heights {
                let heights = heights.iter().join(",");
                args.push("-e".to_string());
                args.push(format!("CONSENSUS_VERSION_HEIGHTS={heights}"));
            }

            ensure!(StdCommand::new("tmux").args(args).status()?.success(), "tmux failed to create session");

            let num_nodes = self.num_validators + self.num_clients;

            // Determine base-index.
            let base_index = {
                let out = StdCommand::new("tmux").args(["show-option", "-gv", "base-index"]).output()?;
                String::from_utf8_lossy(&out.stdout).trim().parse::<usize>().unwrap_or(0)
            };

            // Validators
            for idx in 0..self.num_validators {
                let win_idx = idx + base_index;
                let window_name = format!("validator-{idx}");
                if idx != 0 {
                    StdCommand::new("tmux")
                        .args(["new-window", "-t", &format!("devnet:{win_idx}"), "-n", &window_name])
                        .status()?;
                }
                let log_file = log_dir.join(format!("{window_name}.log"));
                let cmd = std::iter::once(snarkos.to_string_lossy().into_owned())
                    .chain(build_args(
                        "validator",
                        self.verbosity,
                        self.network as usize,
                        self.num_validators,
                        num_nodes,
                        idx,
                        log_file.as_path(),
                        &storage,
                        self.rest_port,
                        self.node_port,
                        self.bft_port,
                        self.metrics_port,
                    ))
                    .collect::<Vec<_>>()
                    .join(" ");
                StdCommand::new("tmux")
                    .args(["send-keys", "-t", &format!("devnet:{win_idx}"), &cmd, "C-m"])
                    .status()?;
            }

            // Clients
            for idx in 0..self.num_clients {
                let dev_idx = idx + self.num_validators;
                let win_idx = dev_idx + base_index;
                let window_name = format!("client-{idx}");
                StdCommand::new("tmux")
                    .args(["new-window", "-t", &format!("devnet:{win_idx}"), "-n", &window_name])
                    .status()?;
                let log_file = log_dir.join(format!("{window_name}.log"));
                let cmd = std::iter::once(snarkos.to_string_lossy().into_owned())
                    .chain(build_args(
                        "client",
                        self.verbosity,
                        self.network as usize,
                        self.num_validators,
                        num_nodes,
                        dev_idx,
                        log_file.as_path(),
                        &storage,
                        self.rest_port,
                        self.node_port,
                        self.bft_port,
                        None,
                    ))
                    .collect::<Vec<_>>()
                    .join(" ");
                StdCommand::new("tmux")
                    .args(["send-keys", "-t", &format!("devnet:{win_idx}"), &cmd, "C-m"])
                    .status()?;
            }

            println!("โœ…  tmux session \"devnet\" is ready โ€“ attaching โ€ฆ");
            StdCommand::new("tmux").args(["attach-session", "-t", "devnet"]).status()?;
            return Ok(()); // tmux will hold the terminal
        }

        //โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ background branch โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        println!("โš™๏ธ  Spawning nodes as background tasks โ€ฆ");

        // Helper: setsid() on Unix, Job-object attach on Windows.
        let spawn_with_group = |mut cmd: StdCommand, log_file: &Path| -> AnyhowResult<Child> {
            let log_handle = std::fs::OpenOptions::new().create(true).append(true).open(log_file)?;
            cmd.stdout(Stdio::from(log_handle.try_clone()?));
            cmd.stderr(Stdio::from(log_handle));

            #[cfg(unix)]
            #[allow(unsafe_code)]
            unsafe {
                // SAFETY: We are in the child just before exec; setsid() only
                // affects the child and cannot violate Rust invariants.
                cmd.pre_exec(|| {
                    setsid();
                    Ok(())
                });
            }

            let child = cmd.spawn().map_err(|e| anyhow!("spawn {e}"))?;

            #[cfg(windows)]
            windows_kill_tree::attach_to_global_job(child.id())?;

            Ok(child)
        };

        let num_nodes = self.num_validators + self.num_clients;

        {
            // This should be safe since only the current thread will write to the manager.
            let mut guard = manager.lock();

            // Validators
            for idx in 0..self.num_validators {
                let log_file = log_dir.join(format!("validator-{idx}.log"));
                let child = spawn_with_group(
                    {
                        let mut c = StdCommand::new(&snarkos);
                        c.args(build_args(
                            "validator",
                            self.verbosity,
                            self.network as usize,
                            self.num_validators,
                            num_nodes,
                            idx,
                            &log_file,
                            &storage,
                            self.rest_port,
                            self.node_port,
                            self.bft_port,
                            self.metrics_port,
                        ));
                        c
                    },
                    &log_file,
                )?;
                println!("  โ€ข validator {idx}  (pid = {})", child.id());
                guard.push(child);
            }

            // Clients
            for idx in 0..self.num_clients {
                let dev_idx = idx + self.num_validators;
                let log_file = log_dir.join(format!("client-{idx}.log"));
                let child = spawn_with_group(
                    {
                        let mut c = StdCommand::new(&snarkos);
                        c.args(build_args(
                            "client",
                            self.verbosity,
                            self.network as usize,
                            self.num_validators,
                            num_nodes,
                            dev_idx,
                            &log_file,
                            &storage,
                            self.rest_port,
                            self.node_port,
                            self.bft_port,
                            None,
                        ));
                        c
                    },
                    &log_file,
                )?;
                println!("  โ€ข client    {idx}  (pid = {})", child.id());
                guard.push(child);
            }
        }

        // Print the main process ID.
        println!("๐Ÿ“Œ  Main process ID: {}", std::process::id());
        println!("\nDevnet running โ€“ Ctrl+C, SIGTERM, or terminal close to stop.");

        // Block here until the first (coalesced) shutdown request
        let _ = rx_shutdown.recv();
        manager.lock().shutdown_all(Duration::from_secs(30));

        Ok(())
    }

    /// Handle clean-only mode: delegate to `snarkos clean` for each dev node,
    /// then remove Leo-specific log directories.
    fn handle_clean(&self) -> AnyhowResult<()> {
        let snarkos_path = self.snarkos.as_ref().ok_or_else(|| {
            anyhow!("The `--snarkos` flag is required for `--clean-only`. Provide the path to the snarkOS binary.")
        })?;
        if !snarkos_path.exists() {
            bail!("The snarkOS binary at `{}` does not exist.", snarkos_path.display());
        }
        let snarkos = canonicalize(snarkos_path)?;

        if !self.storage.exists() {
            println!("Storage path `{}` does not exist. Nothing to clean.", self.storage.display());
            return Ok(());
        }
        if !self.storage.is_dir() {
            bail!("Storage path `{}` is not a directory.", self.storage.display());
        }
        let storage = canonicalize(&self.storage)?;

        let total_nodes = self.num_validators + self.num_clients;
        if !confirm(
            &format!("\nClean devnet storage for {total_nodes} nodes in `{}`?", self.storage.display()),
            self.yes,
        )? {
            println!("Aborted.");
            return Ok(());
        }

        println!("๐Ÿงน  Cleaning ledgers โ€ฆ");
        let mut cleaners = Vec::new();
        for idx in 0..self.num_validators {
            cleaners.push(clean_snarkos(
                &snarkos,
                self.network as usize,
                idx,
                &storage.join(format!("node-{idx}")),
                &storage.join(format!("node-data-{idx}")),
            )?);
        }
        for idx in 0..self.num_clients {
            let dev_idx = idx + self.num_validators;
            cleaners.push(clean_snarkos(
                &snarkos,
                self.network as usize,
                dev_idx,
                &storage.join(format!("node-{dev_idx}")),
                &storage.join(format!("node-data-{dev_idx}")),
            )?);
        }
        for mut c in cleaners {
            c.wait()?;
        }

        // Remove Leo-specific log directories that snarkOS does not manage.
        for entry in std::fs::read_dir(&storage)? {
            let entry = entry?;
            let name = entry.file_name();
            let name = name.to_string_lossy();
            if entry.file_type()?.is_dir() && name.starts_with(".logs-") {
                std::fs::remove_dir_all(entry.path())?;
                println!("  Removed {}", entry.path().display());
            }
        }

        println!("Cleaned devnet storage.");
        Ok(())
    }

    /// Validate that `base_port + count` doesn't overflow u16.
    fn validate_port_range(flag: &str, base: Option<u16>, count: usize) -> AnyhowResult<()> {
        if let Some(port) = base {
            if count == 0 {
                return Ok(());
            }
            let max_idx = (count - 1) as u16;
            if port.checked_add(max_idx).is_none() {
                bail!("{flag} {port} + {max_idx} nodes exceeds the maximum port number (65535).");
            }
        }
        Ok(())
    }
}