redgold 0.1.48

Decentralized Portfolio Contracts & Data Lake
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
use flume::Sender;
use itertools::Itertools;
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::str::FromStr;
use std::path::Path;
use tokio::fs;
use reqwest;

use crate::core::backup::aws_backup::AwsBackup;
use crate::core::relay::Relay;
use crate::core::transact::tx_broadcast_support::TxBroadcastSupport;
use crate::core::transact::tx_builder_supports::{TxBuilderApiConvert, TxBuilderApiSupport};
use crate::e2e::tx_submit::TransactionSubmitter;
use crate::infra::deploy::{default_deploy, offline_generate_keys_servers};
use crate::infra::grafana_public_manual_deploy::manual_deploy_grafana_public;
use crate::node_config::{ApiNodeConfig, DataStoreNodeConfig, EnvDefaultNodeConfig};
use crate::test::daily_e2e::run_daily_e2e;
use crate::util::argon_kdf::argon2d_hash;
use crate::util::metadata::read_metadata_json;
use redgold_common::flume_send_help::{Channel, RecvAsyncErrorInfo};
use redgold_common_no_wasm::cmd::run_cmd;
use redgold_common_no_wasm::output_handlers;
use redgold_common_no_wasm::ssh_like::ToSSHDeploy;
use redgold_common_no_wasm::tx_new::TransactionBuilderSupport;
use redgold_data::data_store::DataStore;
use redgold_keys::address_support::AddressSupport;
use redgold_keys::btc::btc_wallet::SingleKeyBitcoinWallet;
use redgold_keys::proof_support::ProofSupport;
use redgold_keys::transaction_support::TransactionSupport;
use redgold_keys::util::mnemonic_support::MnemonicSupport;
use redgold_keys::word_pass_support::{NodeConfigKeyPair, WordsPassNodeConfig};
use redgold_keys::KeyPair;
use redgold_schema::conf::node_config::NodeConfig;
use redgold_schema::conf::rg_args::{AddServer, BalanceCli, ColdWordMixer, DebugCommand, Deploy, FaucetCli, NostrKey, QueryCli, RgDebugCommand, TestTransactionCli, WalletAddress, WalletSend};
use redgold_schema::helpers::easy_json::EasyJson;
use redgold_schema::helpers::easy_json::{json, json_from, json_pretty};
use redgold_schema::helpers::with_metadata_hashable::WithMetadataHashable;
use redgold_schema::keys::words_pass::WordsPass;
use redgold_schema::observability::errors::Loggable;
use redgold_schema::proto_serde::ProtoSerde;
use redgold_schema::servers::ServerOldFormat;
use redgold_schema::structs::{Address, CurrencyAmount, ErrorInfo, Hash, NetworkEnvironment, Proof, PublicKey, SupportedCurrency};
use redgold_schema::transaction::rounded_balance_i64;
use redgold_schema::tx::tx_builder::TransactionBuilder;
use redgold_schema::{error_info, ErrorInfoContext, RgResult, SafeOption};
use tokio::task::JoinHandle;
use tracing::{error, info};

pub async fn add_server(add_server: &AddServer, config: &NodeConfig) -> Result<(), ErrorInfo>  {
    let ds = config.data_store().await;
    let config = ds.config_store.select_config("servers".to_string()).await?;
    let mut servers: Vec<ServerOldFormat> = vec![];
    if let Some(s) = config {
        servers = json_from::<Vec<ServerOldFormat>>(&*s)?;
    }
    let max_index = servers.iter().map(|s| s.index).max().unwrap_or(-1);
    let this_index = add_server.index.unwrap_or(max_index + 1);
    servers.push(ServerOldFormat {
        name: "".to_string(),
        host: add_server.ssh_host.clone(),
        username: add_server.user.clone(),
        ipv4: None,
        node_name: None,
        index: this_index,
        peer_id_index: add_server.peer_id_index.unwrap_or(this_index),
        network_environment: NetworkEnvironment::All.to_std_string(),
        external_host: None,
        reward_address: None,
        jump_host: None,
        party_config: None,
    });
    ds.config_store.insert_update("servers".to_string(), json(&servers)?).await?;
    Ok(())
}

