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
/*
Developed by Stackmate India in 2021.
*/

//! A set of composite functions that uses [rust-bitcoin](https://docs.rs/crate/bitcoin/0.27.1) & [bdk](bitcoindevkit.com) and exposes a simpligied C interface to build descriptor based wallet applications.
//! Refer to the structs in each module for return types.
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
use std::str;

use bitcoin::network::constants::Network;

mod config;
use crate::config::{WalletConfig, DEFAULT, DEFAULT_MAINNET_NODE, DEFAULT_TESTNET_NODE};

pub mod e;
use e::{ErrorKind, S5Error};

pub mod key;
use crate::key::child;
use crate::key::master;

pub mod wallet;
use crate::wallet::address;
use crate::wallet::history;
use crate::wallet::policy;
use crate::wallet::psbt;

pub mod network;
use crate::network::fees;

/// Generates a mnemonic phrase of a given length. Defaults to 24 words.
/// A master xprv is created from the mnemonic and passphrase.
/// # Safety
/// - This function is unsafe because it dereferences and returns raw pointer.
/// - Ensure that result is passed into cstring_free after use.
#[no_mangle]
pub unsafe extern "C" fn generate_master(
    network: *const c_char,
    length: *const c_char,
    passphrase: *const c_char,
) -> *mut c_char {
    let input_cstr = CStr::from_ptr(length);
    let length: usize = match input_cstr.to_str() {
        Err(_) => 24,
        Ok(string) => match string.parse::<usize>() {
            Ok(l) => {
                if l == 12 || l == 24 {
                    l
                } else {
                    24
                }
            }
            Err(_) => 24,
        },
    };

    let passphrase_cstr = CStr::from_ptr(passphrase);
    let passphrase: &str = match passphrase_cstr.to_str() {
        Ok(string) => string,
        Err(_) => "",
    };

    let network_cstr = CStr::from_ptr(network);
    let network_str: &str = match network_cstr.to_str() {
        Ok(string) => string,
        Err(_) => "test",
    };
    let network = match network_str {
        "main" => Network::Bitcoin,
        "test" => Network::Testnet,
        _ => Network::Testnet,
    };

    match master::generate(length, passphrase, network) {
        Ok(master_key) => master_key.c_stringify(),
        Err(e) => e.c_stringify(),
    }
}

/// Creates a master xprv given a mnemonic and passphrase.
/// # Safety
/// - This function is unsafe because it dereferences and returns raw pointer.
/// - Ensure that result is passed into cstring_free after use.
#[no_mangle]
pub unsafe extern "C" fn import_master(
    network: *const c_char,
    mnemonic: *const c_char,
    passphrase: *const c_char,
) -> *mut c_char {
        let input_cstr = CStr::from_ptr(mnemonic);
        let mnemonic: &str = match input_cstr.to_str() {
            Ok(string) => string,
            Err(_) => return S5Error::new(ErrorKind::Input, "Mnemonic").c_stringify(),
        };

        let passphrase_cstr = CStr::from_ptr(passphrase);
        let passphrase: &str = match passphrase_cstr.to_str() {
            Ok(string) => string,
            Err(_) => "",
        };

        let network_cstr = CStr::from_ptr(network);
        let network_str: &str = match network_cstr.to_str() {
            Ok(string) => string,
            Err(_) => "test",
        };
        let network = match network_str {
            "main" => Network::Bitcoin,
            "test" => Network::Testnet,
            _ => Network::Testnet,
        };

        match master::import(mnemonic, passphrase, network) {
            Ok(master_key) => master_key.c_stringify(),
            Err(e) => e.c_stringify(),
        }
    
}

