node-launchpad 0.6.4

TUI for running nodes on the Autonomi network
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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
// Copyright 2025 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.

use crate::action::{Action, StatusActions};
use crate::connection_mode::ConnectionMode;
use ant_bootstrap::InitialPeersConfig;
use ant_evm::{EvmNetwork, RewardsAddress};
use ant_node_manager::{VerbosityLevel, add_services::config::PortRange};
use ant_releases::{self, AntReleaseRepoActions, ReleaseType};
use ant_service_management::{NodeRegistryManager, ServiceStatus};
use color_eyre::Result;
use color_eyre::eyre::eyre;
use service_manager::RestartPolicy;
use std::{path::PathBuf, str::FromStr};
use tokio::runtime::Builder;
use tokio::sync::mpsc::{self, UnboundedSender};
use tokio::task::LocalSet;

pub const PORT_MAX: u32 = 65535;
pub const PORT_MIN: u32 = 1024;

const NODE_ADD_MAX_RETRIES: u32 = 5;

pub const FIXED_INTERVAL: u64 = 60_000;
pub const CONNECTION_TIMEOUT_START: u64 = 120;

pub const NODES_ALL: &str = "NODES_ALL";

#[derive(Debug)]
pub enum NodeManagementTask {
    MaintainNodes {
        args: MaintainNodesArgs,
    },
    ResetNodes {
        start_nodes_after_reset: bool,
        action_sender: UnboundedSender<Action>,
    },
    StopNodes {
        services: Vec<String>,
        action_sender: UnboundedSender<Action>,
    },
    UpgradeNodes {
        args: UpgradeNodesArgs,
    },
    AddNode {
        args: MaintainNodesArgs,
    },
    RemoveNodes {
        services: Vec<String>,
        action_sender: UnboundedSender<Action>,
    },
    StartNode {
        services: Vec<String>,
        action_sender: UnboundedSender<Action>,
    },
}

#[derive(Clone)]
pub struct NodeManagement {
    task_sender: mpsc::UnboundedSender<NodeManagementTask>,
}

impl NodeManagement {
    pub fn new(node_registry: NodeRegistryManager) -> Result<Self> {
        let (send, mut recv) = mpsc::unbounded_channel();

        let rt = Builder::new_current_thread().enable_all().build()?;

        std::thread::spawn(move || {
            let local = LocalSet::new();

            local.spawn_local(async move {
                while let Some(new_task) = recv.recv().await {
                    match new_task {
                        NodeManagementTask::MaintainNodes { args } => {
                            maintain_n_running_nodes(args, node_registry.clone()).await;
                        }
                        NodeManagementTask::ResetNodes {
                            start_nodes_after_reset,
                            action_sender,
                        } => {
                            reset_nodes(
                                action_sender,
                                node_registry.clone(),
                                start_nodes_after_reset,
                            )
                            .await;
                        }
                        NodeManagementTask::StopNodes {
                            services,
                            action_sender,
                        } => {
                            stop_nodes(services, action_sender, node_registry.clone()).await;
                        }
                        NodeManagementTask::UpgradeNodes { args } => {
                            upgrade_nodes(args, node_registry.clone()).await
                        }
                        NodeManagementTask::RemoveNodes {
                            services,
                            action_sender,
                        } => remove_nodes(services, action_sender, node_registry.clone()).await,
                        NodeManagementTask::StartNode {
                            services,
                            action_sender,
                        } => start_nodes(services, action_sender, node_registry.clone()).await,
                        NodeManagementTask::AddNode { args } => {
                            add_node(args, node_registry.clone()).await
                        }
                    }
                }
                // If the while loop returns, then all the LocalSpawner
                // objects have been dropped.
            });

            // This will return once all senders are dropped and all
            // spawned tasks have returned.
            rt.block_on(local);
        });

        Ok(Self { task_sender: send })
    }

    /// Send a task to the NodeManagement local set
    /// These tasks will be executed on a different thread to avoid blocking the main thread
    ///
    /// The results are returned via the standard `UnboundedSender<Action>` that is passed to each task.
    ///
    /// If this function returns an error, it means that the task could not be sent to the local set.
    pub fn send_task(&self, task: NodeManagementTask) -> Result<()> {
        self.task_sender
            .send(task)
            .inspect_err(|err| error!("The node management local set is down {err:?}"))
            .map_err(|_| eyre!("Failed to send task to the node management local set"))?;
        Ok(())
    }
}