pub async fn status(config: &NodeConfig) -> Result<(), ErrorInfo>  {
    //let ds = config.data_store().await;
    let c = config.api_rg_client();
    let a = c.about().await?;
    println!("{}", json_pretty(&a)?);

    let m = c.metrics().await?.json_or();

    println!("metrics: {}", m);

    Ok(())
}

#[ignore]
#[tokio::test]
async fn metrics_debug() {
    let mut nc = NodeConfig::default();
    nc.network = NetworkEnvironment::Dev;
    let c = nc.api_rg_client();
    // let a = c.about().await?;
    // println!("{}", json_pretty(&a)?);

    let m = c.metrics().await.expect("");
    let t = c.table_sizes().await.expect("");

    println!("metrics: {}", m.json_or());

    println!("table sizes: {}", t.json_or());


}

pub async fn list_servers(config: &NodeConfig) -> Result<Vec<ServerOldFormat>, ErrorInfo>  {
    let ds = config.data_store().await;
    let config = ds.config_store.select_config("servers".to_string()).await?;
    let mut servers: Vec<ServerOldFormat> = vec![];
    if let Some(s) = config {
        servers = json_from::<Vec<ServerOldFormat>>(&*s)?;
    }
    Ok(servers)
}

pub fn generate_mnemonic(_generate_mnemonic: &ColdWordMixer) -> RgResult<()> {
    let wp = WordsPass::generate().expect("works");
    println!("{}", wp.words);
    Ok(())
}

pub fn generate_address(generate_address: WalletAddress, node_config: &NodeConfig) -> Result<String, ErrorInfo> {
    let wallet = node_config.secure_words_or();
    let address = if let Some(path) = generate_address.path {
        wallet.keypair_at(path).expect("works").address_typed()
    } else if let Some(index) = generate_address.index {
        wallet.keypair_at_change(index as i64).expect("works").address_typed()
    } else {
        node_config.keypair().address_typed()
    };
    let string = address.render_string().expect("address render failure");
    println!("{}", string.clone());
    Ok(string)
}




pub async fn send(p0: &WalletSend, p1: &NodeConfig) -> Result<(), ErrorInfo> {
    let destination = p0.destination.parse_address()?;
    let amount = p0.amount;
    let amount = CurrencyAmount::from_fractional(amount)?;
    // let mut query_addresses = vec![];
    // let mut hm: HashMap<Vec<u8>, KeyPair> = HashMap::new();
    // for x in p0.from {
    //     let address = Address::parse(x)?;
    //     query_addresses.push(address);
    // }
    let kp = p1.secure_words_or().keypair_at_change(0 as i64).expect("works");
    //
    // for i in 0..10 {
    //     let x1 = kp.address_typed();
    //     let x: Vec<u8> = x1.vec();
    //     query_addresses.push(x1);
    //     hm.insert(x, kp.clone());
    // }
    //
    let client = p1.api_client();
    // let result = client.query_address(query_addresses).await?.as_error()?;
    // let utxos = result.query_addresses_response.safe_get_msg("missing query_addresses_response")?
    //     .utxo_entries.clone();
    // // TODO ^ Balance check here
    // if utxos.len() == 0 {
    //     return Err(ErrorInfo::error_info("No UTXOs found for this address"));
    // }
    // let option1 = utxos.get(0);
    // let first_uto = option1.safe_get_msg("first")?;
    // let first_addr = first_uto.address()?;
    // let option = hm.get(&first_addr.vec());
    // let kp = option.safe_get_msg("keypair")?.clone().clone();
    //
    // let utxo = utxos.get(0).expect("first").clone();
    let b = TransactionBuilder::new(&p1)
        .with_input_address(&kp.address_typed())
        .into_api_wrapper()
        .with_auto_utxos().await?
        .with_output(&destination, &amount)
        .build()?
        .sign(&kp)?;

    let response = client.send_transaction(&b, true).await?;
    let tx_hex = response.transaction_hash.safe_get()?.hex();
    println!("{}", tx_hex);
    Ok(())
}

pub async fn faucet(p0: &FaucetCli, p1: &NodeConfig) -> Result<(), ErrorInfo>  {
    let address = p0.to.clone().parse_address()?;
    let response = p1.api_client().faucet(&address).await?;
    let tx = response.submit_transaction_response.safe_get()?.transaction.safe_get()?;
    let tx_hex = tx.hash_hex();
    println!("{}", tx_hex);
    Ok(())
}