/// Derives hardened child keys from a master xprv.
/// Follows the BIP32 standard of m/purpose'/network'/account'.
/// Network path is inferred from the master xprv.
/// # Safety
/// - This function is unsafe because it dereferences and returns raw pointer.
/// - Ensure that result is passed into cstring_free after use.
#[no_mangle]
pub unsafe extern "C" fn derive_hardened(
    master_xprv: *const c_char,
    purpose: *const c_char,
    account: *const c_char,
) -> *mut c_char {
    
        let master_xprv_cstr = CStr::from_ptr(master_xprv);
        let master_xprv: &str = match master_xprv_cstr.to_str() {
            Ok(string) => string,
            Err(_) => return S5Error::new(ErrorKind::Input, "Master-Xprv").c_stringify(),
        };

        let purpose_cstr = CStr::from_ptr(purpose);
        let purpose: &str = match purpose_cstr.to_str() {
            Ok(string) => match string.parse::<usize>() {
                Ok(value) => {
                    if value == 84 || value == 49 || value == 44 {
                        string
                    } else {
                        "84"
                    }
                }
                Err(_) => "84",
            },
            Err(_) => "84",
        };

        let account_cstr = CStr::from_ptr(account);
        let account: &str = match account_cstr.to_str() {
            Ok(string) => match string.parse::<usize>() {
                Ok(_) => string,
                Err(_) => "0",
            },
            Err(_) => "0",
        };

        match child::derive(master_xprv, purpose, account) {
            Ok(result) => result.c_stringify(),
            Err(e) => e.c_stringify(),
        }
}

/// Compiles a policy into a descriptor of the specified script type.
/// Use wpkh for a single signature segwit native wallet (default).
/// Use wsh for a scripted segwit native wallet.
/// # Safety
/// - This function is unsafe because it dereferences and returns raw pointer.
/// - Ensure that result is passed into cstring_free after use.
#[no_mangle]
pub unsafe extern "C" fn compile(policy: *const c_char, script_type: *const c_char) -> *mut c_char {
    
        let policy_cstr = CStr::from_ptr(policy);
        let policy_str: &str = match policy_cstr.to_str() {
            Ok(string) => string,
            Err(_) => return S5Error::new(ErrorKind::Input, "Policy").c_stringify(),
        };

        let script_type_cstr = CStr::from_ptr(script_type);
        let script_type_str: &str = match script_type_cstr.to_str() {
            Ok(string) => {
                if string != "wsh" || string != "wpkh" || string != "sh" || string != "sh-wsh" {
                    "wpkh"
                } else {
                    string
                }
            }
            Err(_) => "wpkh",
        };

        match policy::compile(policy_str, script_type_str) {
            Ok(result) => result.c_stringify(),
            Err(e) => e.c_stringify(),
        }
}

/// Syncs to a remote node and fetches balance of a descriptor wallet.
/// # Safety
/// - This function is unsafe because it dereferences and returns raw pointer.
/// - Ensure that result is passed into cstring_free after use.
#[no_mangle]
pub unsafe extern "C" fn sync_balance(
    deposit_desc: *const c_char,
    node_address: *const c_char,
) -> *mut c_char {
    
        let deposit_desc_cstr = CStr::from_ptr(deposit_desc);
        let deposit_desc: &str = match deposit_desc_cstr.to_str() {
            Ok(string) => string,
            Err(_) => {
                return S5Error::new(ErrorKind::Input, "Deposit-Descriptor").c_stringify()
            }
        };

        let node_address_cstr = CStr::from_ptr(node_address);
        let node_address: &str = match node_address_cstr.to_str() {
            Ok(string) => {
                if string.contains("electrum") || string.contains("http") {
                    string
                } else {
                    DEFAULT
                }
            }
            Err(_) => DEFAULT,
        };

        let config = match WalletConfig::new(deposit_desc, node_address) {
            Ok(conf) => conf,
            Err(e) => return S5Error::new(ErrorKind::Internal, &e.message).c_stringify(),
        };
        match history::sync_balance(config) {
            Ok(result) =>  result.c_stringify(),
            Err(e) =>  e.c_stringify(),
        }
}