/// Stop the specified services
async fn stop_nodes(
    services: Vec<String>,
    action_sender: UnboundedSender<Action>,
    node_registry: NodeRegistryManager,
) {
    if let Err(err) = ant_node_manager::cmd::node::stop(
        None,
        node_registry.clone(),
        vec![],
        services.clone(),
        VerbosityLevel::Minimal,
    )
    .await
    {
        error!("Error while stopping services {err:?}");
        send_action(
            action_sender,
            Action::StatusActions(StatusActions::ErrorStoppingNodes {
                services,
                raw_error: err.to_string(),
            }),
        );
    } else {
        info!("Successfully stopped services");
        for service in services {
            send_action(
                action_sender.clone(),
                Action::StatusActions(StatusActions::StopNodesCompleted {
                    service_name: service,
                    all_nodes_data: node_registry.get_node_service_data().await,
                    is_nat_status_determined: node_registry.nat_status.read().await.is_some(),
                }),
            );
        }
    }
}

#[derive(Debug)]
pub struct MaintainNodesArgs {
    pub action_sender: UnboundedSender<Action>,
    pub antnode_path: Option<PathBuf>,
    pub connection_mode: ConnectionMode,
    pub count: u16,
    pub data_dir_path: Option<PathBuf>,
    pub network_id: Option<u8>,
    pub owner: String,
    pub init_peers_config: InitialPeersConfig,
    pub port_range: Option<PortRange>,
    pub rewards_address: String,
    pub run_nat_detection: bool,
}

/// Maintain the specified number of nodes
async fn maintain_n_running_nodes(args: MaintainNodesArgs, node_registry: NodeRegistryManager) {
    debug!("Maintaining {} nodes", args.count);
    if args.run_nat_detection {
        run_nat_detection(&args.action_sender).await;
    }

    let config = prepare_node_config(&args);
    debug_log_config(&config, &args);

    let mut used_ports = get_used_ports(&node_registry).await;
    let (mut current_port, max_port) = get_port_range(&config.custom_ports);

    let mut non_removed_nodes = 0;
    for node in node_registry.nodes.read().await.iter() {
        let node = node.read().await;
        if node.status != ServiceStatus::Removed {
            non_removed_nodes += 1;
        }
    }
    let nodes_to_add = args.count as i32 - non_removed_nodes;

    if nodes_to_add <= 0 {
        debug!("Scaling down nodes to {}", nodes_to_add);
        scale_down_nodes(&config, args.count, node_registry.clone()).await;
    } else {
        debug!("Scaling up nodes to {}", nodes_to_add);
        add_nodes(
            &args.action_sender,
            &config,
            nodes_to_add,
            &mut used_ports,
            &mut current_port,
            max_port,
            node_registry.clone(),
        )
        .await;
    }

    debug!("Finished maintaining {} nodes", args.count);
    send_action(
        args.action_sender,
        Action::StatusActions(StatusActions::StartNodesCompleted {
            service_name: NODES_ALL.to_string(),
            all_nodes_data: node_registry.get_node_service_data().await,
            is_nat_status_determined: node_registry.nat_status.read().await.is_some(),
        }),
    );
}

/// Reset all the nodes
async fn reset_nodes(
    action_sender: UnboundedSender<Action>,
    node_registry: NodeRegistryManager,
    start_nodes_after_reset: bool,
) {
    if let Err(err) =
        ant_node_manager::cmd::node::reset(true, node_registry.clone(), VerbosityLevel::Minimal)
            .await
    {
        error!("Error while resetting services {err:?}");
        send_action(
            action_sender,
            Action::StatusActions(StatusActions::ErrorResettingNodes {
                raw_error: err.to_string(),
            }),
        );
    } else {
        info!("Successfully reset services");
        send_action(
            action_sender,
            Action::StatusActions(StatusActions::ResetNodesCompleted {
                trigger_start_node: start_nodes_after_reset,
                all_nodes_data: node_registry.get_node_service_data().await,
                is_nat_status_determined: node_registry.nat_status.read().await.is_some(),
            }),
        );
    }
}