pub async fn balance_lookup(request: &BalanceCli, nc: &Box<NodeConfig>) -> Result<(), ErrorInfo> {
    // TODO: Get keypair from prior cli steps.
    let words = nc.cli_get_words_pass(false);
    let ext = ExternalNetworkResourcesImpl::new(nc, None).unwrap();
    let kp = words.keypair_at_change(0).expect("works");
    if let Some(a) = request.address.as_ref() {
        let a = a.parse_address()?;
        if a.as_external().currency_or() == SupportedCurrency::Redgold {
            let b = nc.api_rg_client().balance(&a).await?;
            let a = CurrencyAmount::from_rdg(b);
            println!("{} RDG", a.to_fractional().to_string());
        } else {
            let a = a.as_external();
            let b = ext.get_live_balance(&a).await?.to_fractional();
            println!("{} {}", b, a.currency_or().abbreviated());
        }
        return Ok(())
    }

    let c = nc.api_rg_client().balance_pk(&kp.public_key()).await?;
    // println!("about to query");
    // let client = nc.api_client();
    // let response = client.query_hash(addr.render_string()?).await?;
    // let rounded = rounded_balance_i64(response.address_info.safe_get_msg("missing address_info")?.balance);
    println!("{} RDG", c.to_fractional().to_string());
    let addrs = words.to_all_addresses_default(&nc.network).ok();
    if let Some(a) = addrs {
        for addr in a {
            if addr.currency_or() == SupportedCurrency::Redgold {
                continue;
            }
            let b = ext.get_live_balance(&addr).await.log_error().ok()
                .map(|a| a.to_fractional()).unwrap_or(0.);
            println!("{} {} {}", addr.render_string()?, b, addr.currency_or().abbreviated());
        }
    }

    Ok(())
}


pub async fn query(p0: &QueryCli, p1: &Box<NodeConfig>) -> Result<(), ErrorInfo> {
    let h = p0.hash.clone();
    let response = p1.api_client().query_hash(h.clone()).await?;
    println!("{}", json(&response)?);
    Ok(())
}


pub fn generate_random_mnemonic() -> WordsPass {
    WordsPass::generate().expect("works")
}


#[test]
pub fn mnemonic_generate_test() {
    assert_eq!(generate_random_mnemonic().words.split(" ").count(), 24);
}

pub const REDGOLD_SECURE_DATA_PATH: &str = "REDGOLD_SECURE_PATH";

pub fn default_path() -> PathBuf {
    dirs::home_dir().expect("home directory not found").join(".rg")
}

pub fn default_all_path() -> String {
    default_path().join("all").to_str().expect("all").to_string()
}

pub fn add_server_prompt() -> ServerOldFormat {
    println!("Enter hostname or IP address of server");
    let mut host = String::new();
    std::io::stdin().read_line(&mut host).expect("Failed to read line");
    println!("Enter SSH username, or press enter to use default of 'root'");
    let mut username = "root".to_string();
    std::io::stdin().read_line(&mut username).expect("Failed to read line");
    println!("Enter SSH key path, or press enter to use default of ~/.ssh/id_rsa");
    let mut key_path = dirs::home_dir().expect("Home").join(".ssh/id_rsa").to_str().expect("str").to_string();
    std::io::stdin().read_line(&mut key_path).expect("Failed to read line");
    ServerOldFormat {
        name: "".to_string(),
        host,
        index: 0,
        username: Some(username),
        ipv4: None,
        node_name: None,
        peer_id_index: 0,
        network_environment: NetworkEnvironment::All.to_std_string(),
        external_host: None,
        reward_address: None,
        jump_host: None,
        party_config: None,
    }
}