/// Syncs to a remote node and fetches history of a descriptor wallet.
/// # Safety
/// - This function is unsafe because it dereferences and returns raw pointer.
/// - Ensure that result is passed into cstring_free after use.
#[no_mangle]
pub unsafe extern "C" fn sync_history(
    deposit_desc: *const c_char,
    node_address: *const c_char,
) -> *mut c_char {
    
        let deposit_desc_cstr = CStr::from_ptr(deposit_desc);
        let deposit_desc: &str = match deposit_desc_cstr.to_str() {
            Ok(string) => string,
            Err(_) => {
                return S5Error::new(ErrorKind::Input, "Deposit-Descriptor").c_stringify()
            }
        };

        let node_address_cstr = CStr::from_ptr(node_address);
        let node_address: &str = match node_address_cstr.to_str() {
            Ok(string) => {
                if string.contains("electrum") || string.contains("http") {
                    string
                } else {
                    DEFAULT
                }
            }
            Err(_) => DEFAULT,
        };

        let config = match WalletConfig::new(deposit_desc, node_address) {
            Ok(conf) => conf,
            Err(e) => return S5Error::new(ErrorKind::Internal, &e.message).c_stringify(),
        };
        match history::sync_history(config) {
            Ok(result) => result.c_stringify(),
            Err(e) => e.c_stringify(),
        }
}

/// Gets a new address for a descriptor wallet at a given index.
/// Client must keep track of address indexes and ensure prevention of address reuse.
/// # Safety
/// - This function is unsafe because it dereferences and returns raw pointer.
/// - Ensure that result is passed into cstring_free after use.
#[no_mangle]
pub unsafe extern "C" fn get_address(
    deposit_desc: *const c_char,
    node_address: *const c_char,
    index: *const c_char,
) -> *mut c_char {
    
        let deposit_desc_cstr = CStr::from_ptr(deposit_desc);
        let deposit_desc: &str = match deposit_desc_cstr.to_str() {
            Ok(string) => string,
            Err(_) => {
                return S5Error::new(ErrorKind::Input, "Deposit-Descriptor").c_stringify()
            }
        };

        let node_address_cstr = CStr::from_ptr(node_address);
        let node_address: &str = match node_address_cstr.to_str() {
            Ok(string) => {
                if string.contains("electrum") || string.contains("http") {
                    string
                } else {
                    DEFAULT
                }
            }
            Err(_) => DEFAULT,
        };

        let config = match WalletConfig::new(deposit_desc, node_address) {
            Ok(conf) => conf,
            Err(e) => return S5Error::new(ErrorKind::Internal, &e.message).c_stringify(),
        };

        let index_cstr = CStr::from_ptr(index);
        let address_index: u32 = match index_cstr.to_str() {
            Ok(string) => match string.parse::<u32>() {
                Ok(i) => i,
                Err(_) => {
                    return CString::new("Error: Address Index Input.")
                        .unwrap()
                        .into_raw()
                }
            },
            Err(_) => return S5Error::new(ErrorKind::Input, "Address-Index").c_stringify(),
        };

        match address::generate(config, address_index) {
            Ok(result) => result.c_stringify(),
            Err(e) => e.c_stringify(),
        }
}

/// Gets the current network fee (in sats/vbyte) for a given confirmation target.
/// # Safety
/// - This function is unsafe because it dereferences and returns raw pointer.
/// - Ensure that result is passed into cstring_free after use.
#[no_mangle]
pub unsafe extern "C" fn get_fees(
    network: *const c_char,
    node_address: *const c_char,
    conf_target: *const c_char,
) -> *mut c_char {
    
        let conf_target_cstr = CStr::from_ptr(conf_target);
        let conf_target_int: usize = match conf_target_cstr.to_str() {
            Ok(string) => string.parse::<usize>().unwrap_or(6),
            Err(_) => 6,
        };

        let network_cstr = CStr::from_ptr(network);
        let network: &str = match network_cstr.to_str() {
            Ok(string) => string,
            Err(_) => "test",
        };
        let network_enum = match network {
            "main" => Network::Bitcoin,
            _ => Network::Testnet,
        };
        let node_address_cstr = CStr::from_ptr(node_address);
        let node_address: &str = match node_address_cstr.to_str() {
            Ok(string) => {
                if string == DEFAULT {
                    match network_enum {
                        Network::Bitcoin => DEFAULT_MAINNET_NODE,
                        _ => DEFAULT_TESTNET_NODE,
                    }
                } else {
                    string
                }
            }
            Err(_) => match network_enum {
                Network::Bitcoin => DEFAULT_MAINNET_NODE,
                _ => DEFAULT_TESTNET_NODE,
            },
        };

        let config = match WalletConfig::new("/0/*", node_address) {
            Ok(conf) => conf,
            Err(e) => return S5Error::new(ErrorKind::Internal, &e.message).c_stringify(),
        };
        match fees::estimate_sats_per_byte(config, conf_target_int) {
            Ok(result) => result.c_stringify(),
            Err(e) => e.c_stringify(),
        }
}