#[derive(Debug)]
pub struct UpgradeNodesArgs {
    pub action_sender: UnboundedSender<Action>,
    pub connection_timeout_s: u64,
    pub do_not_start: bool,
    pub custom_bin_path: Option<PathBuf>,
    pub force: bool,
    pub fixed_interval: Option<u64>,
    pub peer_ids: Vec<String>,
    pub provided_env_variables: Option<Vec<(String, String)>>,
    pub service_names: Vec<String>,
    pub url: Option<String>,
    pub version: Option<String>,
}

async fn upgrade_nodes(args: UpgradeNodesArgs, node_registry: NodeRegistryManager) {
    // First we stop the Nodes
    if let Err(err) = ant_node_manager::cmd::node::stop(
        None,
        node_registry.clone(),
        vec![],
        args.service_names.clone(),
        VerbosityLevel::Minimal,
    )
    .await
    {
        error!("Error while stopping services {err:?}");
        send_action(
            args.action_sender.clone(),
            Action::StatusActions(StatusActions::ErrorUpdatingNodes {
                raw_error: err.to_string(),
            }),
        );
    }

    if let Err(err) = ant_node_manager::cmd::node::upgrade(
        0, // will be overwrite by FIXED_INTERVAL
        args.do_not_start,
        args.custom_bin_path,
        args.force,
        Some(FIXED_INTERVAL),
        node_registry.clone(),
        args.peer_ids,
        args.provided_env_variables,
        args.service_names,
        args.url,
        args.version,
        VerbosityLevel::Minimal,
    )
    .await
    {
        error!("Error while updating services {err:?}");
        send_action(
            args.action_sender,
            Action::StatusActions(StatusActions::ErrorUpdatingNodes {
                raw_error: err.to_string(),
            }),
        );
    } else {
        info!("Successfully updated services");
        send_action(
            args.action_sender,
            Action::StatusActions(StatusActions::UpdateNodesCompleted {
                all_nodes_data: node_registry.get_node_service_data().await,
                is_nat_status_determined: node_registry.nat_status.read().await.is_some(),
            }),
        );
    }
}

async fn remove_nodes(
    services: Vec<String>,
    action_sender: UnboundedSender<Action>,
    node_registry: NodeRegistryManager,
) {
    // First we stop the nodes
    if let Err(err) = ant_node_manager::cmd::node::stop(
        None,
        node_registry.clone(),
        vec![],
        services.clone(),
        VerbosityLevel::Minimal,
    )
    .await
    {
        error!("Error while stopping services {err:?}");
        send_action(
            action_sender.clone(),
            Action::StatusActions(StatusActions::ErrorRemovingNodes {
                services: services.clone(),
                raw_error: err.to_string(),
            }),
        );
    }

    if let Err(err) = ant_node_manager::cmd::node::remove(
        false,
        vec![],
        node_registry.clone(),
        services.clone(),
        VerbosityLevel::Minimal,
    )
    .await
    {
        error!("Error while removing services {err:?}");
        send_action(
            action_sender,
            Action::StatusActions(StatusActions::ErrorRemovingNodes {
                services,
                raw_error: err.to_string(),
            }),
        );
    } else {
        info!("Successfully removed services {:?}", services);
        for service in services {
            send_action(
                action_sender.clone(),
                Action::StatusActions(StatusActions::RemoveNodesCompleted {
                    service_name: service,
                    all_nodes_data: node_registry.get_node_service_data().await,
                    is_nat_status_determined: node_registry.nat_status.read().await.is_some(),
                }),
            );
        }
    }
}