pub async fn deploy(deploy: &Deploy, node_config: &NodeConfig) -> RgResult<JoinHandle<()>> {
    let mut deploy = deploy.clone();
    // if deploy.wizard {
    //     deploy_wizard(&deploy, node_config).await?;
    //     return Ok(tokio::spawn(async move {()}));
    // }

    if std::env::var("REDGOLD_PRIMARY_GENESIS").is_ok() {
        deploy.genesis = true;
    }
    let mut net = node_config.network.clone();

    if net == NetworkEnvironment::Local {
        net = NetworkEnvironment::Dev;
    } else {
        if node_config.config_data.network.is_none() {
            if node_config.development_mode() {
                net = NetworkEnvironment::Dev;
            } else {
                net = NetworkEnvironment::Main;
            }
        }
        // Get node_config arg translate and set to dev if arg not supplied.
    }

    let mut nc = node_config.clone();
    nc.network = net;


    let (default_fun, output_handler) = output_handlers::log_handler();

    default_deploy(&mut deploy, &nc, output_handler, None, None).await?;

    Ok(default_fun)
}
use crossterm::terminal::{disable_raw_mode, enable_raw_mode};
use crossterm::event::{read, Event, KeyCode, KeyEvent};
use redgold_cli::config_ext::{get_input, NodeConfigExt};
use redgold_common::external_resources::ExternalNetworkResources;
use redgold_schema::util::lang_util;
use crate::integrations::external_network_resources::ExternalNetworkResourcesImpl;
use crate::util::current_time_millis;

//
// pub async fn get_input_rpass(prompt: impl Into<String>, is_password: bool) -> RgResult<Option<String>> {
//     let prompt = prompt.into();
//
//     if is_password {
//         let password = rpassword::read_password_from_tty(Some(&prompt))
//             .error_info("Failed to read password")?;
//         Ok(Some(password))
//     } else {
//         println!("{}", prompt);
//         let mut input = String::new();
//         std::io::stdin().read_line(&mut input).error_info("Failed to read line")?;
//         if input.is_empty() {
//             Ok(None)
//         } else {
//             Ok(Some(input))
//         }
//     }
// }
// TODO: All this code is out of date, need to update it.
// Move to own file
pub async fn deploy_wizard(_deploy: &Deploy, _config: &NodeConfig) -> Result<(), ErrorInfo> {

        println!("Welcome to the Redgold deployment wizard!");
        let mut data_dir = _config.data_folder.all().path;
        let path = std::env::var(REDGOLD_SECURE_DATA_PATH);
        match path {
            Ok(p) => {
                println!("Found secure data path: {}", p);
            }
            Err(_) => {
                println!("No secure data path found, please enter a path to store secure data");
                println!("This should ideally be an encrypted volume (Cryptomator or equivalent) \
                with cloud backups (pCloud or equivalent)");
                println!("If you are unsure, press enter without a path to use the default path");
                let mut path = String::new();
                std::io::stdin().read_line(&mut path).expect("Failed to read line");
                if path.is_empty() {
                    let buf = data_dir.clone();
                    println!("Using default path {}", buf.to_str().expect("").to_string());
                } else {
                    println!("Using path: {}", path);
                    println!("Would you like to add to ~/.bash_profile (y/n)");
                    let mut answer = String::new();
                    std::io::stdin().read_line(&mut answer).expect("Failed to read line");
                    if answer.trim().to_lowercase() == "y" {
                        println!("Adding path to ~/.bash_profile");
                        let (stdout, stderr) = run_cmd(
                            "echo", vec![&*format!("'export REDGOLD_SECURE_PATH={}'", path), ">>", "~/.bash_profile"]);
                        println!("{} {}", stdout, stderr);
                    }
                    data_dir = PathBuf::from(path).join("all");
                }
            }
        }


        // Query to find if any existing servers
        let store_path = data_dir.join("data_store.sqlite").to_str().expect("str").to_string();
        // let _ds = DataStore::from_path(store_path, store_path).await;

        // Check to see if we have a mnemonic stored in backup for generating a random seed

        let mnemonics: Vec<WordsPass> = vec![]; // TODO: Replace from config; DataStoreContext::map_err_sqlx(ds.query_all_mnemonic().await)?;
        let mnemonic = if mnemonics.is_empty() {
            println!("Unable to find random mnemonic from backup, generating a new one and saving");
            let m = generate_random_mnemonic();
            // TODO: Replace this with updating an internal config, potentially encrypted.
            // DataStoreContext::map_err_sqlx(ds.insert_mnemonic(MnemonicEntry{
            //     words: m.to_string(),
            //     time: util::current_time_millis(),
            //     peer_id: vec![]
            // }).await)?;
            m
        } else {
            println!("Found stored random mnemonic");
            let x = mnemonics.get(0).expect("").clone();
            let string = x.words.clone();
            WordsPass::new(&string, None)
        };
        println!("Random mnemonic fingerprint: {}", mnemonic.checksum().expect("checksum"));

        let mut servers: Vec<ServerOldFormat> = vec![]; // ds.server_store.servers().await?;

        if servers.is_empty() {
            println!("No deployment server found, please add a new server");
            let server = add_server_prompt();
            servers.push(server);
        }

        let mut done_adding_servers = false;
        while !done_adding_servers {
            println!("Would you like to add another server? (y/n)");
            let mut answer = String::new();
            std::io::stdin().read_line(&mut answer).expect("Failed to read line");
            if answer.trim().to_lowercase() == "y" {
                let server = add_server_prompt();
                servers.push(server);
            } else {
                done_adding_servers = true;
            }
        }

        println!("Enter deployment target environment: 'main' for mainnet, 'test' for testnet,\
         'all' for all environments on same machine no quotes -- empty for default of 'all'");
        let mut answer = String::new();
        std::io::stdin().read_line(&mut answer).expect("Failed to read line");
        let _network_env = if answer.is_empty(){
            NetworkEnvironment::All
        } else { NetworkEnvironment::parse(answer.trim().to_lowercase())};

        println!("Enter mnemonic passphrase, leave empty for none");
        let passphrase_input = String::new();
        std::io::stdin().read_line(&mut answer).expect("Failed to read line");
        let passphrase: Option<&str> = if passphrase_input.is_empty() {
            None
        } else {
            Some(&*passphrase_input)
        };
        // let _seed_bytes = mnemonic.to_seed(passphrase).0;
        //
        // for server in servers {
        //
        // }
    Ok(())
}