/// Builds a transaction for a given descriptor wallet.
/// If sweep is set to true, amount value is ignored and will default to None.
/// Set amount to 0 for sweep.
/// # Safety
/// - This function is unsafe because it dereferences and returns raw pointer.
/// - Ensure that result is passed into cstring_free after use.
#[no_mangle]
pub unsafe extern "C" fn build_tx(
    deposit_desc: *const c_char,
    node_address: *const c_char,
    to_address: *const c_char,
    amount: *const c_char,
    fee_rate: *const c_char,
    sweep: *const c_char,
) -> *mut c_char {
    
        let deposit_desc_cstr = CStr::from_ptr(deposit_desc);
        let deposit_desc: &str = match deposit_desc_cstr.to_str() {
            Ok(string) => string,
            Err(_) => {
                return S5Error::new(ErrorKind::Input, "Deposit-Descriptor").c_stringify()
            }
        };

        let node_address_cstr = CStr::from_ptr(node_address);
        let node_address: &str = match node_address_cstr.to_str() {
            Ok(string) => {
                if string.contains("electrum") || string.contains("http") {
                    string
                } else {
                    DEFAULT
                }
            }
            Err(_) => DEFAULT,
        };

        let config = match WalletConfig::new(deposit_desc, node_address) {
            Ok(conf) => conf,
            Err(e) => return S5Error::new(ErrorKind::Internal, &e.message).c_stringify(),
        };

        let to_address_cstr = CStr::from_ptr(to_address);
        let to_address: &str = match to_address_cstr.to_str() {
            Ok(string) => string,
            Err(_) => return S5Error::new(ErrorKind::Input, "To-Address").c_stringify(),
        };

        let sweep_cstr = CStr::from_ptr(sweep);
        let sweep: bool = match sweep_cstr.to_str() {
            Ok(string) => {
                string == "true"
            }
            Err(_) => false,
        };

        let amount_cstr = CStr::from_ptr(amount);
        let amount: Option<u64> = match amount_cstr.to_str() {
            Ok(string) => match string.parse::<u64>() {
                Ok(i) => {
                    if sweep {
                        None
                    } else {
                        Some(i)
                    }
                }
                Err(_) => {
                    return S5Error::new(ErrorKind::Input, "Invalid Amount.").c_stringify()
                }
            },
            Err(_) => return S5Error::new(ErrorKind::Input, "Amount").c_stringify(),
        };

        let fee_rate_cstr = CStr::from_ptr(fee_rate);
        let fee_rate: f32 = match fee_rate_cstr.to_str() {
            Ok(string) => match string.parse::<f32>() {
                Ok(i) => i,
                Err(_) => return S5Error::new(ErrorKind::Input, "Fee Rate").c_stringify(),
            },
            Err(_) => return S5Error::new(ErrorKind::Input, "Fee Rate").c_stringify(),
        };

        match psbt::build(config, to_address, amount, fee_rate, sweep) {
            Ok(result) => result.c_stringify(),
            Err(e) => e.c_stringify(),
        }
}