async fn add_node(args: MaintainNodesArgs, node_registry: NodeRegistryManager) {
    debug!("Adding node");

    if args.run_nat_detection {
        run_nat_detection(&args.action_sender).await;
    }

    let config = prepare_node_config(&args);

    let used_ports = get_used_ports(&node_registry).await;
    let (mut current_port, max_port) = get_port_range(&config.custom_ports);

    while used_ports.contains(&current_port) && current_port <= max_port {
        current_port += 1;
    }

    if current_port > max_port {
        error!("Reached maximum port number. Unable to find an available port.");
        send_action(
            args.action_sender.clone(),
            Action::StatusActions(StatusActions::ErrorAddingNodes {
                raw_error: format!(
                    "When adding a new node we reached maximum port number ({max_port}).\nUnable to find an available port."
                ),
            }),
        );
    }

    let port_range = Some(PortRange::Single(current_port));
    match ant_node_manager::cmd::node::add(
        false, // alpha,
        false, // auto_restart,
        config.auto_set_nat_flags,
        Some(config.count),
        config.data_dir_path,
        true,       // enable_metrics_server,
        None,       // env_variables,
        None,       // evm_network
        None,       // log_dir_path,
        None,       // log_format,
        None,       // max_archived_log_files,
        None,       // max_log_files,
        None,       // metrics_port,
        None,       // network_id
        None,       // node_ip,
        port_range, // node_port
        node_registry.clone(),
        config.init_peers_config.clone(),
        config.relay, // relay,
        get_restart_policy(),
        RewardsAddress::from_str(config.rewards_address.as_str()).unwrap(),
        None,                        // rpc_address,
        None,                        // rpc_port,
        config.antnode_path.clone(), // src_path,
        !config.upnp,
        None, // url,
        None, // user,
        None, // version,
        VerbosityLevel::Minimal,
        false, // write_older_cache_files
    )
    .await
    {
        Err(err) => {
            error!("Error while adding services {err:?}");
            send_action(
                args.action_sender,
                Action::StatusActions(StatusActions::ErrorAddingNodes {
                    raw_error: err.to_string(),
                }),
            );
        }
        Ok(services) => {
            info!("Successfully added services: {:?}", services);
            for service in services {
                send_action(
                    args.action_sender.clone(),
                    Action::StatusActions(StatusActions::AddNodesCompleted {
                        service_name: service,
                        all_nodes_data: node_registry.get_node_service_data().await,
                        is_nat_status_determined: node_registry.nat_status.read().await.is_some(),
                    }),
                );
            }
        }
    }
}

async fn start_nodes(
    services: Vec<String>,
    action_sender: UnboundedSender<Action>,
    node_registry: NodeRegistryManager,
) {
    debug!("Starting node {:?}", services);
    if let Err(err) = ant_node_manager::cmd::node::start(
        CONNECTION_TIMEOUT_START,
        None,
        node_registry.clone(),
        vec![],
        services.clone(),
        VerbosityLevel::Minimal,
    )
    .await
    {
        error!("Error while starting services {err:?}");
        send_action(
            action_sender,
            Action::StatusActions(StatusActions::ErrorStartingNodes {
                services,
                raw_error: err.to_string(),
            }),
        );
    } else {
        info!("Successfully started services {:?}", services);
        for service in services {
            send_action(
                action_sender.clone(),
                Action::StatusActions(StatusActions::StartNodesCompleted {
                    service_name: service,
                    all_nodes_data: node_registry.get_node_service_data().await,
                    is_nat_status_determined: node_registry.nat_status.read().await.is_some(),
                }),
            );
        }
    }
}

// --- Helper functions ---

/// Get the appropriate restart policy for the current platform
#[cfg(unix)]
fn get_restart_policy() -> RestartPolicy {
    RestartPolicy::OnSuccess { delay_secs: None }
}

#[cfg(windows)]
fn get_restart_policy() -> RestartPolicy {
    // Use OnFailure so that WinSW restarts the service when the node exits with a non-zero
    // code (e.g., exit code 100 after an auto-upgrade).
    RestartPolicy::OnFailure {
        delay_secs: None,
        max_retries: None,
        reset_after_secs: None,
    }
}

fn send_action(action_sender: UnboundedSender<Action>, action: Action) {
    if let Err(err) = action_sender.send(action) {
        error!("Error while sending action: {err:?}");
    }
}

struct NodeConfig {
    antnode_path: Option<PathBuf>,
    auto_set_nat_flags: bool,
    count: u16,
    custom_ports: Option<PortRange>,
    data_dir_path: Option<PathBuf>,
    relay: bool,
    network_id: Option<u8>,
    owner: Option<String>,
    init_peers_config: InitialPeersConfig,
    rewards_address: String,
    upnp: bool,
}