pub async fn test_transaction(_p0: &&TestTransactionCli, p1: &NodeConfig
                        // , arc: Arc<Runtime>
) -> Result<(), ErrorInfo> {
    if p1.network == NetworkEnvironment::Main {
        return Err(error_info("Cannot test transaction on mainnet unsupported".to_string()));
    }
    let client = p1.api_client();
    let tx_submit = TransactionSubmitter::default(
        client.clone(), vec![], &p1,
    );
    let faucet_tx = tx_submit.with_faucet().await?;
    // info!("Faucet response: {}", faucet_tx.json_or());
    let faucet_tx = faucet_tx.submit_transaction_response.safe_get()?.transaction.safe_get()?;
    let address = faucet_tx.first_output_address_non_input_or_fee().expect("a");
    let response = client.query_hash(address.render_string().expect("")).await?;
    let rounded = rounded_balance_i64(response.address_info.safe_get_msg("missing address_info")?.balance);
    assert!(rounded > 0.);
    let _ = {
        let gen =
        tx_submit.generator.lock().expect("");
        assert!(gen.finished_pool.len() > 0);
    };
    // let source = Proof::proofs_to_addresses(&faucet_tx.inputs.get(0).expect("").proof)?.get(0).expect("source").clone();
    // let repeat = tx_submit.drain(source).await?;
    // // assert!(repeat.accepted());
    // // assert proofs here
    // let s = repeat;
    // // info!("Repeat response: {}", s.json_or());
    // // let h2 = s.transaction_hash.expect("hash");
    // let q = s.query_transaction_response.expect("query transaction response");
    // // println!("Obs proofs second tx: {}", q.observation_proofs.json_or());
    // let i = q.observation_proofs.len();
    // println!("Obs proofs number length: {:?}", i);
    // assert!(i > 0);
    // let mut peer_keys: HashSet<PublicKey> = HashSet::new();
    //
    // for o in q.observation_proofs {
    //     let key = o.proof.expect("p").public_key.expect("");
    //     peer_keys.insert(key);
    // }
    //
    // println!("Number of unique peer observations {}", peer_keys.len());

    // client.client_wrapper()



    // let result = arc.block_on(client.query_hash(h2.hex())).expect("query hash");
    // info!("Result: {}", result.json_pretty().expect("json pretty"));
    Ok(())

}

#[ignore]
#[tokio::test]
async fn test_transaction_dev() {
    // init_logger(); //.ok();
    let mut nc = NodeConfig::default();
    nc.network = NetworkEnvironment::Dev;
    // let rt = build_runtime(5, "asdf");
    let t = TestTransactionCli{};
    // let arc = rt.clone();
    let _ = test_transaction(&&t, &nc
                               // , arc
    ).await.expect("");
}