/// Decodes a PSBT and returns all outputs of the transaction and total size.
/// "miner" is used in the 'to' field of an output to indicate fee.
/// # Safety
/// - This function is unsafe because it dereferences and returns raw pointer.
/// - Ensure that result is passed into cstring_free after use.
#[no_mangle]
pub unsafe extern "C" fn decode_psbt(network: *const c_char, psbt: *const c_char) -> *mut c_char {
    
        let network_cstr = CStr::from_ptr(network);
        let network_str: &str = match network_cstr.to_str() {
            Ok(string) => string,
            Err(_) => "test",
        };
        let network = match network_str {
            "main" => Network::Bitcoin,
            "test" => Network::Testnet,
            _ => Network::Testnet,
        };

        let psbt_cstr = CStr::from_ptr(psbt);
        let psbt: &str = match psbt_cstr.to_str() {
            Ok(string) => string,
            Err(_) => return S5Error::new(ErrorKind::Input, "PSBT-Input").c_stringify(),
        };

        match psbt::decode(network, psbt) {
            Ok(result) => result.c_stringify(),
            Err(e) => e.c_stringify(),
        }
}

/// Signs a PSBT with a descriptor.
/// Can only be used with descriptors containing private key(s).
/// # Safety
/// - This function is unsafe because it dereferences and returns raw pointer.
/// - Ensure that result is passed into cstring_free after use.
#[no_mangle]
pub unsafe extern "C" fn sign_tx(
    deposit_desc: *const c_char,
    node_address: *const c_char,
    unsigned_psbt: *const c_char,
) -> *mut c_char {
    
        let deposit_desc_cstr = CStr::from_ptr(deposit_desc);
        let deposit_desc: &str = match deposit_desc_cstr.to_str() {
            Ok(string) => string,
            Err(_) => {
                return S5Error::new(ErrorKind::Input, "Deposit-Descriptor").c_stringify()
            }
        };

        let node_address_cstr = CStr::from_ptr(node_address);
        let node_address: &str = match node_address_cstr.to_str() {
            Ok(string) => {
                if string.contains("electrum") || string.contains("http") {
                    string
                } else {
                    DEFAULT
                }
            }
            Err(_) => DEFAULT,
        };

        let config = match WalletConfig::new(deposit_desc, node_address) {
            Ok(conf) => conf,
            Err(e) => return S5Error::new(ErrorKind::Internal, &e.message).c_stringify(),
        };

        let unsigned_psbt_cstr = CStr::from_ptr(unsigned_psbt);
        let unsigned_psbt: &str = match unsigned_psbt_cstr.to_str() {
            Ok(string) => string,
            Err(_) => {
                return S5Error::new(ErrorKind::Input, "Deposit-Descriptor").c_stringify()
            }
        };

        match psbt::sign(config, unsigned_psbt) {
            Ok(result) => result.c_stringify(),
            Err(e) => e.c_stringify(),
        }
}

/// Broadcasts a signed transaction to a remote node.
/// # Safety
/// - This function is unsafe because it dereferences and returns raw pointer.
/// - Ensure that result is passed into cstring_free after use.
#[no_mangle]
pub unsafe extern "C" fn broadcast_tx(
    deposit_desc: *const c_char,
    node_address: *const c_char,
    signed_psbt: *const c_char,
) -> *mut c_char {
    
        let deposit_desc_cstr = CStr::from_ptr(deposit_desc);
        let deposit_desc: &str = match deposit_desc_cstr.to_str() {
            Ok(string) => string,
            Err(_) => {
                return S5Error::new(ErrorKind::Input, "Deposit-Descriptor").c_stringify()
            }
        };

        let node_address_cstr = CStr::from_ptr(node_address);
        let node_address: &str = match node_address_cstr.to_str() {
            Ok(string) => {
                if string.contains("electrum") || string.contains("http") {
                    string
                } else {
                    DEFAULT
                }
            }
            Err(_) => DEFAULT,
        };

        let config = match WalletConfig::new(deposit_desc, node_address) {
            Ok(conf) => conf,
            Err(e) => return e.c_stringify(),
        };

        let psbt_cstr = CStr::from_ptr(signed_psbt);
        let signed_psbt: &str = match psbt_cstr.to_str() {
            Ok(string) => string,
            Err(_) => {
                return S5Error::new(ErrorKind::Input, "Deposit-Descriptor").c_stringify()
            }
        };

        match psbt::broadcast(config, signed_psbt) {
            Ok(result) => result.c_stringify(),
            Err(e) => e.c_stringify(),
        }
}