/// Run the NAT detection process
async fn run_nat_detection(action_sender: &UnboundedSender<Action>) {
    info!("Running nat detection....");

    // Notify that NAT detection is starting
    if let Err(err) = action_sender.send(Action::StatusActions(StatusActions::NatDetectionStarted))
    {
        error!("Error while sending action: {err:?}");
    }

    let release_repo = <dyn AntReleaseRepoActions>::default_config();
    let version = match release_repo
        .get_latest_version(&ReleaseType::NatDetection)
        .await
    {
        Ok(v) => {
            info!("Using NAT detection version {}", v.to_string());
            v.to_string()
        }
        Err(err) => {
            info!("No NAT detection release found, using fallback version 0.1.0");
            info!("Error: {err}");
            "0.1.0".to_string()
        }
    };

    if let Err(err) = ant_node_manager::cmd::nat_detection::run_nat_detection(
        None,
        true,
        None,
        None,
        Some(version),
        VerbosityLevel::Minimal,
    )
    .await
    {
        error!("Error while running nat detection {err:?}. Registering the error.");
        if let Err(err) = action_sender.send(Action::StatusActions(
            StatusActions::ErrorWhileRunningNatDetection,
        )) {
            error!("Error while sending action: {err:?}");
        }
    } else {
        info!("Successfully ran nat detection.");
        if let Err(err) = action_sender.send(Action::StatusActions(
            StatusActions::SuccessfullyDetectedNatStatus,
        )) {
            error!("Error while sending action: {err:?}");
        }
    }
}

fn prepare_node_config(args: &MaintainNodesArgs) -> NodeConfig {
    NodeConfig {
        antnode_path: args.antnode_path.clone(),
        auto_set_nat_flags: args.connection_mode == ConnectionMode::Automatic,
        data_dir_path: args.data_dir_path.clone(),
        count: args.count,
        custom_ports: if args.connection_mode == ConnectionMode::CustomPorts {
            args.port_range.clone()
        } else {
            None
        },
        owner: if args.owner.is_empty() {
            None
        } else {
            Some(args.owner.clone())
        },
        relay: args.connection_mode == ConnectionMode::HomeNetwork,
        network_id: args.network_id,
        init_peers_config: args.init_peers_config.clone(),
        rewards_address: args.rewards_address.clone(),
        upnp: args.connection_mode == ConnectionMode::UPnP,
    }
}

/// Debug log the node config
fn debug_log_config(config: &NodeConfig, args: &MaintainNodesArgs) {
    debug!("************ STARTING NODE MAINTENANCE ************");
    debug!(
        "Maintaining {} running nodes with the following args:",
        config.count
    );
    debug!(
        " owner: {:?}, init_peers_config: {:?}, antnode_path: {:?}, network_id: {:?}",
        config.owner, config.init_peers_config, config.antnode_path, args.network_id
    );
    debug!(
        " data_dir_path: {:?}, connection_mode: {:?}",
        config.data_dir_path, args.connection_mode
    );
    debug!(
        " auto_set_nat_flags: {:?}, custom_ports: {:?}, upnp: {}, relay: {}",
        config.auto_set_nat_flags, config.custom_ports, config.upnp, config.relay
    );
}

/// Get the currently used ports from the node registry
async fn get_used_ports(node_registry: &NodeRegistryManager) -> Vec<u16> {
    let mut used_ports = Vec::new();
    for node in node_registry.nodes.read().await.iter() {
        let node = node.read().await;
        if let Some(port) = node.node_port {
            used_ports.push(port);
        }
    }
    debug!("Currently used ports: {:?}", used_ports);
    used_ports
}

/// Get the port range (u16, u16) from the custom ports PortRange
fn get_port_range(custom_ports: &Option<PortRange>) -> (u16, u16) {
    match custom_ports {
        Some(PortRange::Single(port)) => (*port, *port),
        Some(PortRange::Range(start, end)) => (*start, *end),
        None => (PORT_MIN as u16, PORT_MAX as u16),
    }
}

/// Scale down the nodes
async fn scale_down_nodes(config: &NodeConfig, count: u16, node_registry: NodeRegistryManager) {
    match ant_node_manager::cmd::node::maintain_n_running_nodes(
        false,
        false,
        config.auto_set_nat_flags,
        CONNECTION_TIMEOUT_START,
        count,
        config.data_dir_path.clone(),
        true,
        None,
        Some(EvmNetwork::default()),
        None,
        None,
        None,
        None,
        None,
        config.network_id,
        None,
        None, // We don't care about the port, as we are scaling down
        node_registry,
        config.init_peers_config.clone(),
        config.relay,
        RewardsAddress::from_str(config.rewards_address.as_str()).unwrap(),
        get_restart_policy(),
        None,
        None,
        config.antnode_path.clone(),
        None,
        !config.upnp,
        None,
        None,
        VerbosityLevel::Minimal,
        None,
        false,
    )
    .await
    {
        Ok(_) => {
            info!("Scaling down to {} nodes", count);
        }
        Err(err) => {
            error!("Error while scaling down to {} nodes: {err:?}", count);
        }
    }
}