#[ignore]
#[tokio::test]
async fn test_new_deploy() {
    // init_logger(); //.ok();
    let nc = NodeConfig::dev_default().await;
    let mut dep = Deploy::default();
    dep.ops = false;
    info!("Deploying with {:?}", dep.clone());
    dep.server_index = Some(4);
    deploy(&dep, &nc).await.expect("works").abort();
}

pub async fn test_btc_balance(p0: &&String, network: NetworkEnvironment) {
    let hex = p0.clone().clone();
    let pk = PublicKey::from_hex_direct(&hex).expect("hex");
    let w = SingleKeyBitcoinWallet::new_wallet(pk, network, true).expect("works");
    let b = w.get_wallet_balance().expect("balance");
    println!("Balance: {:?}", b);
    info!("Balance: {:?}", b);
    // let txs = w.get_sourced_tx().expect("tx");
    // for t in txs {
    //     println!("Tx: {:?}", t);
    // }
}
pub async fn convert_metadata_xpub(path: &String) -> RgResult<()> {
    let md = read_metadata_json(path).await?;
    println!("name,derivation_path,xpub");
    for x in md.rdg_btc_message_account_metadata {
        let dp = x.derivation_path.split("/")
            .map(|x| x.replace("'", ""))
            .collect::<Vec<String>>();
        let option = dp.get(1..4);
        if let Some(strs) = option{
            let name = strs.iter().join("_");
            println!("account_{},{},{}", name, x.derivation_path.clone(), x.xpub.clone());
        }

    }
    Ok(())
}

pub async fn debug_commands(p0: &DebugCommand, nc: &Box<NodeConfig>) -> RgResult<()> {
    if let Some(cmd) = &p0.subcmd {
        match cmd {
            RgDebugCommand::GrafanaPublicDeploy(_) => {
                manual_deploy_grafana_public().await.log_error().ok();
                Ok(())
            }
            RgDebugCommand::BuildReleaseArtifacts(b) => {
                // TODO: Capture this in rust instead of bash scripts.
                /*
                cargo install cargo-bundle
                cargo bundle --release
                /target/release/bundle/osx/redgold.app
                 */
                Ok(())
            }
            RgDebugCommand::DailyTest(d) => {
                run_daily_e2e(nc).await
            }
            RgDebugCommand::S3UpDir(d) => {
                let p = PathBuf::from(d.source.clone());
                let dest = d.dest.replace("s3://", "");
                let split = dest.split("/").collect::<Vec<&str>>();
                let bucket = split.get(0).expect("bucket").to_string();
                let prefix = split.get(1).expect("prefix").to_string();
                let relay = Relay::new(*nc.clone()).await;
                AwsBackup::new(&relay).s3_upload_directory(&p, bucket, prefix).await
            }
            RgDebugCommand::Usb(c) => {
                copy_usb_info(nc).await?;
                Ok(())
            }
            RgDebugCommand::ServerInfo(_) => {
                let passphrase = if nc.config_data.cli.as_ref()
                    .and_then(|c| c.passphrase.as_ref()).cloned().unwrap_or(false) {
                    let res = get_input("Enter passphrase:", true)?;
                    Some(res.unwrap())
                } else {
                    None
                };
                let pids = offline_generate_keys_servers(
                    *nc.clone(), nc.servers_old(), PathBuf::from("servers"),
                    nc.secure_words_or().words, passphrase.clone()
                ).await.unwrap();

                for (i,(pid_hex, npk_hex)) in pids.iter().enumerate() {
                    println!("simple_seed(\n\"n{}.redgold.io\",\n\"{}\",\n\"{}\",\n{}),", i, pid_hex, npk_hex, passphrase.is_some());
                }
                Ok(())
            }
            RgDebugCommand::NostrKey(n) => {
                cli_nostr_kp(n.clone(), nc).await
            }

            _ => {
                Ok(())
            }
        }
    } else {
        Ok(())
    }
}