/// Checks if an extended public key is valid.
/// Do not use the key source while checking an xpub i.e. remove [fingerprint/derivation/path/values] and only provide the xpub/tpub.
/// # Safety
/// - This function is unsafe because it dereferences and returns raw pointer.
/// - Ensure that result is passed into cstring_free after use.
#[no_mangle]
pub unsafe extern "C" fn check_xpub(xpub: *const c_char) -> *mut c_char {
    
        let xpub_cstr = CStr::from_ptr(xpub);
        let xpub: &str = match xpub_cstr.to_str() {
            Ok(string) => string,
            Err(_) => return CString::new("false").unwrap().into_raw(),
        };

        match child::check_xpub(xpub) {
            true => CString::new("true").unwrap().into_raw(),
            false => CString::new("false").unwrap().into_raw(),
        }
}

/// After using any other function, pass the output pointer into cstring_free to clear memory.
/// Failure to do so can lead to memory bugs.
/// # Safety
/// - This function is unsafe because it deferences a raw pointer.
#[no_mangle]
pub unsafe extern "C" fn cstring_free(ptr: *mut c_char) {
    if ptr.is_null() {
        return;
    }
    CString::from_raw(ptr);
    // rust automatically deallocates the pointer after using it
    // here we just convert it to a CString so it is used and cleared
}
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    /// Ensure that mnemonic does not error for bad input values.
    /// Default to 24 words mnemonic.
    fn test_ffi_c_master_ops() {
        unsafe {
            let master = generate_master(
                CString::new("notanumber").unwrap().into_raw(),
                CString::new("9").unwrap().into_raw(),
                CString::new("").unwrap().into_raw(),
            );
            // unrecognized network string must default to test
            //length 9 should default to 24 words
            let master = CStr::from_ptr(master).to_str().unwrap();
            let master: master::MasterKey = serde_json::from_str(master).unwrap();
            assert_eq!(
                24,
                master
                    .mnemonic
                    .split_whitespace()
                    .collect::<Vec<&str>>()
                    .len()
            );

            let mnemonic = "panel across strong judge economy song loud valid regret fork consider bid rack young avoid soap plate injury snow crater beef alone stay clock";
            let fingerprint = "eb79e0ff";
            let xprv = "tprv8ZgxMBicQKsPduTkddZgfGyk4ZJjtEEZQjofpyJg74LizJ469DzoF8nmU1YcvBFskXVKdoYmLoRuZZR1wuTeuAf8rNYR2zb1RvFns2Vs8hY";
            let master = import_master(
                CString::new("notanumber").unwrap().into_raw(),
                CString::new(mnemonic).unwrap().into_raw(),
                CString::new("").unwrap().into_raw(),
            );
            let master = CStr::from_ptr(master).to_str().unwrap();
            let master: master::MasterKey = serde_json::from_str(master).unwrap();
            assert_eq!(xprv, master.xprv);
            assert_eq!(fingerprint, master.fingerprint);
        }
    }
    //     /**
    //      * MasterKey {
    //         mnemonic: "panel across strong judge economy song loud valid regret fork consider bid rack young avoid soap plate injury snow crater beef alone stay clock",
    //         fingerprint: "eb79e0ff",
    //         xprv: "tprv8ZgxMBicQKsPduTkddZgfGyk4ZJjtEEZQjofpyJg74LizJ469DzoF8nmU1YcvBFskXVKdoYmLoRuZZR1wuTeuAf8rNYR2zb1RvFns2Vs8hY",
    //     }
    //      */
    #[test]
    fn test_ffi_child_ops() {
        unsafe {
            let fingerprint = "eb79e0ff";
            let master_xprv: &str = "tprv8ZgxMBicQKsPduTkddZgfGyk4ZJjtEEZQjofpyJg74LizJ469DzoF8nmU1YcvBFskXVKdoYmLoRuZZR1wuTeuAf8rNYR2zb1RvFns2Vs8hY";
            let master_xprv_cstr = CString::new(master_xprv).unwrap().into_raw();

            let purpose_index = "84";
            let purpose_cstr = CString::new(purpose_index).unwrap().into_raw();

            let account_index = "0";
            let account_cstr = CString::new(account_index).unwrap().into_raw();
            let hardened_path = "m/84h/1h/0h";
            let account_xprv = "tprv8gqqcZU4CTQ9bFmmtVCfzeSU9ch3SfgpmHUPzFP5ktqYpnjAKL9wQK5vx89n7tgkz6Am42rFZLS9Qs4DmFvZmgukRE2b5CTwiCWrJsFUoxz";
            let account_xpub = "tpubDDXskyWJLq5pUioZn8sGQ46aieCybzsjLb5BGmRPBAdwfGyvwiyXaoho8EYJcgJa5QGHGYpDjLQ8gWzczWbxadeRkCuExW32Boh696yuQ9m";
            let child_keys = child::ChildKeys {
                fingerprint: fingerprint.to_string(),
                hardened_path: hardened_path.to_string(),
                xprv: account_xprv.to_string(),
                xpub: account_xpub.to_string(),
            };

            let stringified = serde_json::to_string(&child_keys).unwrap();

            let result = derive_hardened(master_xprv_cstr, purpose_cstr, account_cstr);
            let result_cstr = CStr::from_ptr(result);
            let result: &str = result_cstr.to_str().unwrap();
            assert_eq!(result, stringified);
        }
    }

    #[test]
    fn test_ffi_wallet() {
        unsafe {
            let xkey = "[db7d25b5/84'/1'/6']tpubDCCh4SuT3pSAQ1qAN86qKEzsLoBeiugoGGQeibmieRUKv8z6fCTTmEXsb9yeueBkUWjGVzJr91bCzeCNShorbBqjZV4WRGjz3CrJsCboXUe";
            let node_address_cstr = CString::new("default").unwrap().into_raw();

            let deposit_desc = format!("wsh(pk({}/0/*))", xkey);
            let deposit_desc_cstr = CString::new(deposit_desc).unwrap().into_raw();
            let balance_ptr = sync_balance(deposit_desc_cstr, node_address_cstr);
            let balance_str = CStr::from_ptr(balance_ptr).to_str().unwrap();
            let balance: history::WalletBalance = serde_json::from_str(balance_str).unwrap();
            assert_eq!(balance.balance, 10_000);
            let index_cstr = CString::new("0").unwrap().into_raw();
            let address_ptr = get_address(deposit_desc_cstr, node_address_cstr, index_cstr);
            let address_str = CStr::from_ptr(address_ptr).to_str().unwrap();
            let address: address::WalletAddress = serde_json::from_str(address_str).unwrap();
            assert_eq!(
                address.address,
                "tb1q5f3jl5lzlxtmhptfe9crhmv4wh392ku5ztkpt6xxmqqx2c3jyxrs8vgat7"
            );
            let network_cstr = CString::new("test").unwrap().into_raw();

            let conf_target = CString::new("1").unwrap().into_raw();
            let fees = get_fees(network_cstr, node_address_cstr, conf_target);
            let fees_str = CStr::from_ptr(fees).to_str().unwrap();

            let fees_struct: fees::NetworkFee = serde_json::from_str(fees_str).unwrap();
            assert!(fees_struct.fee >= 1.0);
        }
    }
    #[test]
    fn test_ffi_history() {
        unsafe {
            let descriptor = "wpkh([71b57c5d/84h/1h/0h]tprv8fUHbn7Tng83h8SvS6JLXM2bTViJai8N31obfNxAyXzaPxiyCxFqxeewBbcDu8jvpbquTW3577nRJc1KLChurPs6rQRefWTgUFH1ZnjU2ap/0/*)";
            let descriptor_cstr = CString::new(descriptor).unwrap().into_raw();
            let node_address_cstr = CString::new("default").unwrap().into_raw();
            let history_ptr = sync_history(descriptor_cstr, node_address_cstr);
            let history_str = CStr::from_ptr(history_ptr).to_str().unwrap();
            let history: history::WalletHistory = serde_json::from_str(history_str).unwrap();
            println!("{:#?}", history);
            // assert_eq!(history.history.len(),3);
        }
    }
}