/// Add the specified number of nodes
async fn add_nodes(
    action_sender: &UnboundedSender<Action>,
    config: &NodeConfig,
    mut nodes_to_add: i32,
    used_ports: &mut Vec<u16>,
    current_port: &mut u16,
    max_port: u16,
    node_registry: NodeRegistryManager,
) {
    let mut retry_count = 0;

    while nodes_to_add > 0 && retry_count < NODE_ADD_MAX_RETRIES {
        // Find the next available port
        while used_ports.contains(current_port) && *current_port <= max_port {
            *current_port += 1;
        }

        if *current_port > max_port {
            error!("Reached maximum port number. Unable to find an available port.");
            send_action(
                action_sender.clone(),
                Action::StatusActions(StatusActions::ErrorScalingUpNodes {
                    raw_error: format!(
                        "Reached maximum port number ({max_port}).\nUnable to find an available port."
                    ),
                }),
            );
            break;
        }

        let port_range = Some(PortRange::Single(*current_port));
        match ant_node_manager::cmd::node::maintain_n_running_nodes(
            false,
            false,
            config.auto_set_nat_flags,
            CONNECTION_TIMEOUT_START,
            config.count,
            config.data_dir_path.clone(),
            true,
            None,
            Some(EvmNetwork::default()),
            None,
            None,
            None,
            None,
            None,
            config.network_id,
            None,
            port_range,
            node_registry.clone(),
            config.init_peers_config.clone(),
            config.relay,
            RewardsAddress::from_str(config.rewards_address.as_str()).unwrap(),
            get_restart_policy(),
            None,
            None,
            config.antnode_path.clone(),
            None,
            !config.upnp,
            None,
            None,
            VerbosityLevel::Minimal,
            None,
            false,
        )
        .await
        {
            Ok(_) => {
                info!("Successfully added a node on port {}", current_port);
                used_ports.push(*current_port);
                nodes_to_add -= 1;
                *current_port += 1;
                retry_count = 0; // Reset retry count on success
            }
            Err(err) => {
                //TODO: We should use concrete error types here instead of string matching (ant_node_manager)
                if err.to_string().contains("is being used by another service") {
                    warn!(
                        "Port {} is being used, retrying with a different port. Attempt {}/{}",
                        current_port,
                        retry_count + 1,
                        NODE_ADD_MAX_RETRIES
                    );
                } else if err
                    .to_string()
                    .contains("Failed to add one or more services")
                    && retry_count >= NODE_ADD_MAX_RETRIES
                {
                    send_action(
                        action_sender.clone(),
                        Action::StatusActions(StatusActions::ErrorScalingUpNodes {
                            raw_error: "When trying to add a node, we failed.\n\
                                 Maybe you ran out of disk space?\n\
                                 Maybe you need to change the port range?"
                                .to_string(),
                        }),
                    );
                } else if err
                    .to_string()
                    .contains("contains a virus or potentially unwanted software")
                    && retry_count >= NODE_ADD_MAX_RETRIES
                {
                    send_action(
                        action_sender.clone(),
                        Action::StatusActions(StatusActions::ErrorScalingUpNodes {
                            raw_error: "When trying to add a node, we failed.\n\
                             You may be running an old version of antnode service?\n\
                             Did you whitelisted antnode and the launchpad?"
                                .to_string(),
                        }),
                    );
                } else {
                    error!("Range of ports to be used {:?}", *current_port..max_port);
                    error!("Error while adding node on port {}: {err:?}", current_port);
                }
                // In case of error, we increase the port and the retry count
                *current_port += 1;
                retry_count += 1;
            }
        }
    }
    if retry_count >= NODE_ADD_MAX_RETRIES {
        send_action(
            action_sender.clone(),
            Action::StatusActions(StatusActions::ErrorScalingUpNodes {
                raw_error: format!(
                    "When trying to start a node, we reached the maximum amount of retries ({NODE_ADD_MAX_RETRIES}).\n\
                    Could this be a firewall blocking nodes starting or ports on your router already in use?"
                ),
            }),
        );
    }
}