async fn copy_usb_info(p1: &Box<NodeConfig>) -> RgResult<()> {
    // Download the binary first
    let url = "https://github.com/redgold-io/redgold/releases/download/release%2Fdev/redgold_linux_ubuntu20";
    let response = reqwest::get(url).await.error_info("Failed to download binary")?;
    let bytes = response.bytes().await.error_info("Failed to read binary")?;
    fs::write("redgold", bytes).await.error_info("Failed to write binary")?;


    // Make binary executable
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = fs::metadata("redgold").await.error_info("Failed to get metadata")?.permissions();
        perms.set_mode(0o755);
        fs::set_permissions("redgold", perms).await.error_info("Failed to set permissions")?;
    }

    // Define possible USB paths
    let user_media_path = format!("/media/{}/", std::env::var("USER").unwrap_or_default());
    let prefix_paths = vec![
        "/Volumes/",
        &user_media_path
    ];
    
    let suffix_paths = vec![
        "Samsung USB",
        "NO NAME", 
        "USB_DRIVE",
        "KINGSTON",
        "B2CF-75D8"
    ];

    let mut copied = false;

    // Try each possible USB path combination
    for prefix in prefix_paths {
        for suffix in suffix_paths.iter() {
            let full_path = format!("{}{}", prefix, suffix);
            let path = Path::new(&full_path);
            
            if path.is_dir() {
                info!("Found USB drive at {}", full_path);
                let dest_path = path.join("redgold");
                match fs::copy("redgold", &dest_path).await {
                    Ok(_) => {
                        info!("Successfully copied redgold binary to {}", dest_path.display());
                        copied = true;
                        // Also copy the config.toml file if present
                        let config_path = p1.secure_or().config_path();
                        let p2 = p1.secure_path();
                        info!("Secure path at {:?}", p2);
                        info!("Looking for config.toml at {:?}", config_path);
                        if config_path.exists() {
                            let config_dest = path.join("config.toml");
                            fs::copy(config_path, config_dest.clone()).await.error_info("Failed to copy config.toml")?;
                            info!("Successfully copied config.toml to {:?}", config_dest);
                        } else {
                            info!("No config.toml found at {:?}", config_path);
                        }
                        break;
                    }
                    Err(e) => {
                        info!("Failed to copy to {}: {}", dest_path.display(), e);
                    }
                }

            }
        }
        if copied {

            break;
        }
    }

    if !copied {
        info!("Could not find any of the specified USB drives");
    }

    Ok(())
}

pub async fn cold_mix(c: ColdWordMixer, nc: &NodeConfig) -> RgResult<()> {

    let words = nc.cli_get_words_pass(false);
    let pass = get_input("Enter mixing password:", true).unwrap().unwrap();
    // let phrase = get_input("Enter wallet passphrase:", true).await?;
    let start = current_time_millis();

    let m_cost= 65536;
    let p_cost= 2;
    let t_cost= c.iterations as u32;
    let sec_words = words;
    let words_from = sec_words.validate();
    let m = words_from.unwrap();
    let seed = m.seed();
    let salt = seed.expect("works").to_vec();
    let result = argon2d_hash(salt, pass.as_bytes().to_vec(), m_cost, t_cost, p_cost).unwrap();
    let w = WordsPass::from_bytes(&*result).ok().unwrap();
    let end = current_time_millis();
    let delta_seconds = ((end - start) as f64) / 1000.0;
    tracing::info!("Argon2d took {} seconds", delta_seconds.clone());
    println!("{}", w.words);
    Ok(())
}

pub async fn cli_nostr_kp(c: NostrKey, nc: &NodeConfig) -> RgResult<()> {
    let sec_words = nc.cli_get_words_pass(true);
    let mixing_pass = "nostr";
    let derivation_path = format!("m/44'/1237'/{}'/0/0", c.account);
    let start = current_time_millis();
    let m_cost= 65536;
    let p_cost= 2;
    let t_cost= c.iterations as u32;
    let words_from = sec_words.validate();
    let m = words_from.unwrap();
    let seed_checksum = m.checksum().unwrap();
    println!("Seed checksum {}", seed_checksum);
    let seed = m.seed();
    let salt = seed.expect("works").to_vec();
    let result = argon2d_hash(salt, mixing_pass.as_bytes().to_vec(), m_cost, t_cost, p_cost).unwrap();
    let w = WordsPass::from_bytes(&*result).ok().unwrap();
    let end = current_time_millis();
    let delta_seconds = ((end - start) as f64) / 1000.0;
    tracing::info!("Argon2d took {} seconds", delta_seconds.clone());
    // println!("{}", w.words);
    let pk_hex = w.private_at(derivation_path).expect("works");
    println!("{}", pk_hex);
    Ok(())
}