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
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
// Magical Bitcoin Library
// Written in 2020 by
//     Alekos Filini <alekos.filini@gmail.com>
//
// Copyright (c) 2020 Magical Bitcoin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

//! BDK command line interface
//!
//! This lib provides [`structopt`] structs and enums that parse CLI options and sub-commands from
//! the command line or from a `String` vector that can be used to access features of the [`bdk`]
//! library. Functions are also provided to handle subcommands and options and provide results via
//! the [`bdk`] lib.
//!
//! See the [`bdk-cli`] example bin for how to use this lib to create a simple command line
//! application that demonstrates [`bdk`] wallet and key management features.
//!
//! See [`CliOpts`] for global cli options and [`CliSubCommand`] for supported top level sub-commands.
//!
//! [`structopt`]: https://docs.rs/crate/structopt
//! [`bdk`]: https://github.com/bitcoindevkit/bdk
//! [`bdk-cli`]: https://github.com/bitcoindevkit/bdk-cli/blob/master/src/bdk_cli.rs
//!
//! # Example
//!
//! ```no_run
//! # #[cfg(feature = "electrum")]
//! # {
//! # use bdk::bitcoin::Network;
//! # use bdk::blockchain::{AnyBlockchain, ConfigurableBlockchain};
//! # use bdk::blockchain::{AnyBlockchainConfig, ElectrumBlockchainConfig};
//! # use bdk_cli::{self, CliOpts, CliSubCommand, WalletOpts, OfflineWalletSubCommand, WalletSubCommand};
//! # use bdk::database::MemoryDatabase;
//! # use bdk::Wallet;
//! # use std::sync::Arc;
//! # use structopt::StructOpt;
//! # use std::str::FromStr;
//!
//! // to get args from cli use:
//! // let cli_opts = CliOpts::from_args();
//!
//! let cli_args = vec!["bdk-cli", "--network", "testnet", "wallet", "--descriptor",
//!                     "wpkh(tpubEBr4i6yk5nf5DAaJpsi9N2pPYBeJ7fZ5Z9rmN4977iYLCGco1VyjB9tvvuvYtfZzjD5A8igzgw3HeWeeKFmanHYqksqZXYXGsw5zjnj7KM9/*)",
//!                     "sync", "--max_addresses", "50"];
//!
//! let cli_opts = CliOpts::from_iter(&cli_args);
//! let network = cli_opts.network;
//!
//! if let CliSubCommand::Wallet {
//!         wallet_opts,
//!         subcommand: WalletSubCommand::OnlineWalletSubCommand(online_subcommand)
//!     } = cli_opts.subcommand {
//!
//!     let descriptor = wallet_opts.descriptor.as_str();
//!     let change_descriptor = wallet_opts.change_descriptor.as_deref();
//!
//!     let database = MemoryDatabase::new();
//!
//!     let config = AnyBlockchainConfig::Electrum(ElectrumBlockchainConfig {
//!                 url: wallet_opts.electrum_opts.server,
//!                 socks5: wallet_opts.proxy_opts.proxy,
//!                 retry: wallet_opts.proxy_opts.retries,
//!                 timeout: None,
//!                 stop_gap: 10
//!             });
//!
//!     let wallet = Wallet::new(
//!         descriptor,
//!         change_descriptor,
//!         network,
//!         database,
//!         AnyBlockchain::from_config(&config).unwrap(),
//!     ).unwrap();
//!
//!     let result = bdk_cli::handle_online_wallet_subcommand(&wallet, online_subcommand).unwrap();
//!     println!("{}", serde_json::to_string_pretty(&result).unwrap());
//! }
//! # }
//! ```

pub extern crate bdk;
#[macro_use]
extern crate serde_json;

#[cfg(any(
    feature = "electrum",
    feature = "esplora",
    feature = "compact_filters",
    feature = "rpc"
))]
#[macro_use]
extern crate bdk_macros;

use std::collections::BTreeMap;
use std::str::FromStr;

pub use structopt;
use structopt::StructOpt;

use crate::OfflineWalletSubCommand::*;
#[cfg(any(
    feature = "electrum",
    feature = "esplora",
    feature = "compact_filters",
    feature = "rpc"
))]
use crate::OnlineWalletSubCommand::*;
use bdk::bitcoin::consensus::encode::{deserialize, serialize, serialize_hex};
#[cfg(any(
    feature = "electrum",
    feature = "esplora",
    feature = "compact_filters",
    feature = "rpc"
))]
use bdk::bitcoin::hashes::hex::FromHex;
use bdk::bitcoin::secp256k1::Secp256k1;
use bdk::bitcoin::util::bip32::{DerivationPath, ExtendedPrivKey, KeySource};
use bdk::bitcoin::util::psbt::PartiallySignedTransaction;
use bdk::bitcoin::{Address, Network, OutPoint, Script, Txid};
#[cfg(any(
    feature = "electrum",
    feature = "esplora",
    feature = "compact_filters",
    feature = "rpc"
))]
use bdk::blockchain::{log_progress, Blockchain};
use bdk::database::BatchDatabase;
use bdk::descriptor::Segwitv0;
#[cfg(feature = "compiler")]
use bdk::descriptor::{Descriptor, Legacy, Miniscript};
use bdk::keys::bip39::{Language, Mnemonic, MnemonicType};
use bdk::keys::DescriptorKey::Secret;
use bdk::keys::KeyError::{InvalidNetwork, Message};
use bdk::keys::{DerivableKey, DescriptorKey, ExtendedKey, GeneratableKey, GeneratedKey};
use bdk::miniscript::miniscript;
#[cfg(feature = "compiler")]
use bdk::miniscript::policy::Concrete;
use bdk::wallet::AddressIndex;
use bdk::Error;
use bdk::SignOptions;
use bdk::{FeeRate, KeychainKind, Wallet};

/// Global options
///
/// The global options and top level sub-command required for all subsequent [`CliSubCommand`]'s.
///
/// # Example
///
/// ```
/// # #[cfg(any(feature = "electrum", feature = "esplora", feature = "compact_filters", feature = "rpc"))]
/// # {
/// # use bdk::bitcoin::Network;
/// # use structopt::StructOpt;
/// # use bdk_cli::{CliOpts, WalletOpts, CliSubCommand, WalletSubCommand};
/// # #[cfg(feature = "electrum")]
/// # use bdk_cli::ElectrumOpts;
/// # #[cfg(feature = "esplora")]
/// # use bdk_cli::EsploraOpts;
/// # #[cfg(feature = "rpc")]
/// # use bdk_cli::RpcOpts;
/// # #[cfg(feature = "compact_filters")]
/// # use bdk_cli::CompactFilterOpts;
/// # #[cfg(any(feature = "compact_filters", feature = "electrum", feature="esplora"))]
/// # use bdk_cli::ProxyOpts;
/// # use bdk_cli::OnlineWalletSubCommand::Sync;
///
/// let cli_args = vec!["bdk-cli", "--network", "testnet", "wallet",
///                     "--descriptor", "wpkh(tpubEBr4i6yk5nf5DAaJpsi9N2pPYBeJ7fZ5Z9rmN4977iYLCGco1VyjB9tvvuvYtfZzjD5A8igzgw3HeWeeKFmanHYqksqZXYXGsw5zjnj7KM9/44'/1'/0'/0/*)",
///                     "sync", "--max_addresses", "50"];
///
/// // to get CliOpts from the OS command line args use:
/// // let cli_opts = CliOpts::from_args();
/// let cli_opts = CliOpts::from_iter(&cli_args);
///
/// let expected_cli_opts = CliOpts {
///             network: Network::Testnet,
///             subcommand: CliSubCommand::Wallet {
///                 wallet_opts: WalletOpts {
///                     wallet: "main".to_string(),
///                     verbose: false,
///                     descriptor: "wpkh(tpubEBr4i6yk5nf5DAaJpsi9N2pPYBeJ7fZ5Z9rmN4977iYLCGco1VyjB9tvvuvYtfZzjD5A8igzgw3HeWeeKFmanHYqksqZXYXGsw5zjnj7KM9/44'/1'/0'/0/*)".to_string(),
///                     change_descriptor: None,
///               #[cfg(feature = "electrum")]
///               electrum_opts: ElectrumOpts {
///                   timeout: None,
///                   server: "ssl://electrum.blockstream.info:60002".to_string(),
///                   stop_gap: 10
///               },
///               #[cfg(feature = "esplora-ureq")]
///               esplora_opts: EsploraOpts {
///                   server: "https://blockstream.info/testnet/api/".to_string(),
///                   read_timeout: 5,
///                   write_timeout: 5,
///                   stop_gap: 10
///               },
///               #[cfg(feature = "esplora-reqwest")]
///               esplora_opts: EsploraOpts {
///                   server: "https://blockstream.info/testnet/api/".to_string(),
///                   conc: 4,
///                   stop_gap: 10
///               },
///                 #[cfg(feature = "rpc")]
///                 rpc_opts: RpcOpts{
///                    address: "127.0.0.1:18443".to_string(),
///                    auth: ("user".to_string(), "password".to_string()),
///                    skip_blocks: None,
///                },
///                #[cfg(feature = "compact_filters")]
///                compactfilter_opts: CompactFilterOpts{
///                    address: vec!["127.0.0.1:18444".to_string()],
///                    conn_count: 4,
///                    skip_blocks: 0,
///                },
///                #[cfg(any(feature="compact_filters", feature="electrum", feature="esplora"))]
///                    proxy_opts: ProxyOpts{
///                        proxy: None,
///                        proxy_auth: None,
///                        retries: 5,
///                    },
///                 },
///                 subcommand: WalletSubCommand::OnlineWalletSubCommand(Sync {
///                     max_addresses: Some(50)
///                 }),
///             },
///         };
///
/// assert_eq!(expected_cli_opts, cli_opts);
/// # }
/// ```

#[derive(Debug, StructOpt, Clone, PartialEq)]
#[structopt(name = "BDK CLI",
version = option_env ! ("CARGO_PKG_VERSION").unwrap_or("unknown"),
author = option_env ! ("CARGO_PKG_AUTHORS").unwrap_or(""))]
pub struct CliOpts {
    /// Sets the network
    #[structopt(
        name = "NETWORK",
        short = "n",
        long = "network",
        default_value = "testnet"
    )]
    pub network: Network,
    /// Top level cli sub-command
    #[structopt(subcommand)]
    pub subcommand: CliSubCommand,
}

/// CLI sub-commands
///
/// The top level sub-commands, each may have different required options. For
/// instance [`CliSubCommand::Wallet`] requires [`WalletOpts`] with a required descriptor but
/// [`CliSubCommand::Key`] sub-command does not. [`CliSubCommand::Repl`] also requires
/// [`WalletOpts`] and a descriptor because in this mode both [`WalletSubCommand`] and
/// [`KeySubCommand`] sub-commands are available.
#[derive(Debug, StructOpt, Clone, PartialEq)]
#[structopt(
    rename_all = "snake",
    long_about = "Top level options and command modes"
)]
pub enum CliSubCommand {
    /// Wallet options and sub-commands
    #[structopt(long_about = "Wallet mode")]
    Wallet {
        #[structopt(flatten)]
        wallet_opts: WalletOpts,
        #[structopt(subcommand)]
        subcommand: WalletSubCommand,
    },
    /// Key management sub-commands
    #[structopt(long_about = "Key management mode")]
    Key {
        #[structopt(subcommand)]
        subcommand: KeySubCommand,
    },
    /// Compile a miniscript policy to an output descriptor
    #[cfg(feature = "compiler")]
    #[structopt(long_about = "Miniscript policy compiler")]
    Compile {
        /// Sets the spending policy to compile
        #[structopt(name = "POLICY", required = true, index = 1)]
        policy: String,
        /// Sets the script type used to embed the compiled policy
        #[structopt(name = "TYPE", short = "t", long = "type", default_value = "wsh", possible_values = &["sh","wsh", "sh-wsh"])]
        script_type: String,
    },
    /// Enter REPL command loop mode
    #[cfg(feature = "repl")]
    #[structopt(long_about = "REPL command loop mode")]
    Repl {
        #[structopt(flatten)]
        wallet_opts: WalletOpts,
    },
}

/// Wallet sub-commands
///
/// Can use either an online or offline wallet. An [`OnlineWalletSubCommand`] requires a blockchain
/// client and network connection and an [`OfflineWalletSubCommand`] does not.
#[derive(Debug, StructOpt, Clone, PartialEq)]
pub enum WalletSubCommand {
    #[cfg(any(
        feature = "electrum",
        feature = "esplora",
        feature = "compact_filters",
        feature = "rpc"
    ))]
    #[structopt(flatten)]
    OnlineWalletSubCommand(OnlineWalletSubCommand),
    #[structopt(flatten)]
    OfflineWalletSubCommand(OfflineWalletSubCommand),
}

/// Wallet options
///
/// The wallet options required for all [`CliSubCommand::Wallet`] or [`CliSubCommand::Repl`]
/// sub-commands. These options capture wallet descriptor and blockchain client information. The
/// blockchain client details are only used for [`OnlineWalletSubCommand`]s.
///
/// # Example
///
/// ```
/// # use bdk::bitcoin::Network;
/// # use structopt::StructOpt;
/// # use bdk_cli::WalletOpts;
/// # #[cfg(feature = "electrum")]
/// # use bdk_cli::ElectrumOpts;
/// # #[cfg(feature = "esplora")]
/// # use bdk_cli::EsploraOpts;
/// # #[cfg(feature = "compact_filters")]
/// # use bdk_cli::CompactFilterOpts;
/// # #[cfg(feature = "rpc")]
/// # use bdk_cli::RpcOpts;
/// # #[cfg(any(feature = "compact_filters", feature = "electrum", feature="esplora"))]
/// # use bdk_cli::ProxyOpts;
///
/// let cli_args = vec!["wallet",
///                     "--descriptor", "wpkh(tpubEBr4i6yk5nf5DAaJpsi9N2pPYBeJ7fZ5Z9rmN4977iYLCGco1VyjB9tvvuvYtfZzjD5A8igzgw3HeWeeKFmanHYqksqZXYXGsw5zjnj7KM9/44'/1'/0'/0/*)"];
///
/// // to get WalletOpt from OS command line args use:
/// // let wallet_opt = WalletOpt::from_args();
///
/// let wallet_opts = WalletOpts::from_iter(&cli_args);
///
/// let expected_wallet_opts = WalletOpts {
///               wallet: "main".to_string(),
///                     verbose: false,
///               descriptor: "wpkh(tpubEBr4i6yk5nf5DAaJpsi9N2pPYBeJ7fZ5Z9rmN4977iYLCGco1VyjB9tvvuvYtfZzjD5A8igzgw3HeWeeKFmanHYqksqZXYXGsw5zjnj7KM9/44'/1'/0'/0/*)".to_string(),
///               change_descriptor: None,
///               #[cfg(feature = "electrum")]
///               electrum_opts: ElectrumOpts {
///                   timeout: None,
///                   server: "ssl://electrum.blockstream.info:60002".to_string(),
///                   stop_gap: 10
///               },
///               #[cfg(feature = "esplora-ureq")]
///               esplora_opts: EsploraOpts {
///                   server: "https://blockstream.info/testnet/api/".to_string(),
///                   read_timeout: 5,
///                   write_timeout: 5,
///                   stop_gap: 10
///               },
///               #[cfg(feature = "esplora-reqwest")]
///               esplora_opts: EsploraOpts {
///                   server: "https://blockstream.info/testnet/api/".to_string(),
///                   conc: 4,
///                   stop_gap: 10
///               },
///                #[cfg(feature = "compact_filters")]
///                compactfilter_opts: CompactFilterOpts{
///                    address: vec!["127.0.0.1:18444".to_string()],
///                    conn_count: 4,
///                    skip_blocks: 0,
///                },
///                 #[cfg(feature = "rpc")]
///                 rpc_opts: RpcOpts{
///                    address: "127.0.0.1:18443".to_string(),
///                    auth: ("user".to_string(), "password".to_string()),
///                    skip_blocks: None,
///                },
///               #[cfg(any(feature="compact_filters", feature="electrum", feature="esplora"))]
///                    proxy_opts: ProxyOpts{
///                        proxy: None,
///                        proxy_auth: None,
///                        retries: 5,
///               },
/// };
///
/// assert_eq!(expected_wallet_opts, wallet_opts);
/// ```

#[derive(Debug, StructOpt, Clone, PartialEq)]
pub struct WalletOpts {
    /// Selects the wallet to use
    #[structopt(
        name = "WALLET_NAME",
        short = "w",
        long = "wallet",
        default_value = "main"
    )]
    pub wallet: String,
    /// Adds verbosity, returns PSBT in JSON format alongside serialized, displays expanded objects
    #[structopt(name = "VERBOSE", short = "v", long = "verbose")]
    pub verbose: bool,
    /// Sets the descriptor to use for the external addresses
    #[structopt(name = "DESCRIPTOR", short = "d", long = "descriptor", required = true)]
    pub descriptor: String,
    /// Sets the descriptor to use for internal addresses
    #[structopt(name = "CHANGE_DESCRIPTOR", short = "c", long = "change_descriptor")]
    pub change_descriptor: Option<String>,
    #[cfg(feature = "electrum")]
    #[structopt(flatten)]
    pub electrum_opts: ElectrumOpts,
    #[cfg(feature = "esplora")]
    #[structopt(flatten)]
    pub esplora_opts: EsploraOpts,
    #[cfg(feature = "compact_filters")]
    #[structopt(flatten)]
    pub compactfilter_opts: CompactFilterOpts,
    #[cfg(feature = "rpc")]
    #[structopt(flatten)]
    pub rpc_opts: RpcOpts,
    #[cfg(any(feature = "compact_filters", feature = "electrum", feature = "esplora"))]
    #[structopt(flatten)]
    pub proxy_opts: ProxyOpts,
}

/// Proxy Server options
///
/// Only activated for `compact_filters` or `electrum`
#[cfg(any(feature = "compact_filters", feature = "electrum", feature = "esplora"))]
#[derive(Debug, StructOpt, Clone, PartialEq)]
pub struct ProxyOpts {
    /// Sets the SOCKS5 proxy for Blockchain backend
    #[structopt(name = "PROXY_ADDRS:PORT", long = "proxy", short = "p")]
    pub proxy: Option<String>,

    /// Sets the SOCKS5 proxy credential
    #[structopt(name="PROXY_USER:PASSWD", long="proxy_auth", short="a", parse(try_from_str = parse_proxy_auth))]
    pub proxy_auth: Option<(String, String)>,

    /// Sets the SOCKS5 proxy retries for the Electrum client
    #[structopt(
        name = "PROXY_RETRIES",
        short = "r",
        long = "retries",
        default_value = "5"
    )]
    pub retries: u8,
}

/// Compact Filter options
///
/// Compact filter peer information used by [`OnlineWalletSubCommand`]s.
#[cfg(feature = "compact_filters")]
#[derive(Debug, StructOpt, Clone, PartialEq)]
pub struct CompactFilterOpts {
    /// Sets the full node network address
    #[structopt(
        name = "ADDRESS:PORT",
        short = "n",
        long = "node",
        default_value = "127.0.0.1:18444"
    )]
    pub address: Vec<String>,

    /// Sets the number of parallel node connections
    #[structopt(name = "CONNECTIONS", long = "conn_count", default_value = "4")]
    pub conn_count: usize,

    /// Optionally skip initial `skip_blocks` blocks
    #[structopt(
        name = "SKIP_BLOCKS",
        short = "k",
        long = "skip_blocks",
        default_value = "0"
    )]
    pub skip_blocks: usize,
}

#[cfg(feature = "rpc")]
#[derive(Debug, StructOpt, Clone, PartialEq)]
pub struct RpcOpts {
    /// Sets the full node address for rpc connection
    #[structopt(
        name = "ADDRESS:PORT",
        short = "n",
        long = "node",
        default_value = "127.0.0.1:18443"
    )]
    pub address: String,

    /// Sets the rpc authentication username:password
    #[structopt(
        name = "USER:PASSWD",
        short = "a",
        long = "auth",
        parse(try_from_str = parse_proxy_auth),
        default_value = "user:password",
    )]
    pub auth: (String, String),

    /// Optionally skip initial `skip_blocks` blocks
    #[structopt(name = "SKIP_BLOCKS", short = "s", long = "skip-blocks")]
    pub skip_blocks: Option<u32>,
}

/// Electrum options
///
/// Electrum blockchain client information used by [`OnlineWalletSubCommand`]s.
#[cfg(feature = "electrum")]
#[derive(Debug, StructOpt, Clone, PartialEq)]
pub struct ElectrumOpts {
    /// Sets the SOCKS5 proxy timeout for the Electrum client
    #[structopt(name = "PROXY_TIMEOUT", short = "t", long = "timeout")]
    pub timeout: Option<u8>,
    /// Sets the Electrum server to use
    #[structopt(
        name = "ELECTRUM_URL",
        short = "s",
        long = "server",
        default_value = "ssl://electrum.blockstream.info:60002"
    )]
    pub server: String,

    /// Stop searching addresses for transactions after finding an unused gap of this length.
    #[structopt(
        name = "STOP_GAP",
        long = "stop_gap",
        short = "g",
        default_value = "10"
    )]
    pub stop_gap: usize,
}

/// Esplora options
///
/// Esplora blockchain client information used by [`OnlineWalletSubCommand`]s.
#[cfg(feature = "esplora-ureq")]
#[derive(Debug, StructOpt, Clone, PartialEq)]
pub struct EsploraOpts {
    /// Use the esplora server if given as parameter
    #[structopt(
        name = "ESPLORA_URL",
        short = "s",
        long = "server",
        default_value = "https://blockstream.info/testnet/api/"
    )]
    pub server: String,

    /// Socket read timeout
    #[structopt(name = "READ_TIMEOUT", long = "read_timeout", default_value = "5")]
    pub read_timeout: u64,

    /// Socket write timeout
    #[structopt(name = "WRITE_TIMEOUT", long = "write_timeout", default_value = "5")]
    pub write_timeout: u64,

    /// Stop searching addresses for transactions after finding an unused gap of this length.
    #[structopt(
        name = "STOP_GAP",
        long = "stop_gap",
        short = "g",
        default_value = "10"
    )]
    pub stop_gap: usize,
}

#[cfg(feature = "esplora-reqwest")]
#[derive(Debug, StructOpt, Clone, PartialEq)]
pub struct EsploraOpts {
    /// Use the esplora server if given as parameter
    #[structopt(
        name = "ESPLORA_URL",
        short = "s",
        long = "server",
        default_value = "https://blockstream.info/testnet/api/"
    )]
    pub server: String,

    /// Number of parallel requests sent to the esplora service (default: 4)
    #[structopt(name = "CONCURRENCY", long = "conc", default_value = "4")]
    pub conc: u8,

    /// Stop searching addresses for transactions after finding an unused gap of this length.
    #[structopt(
        name = "STOP_GAP",
        long = "stop_gap",
        short = "g",
        default_value = "10"
    )]
    pub stop_gap: usize,
}

// This is a workaround for `structopt` issue #333, #391, #418; see https://github.com/TeXitoi/structopt/issues/333#issuecomment-712265332
#[cfg_attr(not(doc), allow(missing_docs))]
#[cfg_attr(
    doc,
    doc = r#"
Offline Wallet sub-command

[`CliSubCommand::Wallet`] sub-commands that do not require a blockchain client and network
connection. These sub-commands use only the provided descriptor or locally cached wallet
information.

# Example

```
# use bdk_cli::OfflineWalletSubCommand;
# use structopt::StructOpt;

let address_sub_command = OfflineWalletSubCommand::from_iter(&["wallet", "get_new_address"]);
assert!(matches!(
     address_sub_command,
    OfflineWalletSubCommand::GetNewAddress
));
```

To capture wallet sub-commands from a string vector without a preceeding binary name you can
create a custom struct the includes the `NoBinaryName` clap setting and wraps the WalletSubCommand
enum. See also the [`bdk-cli`](https://github.com/bitcoindevkit/bdk-cli/blob/master/src/bdkcli.rs)
example app.
"#
)]
#[cfg_attr(
    all(doc, feature = "repl"),
    doc = r#"

# Example
```
# use bdk_cli::OfflineWalletSubCommand;
# use structopt::StructOpt;
# use clap::AppSettings;

#[derive(Debug, StructOpt, Clone, PartialEq)]
#[structopt(name = "BDK CLI", setting = AppSettings::NoBinaryName,
version = option_env ! ("CARGO_PKG_VERSION").unwrap_or("unknown"),
author = option_env ! ("CARGO_PKG_AUTHORS").unwrap_or(""))]
struct ReplOpts {
    /// Wallet sub-command
    #[structopt(subcommand)]
    pub subcommand: OfflineWalletSubCommand,
}

let repl_opts = ReplOpts::from_iter(&["get_new_address"]);
assert!(matches!(
    repl_opts.subcommand,
    OfflineWalletSubCommand::GetNewAddress
));
"#
)]
#[derive(Debug, StructOpt, Clone, PartialEq)]
#[structopt(rename_all = "snake")]
pub enum OfflineWalletSubCommand {
    /// Generates a new external address
    GetNewAddress,
    /// Lists the available spendable UTXOs
    ListUnspent,
    /// Lists all the incoming and outgoing transactions of the wallet
    ListTransactions,
    /// Returns the current wallet balance
    GetBalance,
    /// Creates a new unsigned transaction
    CreateTx {
        /// Adds a recipient to the transaction
        #[structopt(name = "ADDRESS:SAT", long = "to", required = true, parse(try_from_str = parse_recipient))]
        recipients: Vec<(Script, u64)>,
        /// Sends all the funds (or all the selected utxos). Requires only one recipients of value 0
        #[structopt(short = "all", long = "send_all")]
        send_all: bool,
        /// Enables Replace-By-Fee (BIP125)
        #[structopt(short = "rbf", long = "enable_rbf")]
        enable_rbf: bool,
        /// Make a PSBT that can be signed by offline signers and hardware wallets. Forces the addition of `non_witness_utxo` and more details to let the signer identify the change output.
        #[structopt(long = "offline_signer")]
        offline_signer: bool,
        /// Selects which utxos *must* be spent
        #[structopt(name = "MUST_SPEND_TXID:VOUT", long = "utxos", parse(try_from_str = parse_outpoint))]
        utxos: Option<Vec<OutPoint>>,
        /// Marks a utxo as unspendable
        #[structopt(name = "CANT_SPEND_TXID:VOUT", long = "unspendable", parse(try_from_str = parse_outpoint))]
        unspendable: Option<Vec<OutPoint>>,
        /// Fee rate to use in sat/vbyte
        #[structopt(name = "SATS_VBYTE", short = "fee", long = "fee_rate")]
        fee_rate: Option<f32>,
        /// Selects which policy should be used to satisfy the external descriptor
        #[structopt(name = "EXT_POLICY", long = "external_policy")]
        external_policy: Option<String>,
        /// Selects which policy should be used to satisfy the internal descriptor
        #[structopt(name = "INT_POLICY", long = "internal_policy")]
        internal_policy: Option<String>,
    },
    /// Bumps the fees of an RBF transaction
    BumpFee {
        /// TXID of the transaction to update
        #[structopt(name = "TXID", short = "txid", long = "txid")]
        txid: String,
        /// Allows the wallet to reduce the amount of the only output in order to increase fees. This is generally the expected behavior for transactions originally created with `send_all`
        #[structopt(short = "all", long = "send_all")]
        send_all: bool,
        /// Make a PSBT that can be signed by offline signers and hardware wallets. Forces the addition of `non_witness_utxo` and more details to let the signer identify the change output.
        #[structopt(long = "offline_signer")]
        offline_signer: bool,
        /// Selects which utxos *must* be added to the tx. Unconfirmed utxos cannot be used
        #[structopt(name = "MUST_SPEND_TXID:VOUT", long = "utxos", parse(try_from_str = parse_outpoint))]
        utxos: Option<Vec<OutPoint>>,
        /// Marks an utxo as unspendable, in case more inputs are needed to cover the extra fees
        #[structopt(name = "CANT_SPEND_TXID:VOUT", long = "unspendable", parse(try_from_str = parse_outpoint))]
        unspendable: Option<Vec<OutPoint>>,
        /// The new targeted fee rate in sat/vbyte
        #[structopt(name = "SATS_VBYTE", short = "fee", long = "fee_rate")]
        fee_rate: f32,
    },
    /// Returns the available spending policies for the descriptor
    Policies,
    /// Returns the public version of the wallet's descriptor(s)
    PublicDescriptor,
    /// Signs and tries to finalize a PSBT
    Sign {
        /// Sets the PSBT to sign
        #[structopt(name = "BASE64_PSBT", long = "psbt")]
        psbt: String,
        /// Assume the blockchain has reached a specific height. This affects the transaction finalization, if there are timelocks in the descriptor
        #[structopt(name = "HEIGHT", long = "assume_height")]
        assume_height: Option<u32>,
    },
    /// Extracts a raw transaction from a PSBT
    ExtractPsbt {
        /// Sets the PSBT to extract
        #[structopt(name = "BASE64_PSBT", long = "psbt")]
        psbt: String,
    },
    /// Finalizes a PSBT
    FinalizePsbt {
        /// Sets the PSBT to finalize
        #[structopt(name = "BASE64_PSBT", long = "psbt")]
        psbt: String,
        /// Assume the blockchain has reached a specific height
        #[structopt(name = "HEIGHT", long = "assume_height")]
        assume_height: Option<u32>,
    },
    /// Combines multiple PSBTs into one
    CombinePsbt {
        /// Add one PSBT to combine. This option can be repeated multiple times, one for each PSBT
        #[structopt(name = "BASE64_PSBT", long = "psbt", required = true)]
        psbt: Vec<String>,
    },
}

#[cfg_attr(not(doc), allow(missing_docs))]
#[cfg_attr(
    doc,
    doc = r#"
Online Wallet sub-command

[`CliSubCommand::Wallet`] sub-commands that require a blockchain client and network connection.
These sub-commands use a provided descriptor, locally cached wallet information, and require a
blockchain client and network connection.
"#
)]
#[derive(Debug, StructOpt, Clone, PartialEq)]
#[structopt(rename_all = "snake")]
#[cfg(any(
    feature = "electrum",
    feature = "esplora",
    feature = "compact_filters",
    feature = "rpc"
))]
pub enum OnlineWalletSubCommand {
    /// Syncs with the chosen blockchain server
    Sync {
        /// max addresses to consider
        #[structopt(short = "v", long = "max_addresses")]
        max_addresses: Option<u32>,
    },
    /// Broadcasts a transaction to the network. Takes either a raw transaction or a PSBT to extract
    Broadcast {
        /// Sets the PSBT to sign
        #[structopt(
            name = "BASE64_PSBT",
            long = "psbt",
            required_unless = "RAWTX",
            conflicts_with = "RAWTX"
        )]
        psbt: Option<String>,
        /// Sets the raw transaction to broadcast
        #[structopt(
            name = "RAWTX",
            long = "tx",
            required_unless = "BASE64_PSBT",
            conflicts_with = "BASE64_PSBT"
        )]
        tx: Option<String>,
    },
}

fn parse_recipient(s: &str) -> Result<(Script, u64), String> {
    let parts: Vec<_> = s.split(':').collect();
    if parts.len() != 2 {
        return Err("Invalid format".to_string());
    }

    let addr = Address::from_str(parts[0]);
    if let Err(e) = addr {
        return Err(format!("{:?}", e));
    }
    let val = u64::from_str(parts[1]);
    if let Err(e) = val {
        return Err(format!("{:?}", e));
    }

    Ok((addr.unwrap().script_pubkey(), val.unwrap()))
}
#[cfg(any(
    feature = "electrum",
    feature = "compact_filters",
    feature = "esplora",
    feature = "rpc"
))]
fn parse_proxy_auth(s: &str) -> Result<(String, String), String> {
    let parts: Vec<_> = s.split(':').collect();
    if parts.len() != 2 {
        return Err("Invalid format".to_string());
    }

    let user = parts[0].to_string();
    let passwd = parts[1].to_string();

    Ok((user, passwd))
}

fn parse_outpoint(s: &str) -> Result<OutPoint, String> {
    OutPoint::from_str(s).map_err(|e| format!("{:?}", e))
}

/// Execute an offline wallet sub-command
///
/// Offline wallet sub-commands are described in [`OfflineWalletSubCommand`].
pub fn handle_offline_wallet_subcommand<T, D>(
    wallet: &Wallet<T, D>,
    wallet_opts: &WalletOpts,
    offline_subcommand: OfflineWalletSubCommand,
) -> Result<serde_json::Value, Error>
where
    D: BatchDatabase,
{
    match offline_subcommand {
        GetNewAddress => Ok(json!({"address": wallet.get_address(AddressIndex::New)?.address})),
        ListUnspent => Ok(serde_json::to_value(&wallet.list_unspent()?)?),
        ListTransactions => Ok(serde_json::to_value(
            &wallet.list_transactions(wallet_opts.verbose)?,
        )?),
        GetBalance => Ok(json!({"satoshi": wallet.get_balance()?})),
        CreateTx {
            recipients,
            send_all,
            enable_rbf,
            offline_signer,
            utxos,
            unspendable,
            fee_rate,
            external_policy,
            internal_policy,
        } => {
            let mut tx_builder = wallet.build_tx();

            if send_all {
                tx_builder.drain_wallet().drain_to(recipients[0].0.clone());
            } else {
                tx_builder.set_recipients(recipients);
            }

            if enable_rbf {
                tx_builder.enable_rbf();
            }

            if offline_signer {
                tx_builder.include_output_redeem_witness_script();
            }

            if let Some(fee_rate) = fee_rate {
                tx_builder.fee_rate(FeeRate::from_sat_per_vb(fee_rate));
            }

            if let Some(utxos) = utxos {
                tx_builder.add_utxos(&utxos[..])?.manually_selected_only();
            }

            if let Some(unspendable) = unspendable {
                tx_builder.unspendable(unspendable);
            }

            let policies = vec![
                external_policy.map(|p| (p, KeychainKind::External)),
                internal_policy.map(|p| (p, KeychainKind::Internal)),
            ];

            for (policy, keychain) in policies.into_iter().flatten() {
                let policy = serde_json::from_str::<BTreeMap<String, Vec<usize>>>(&policy)
                    .map_err(|s| Error::Generic(s.to_string()))?;
                tx_builder.policy_path(policy, keychain);
            }

            let (psbt, details) = tx_builder.finish()?;
            if wallet_opts.verbose {
                Ok(
                    json!({"psbt": base64::encode(&serialize(&psbt)),"details": details, "serialized_psbt": psbt}),
                )
            } else {
                Ok(json!({"psbt": base64::encode(&serialize(&psbt)),"details": details}))
            }
        }
        BumpFee {
            txid,
            send_all,
            offline_signer,
            utxos,
            unspendable,
            fee_rate,
        } => {
            let txid = Txid::from_str(txid.as_str()).map_err(|s| Error::Generic(s.to_string()))?;

            let mut tx_builder = wallet.build_fee_bump(txid)?;
            tx_builder.fee_rate(FeeRate::from_sat_per_vb(fee_rate));

            if send_all {
                // TODO: Find a way to get the recipient scriptpubkey to allow shrinking
                //tx_builder.allow_shrinking()
            }

            if offline_signer {
                tx_builder.include_output_redeem_witness_script();
            }

            if let Some(utxos) = utxos {
                tx_builder.add_utxos(&utxos[..])?;
            }

            if let Some(unspendable) = unspendable {
                tx_builder.unspendable(unspendable);
            }

            let (psbt, details) = tx_builder.finish()?;
            Ok(json!({"psbt": base64::encode(&serialize(&psbt)),"details": details,}))
        }
        Policies => Ok(json!({
            "external": wallet.policies(KeychainKind::External)?,
            "internal": wallet.policies(KeychainKind::Internal)?,
        })),
        PublicDescriptor => Ok(json!({
            "external": wallet.public_descriptor(KeychainKind::External)?.map(|d| d.to_string()),
            "internal": wallet.public_descriptor(KeychainKind::Internal)?.map(|d| d.to_string()),
        })),
        Sign {
            psbt,
            assume_height,
        } => {
            let psbt = base64::decode(&psbt).unwrap();
            let mut psbt: PartiallySignedTransaction = deserialize(&psbt).unwrap();
            let signopt = SignOptions {
                assume_height,
                ..Default::default()
            };
            let finalized = wallet.sign(&mut psbt, signopt)?;
            if wallet_opts.verbose {
                Ok(
                    json!({"psbt": base64::encode(&serialize(&psbt)),"is_finalized": finalized, "serialized_psbt": psbt}),
                )
            } else {
                Ok(json!({"psbt": base64::encode(&serialize(&psbt)),"is_finalized": finalized,}))
            }
        }
        ExtractPsbt { psbt } => {
            let psbt = base64::decode(&psbt).unwrap();
            let psbt: PartiallySignedTransaction = deserialize(&psbt).unwrap();
            Ok(json!({"raw_tx": serialize_hex(&psbt.extract_tx()),}))
        }
        FinalizePsbt {
            psbt,
            assume_height,
        } => {
            let psbt = base64::decode(&psbt).unwrap();
            let mut psbt: PartiallySignedTransaction = deserialize(&psbt).unwrap();

            let signopt = SignOptions {
                assume_height,
                ..Default::default()
            };
            let finalized = wallet.finalize_psbt(&mut psbt, signopt)?;
            if wallet_opts.verbose {
                Ok(
                    json!({ "psbt": base64::encode(&serialize(&psbt)),"is_finalized": finalized, "serialized_psbt": psbt}),
                )
            } else {
                Ok(json!({ "psbt": base64::encode(&serialize(&psbt)),"is_finalized": finalized,}))
            }
        }
        CombinePsbt { psbt } => {
            let mut psbts = psbt
                .iter()
                .map(|s| {
                    let psbt = base64::decode(&s).unwrap();
                    let psbt: PartiallySignedTransaction = deserialize(&psbt).unwrap();
                    psbt
                })
                .collect::<Vec<_>>();

            let init_psbt = psbts.pop().unwrap();
            let final_psbt = psbts
                .into_iter()
                .try_fold::<_, _, Result<PartiallySignedTransaction, Error>>(
                    init_psbt,
                    |mut acc, x| {
                        acc.merge(x)?;
                        Ok(acc)
                    },
                )?;
            Ok(json!({ "psbt": base64::encode(&serialize(&final_psbt)) }))
        }
    }
}

/// Execute an online wallet sub-command
///
/// Online wallet sub-commands are described in [`OnlineWalletSubCommand`]. See [`crate`] for
/// example usage.
#[cfg(any(
    feature = "electrum",
    feature = "esplora",
    feature = "compact_filters",
    feature = "rpc"
))]
#[maybe_async]
pub fn handle_online_wallet_subcommand<C, D>(
    wallet: &Wallet<C, D>,
    online_subcommand: OnlineWalletSubCommand,
) -> Result<serde_json::Value, Error>
where
    C: Blockchain,
    D: BatchDatabase,
{
    match online_subcommand {
        Sync { max_addresses } => {
            maybe_await!(wallet.sync(log_progress(), max_addresses))?;
            Ok(json!({}))
        }
        Broadcast { psbt, tx } => {
            let tx = match (psbt, tx) {
                (Some(psbt), None) => {
                    let psbt = base64::decode(&psbt).unwrap();
                    let psbt: PartiallySignedTransaction = deserialize(&psbt).unwrap();
                    psbt.extract_tx()
                }
                (None, Some(tx)) => deserialize(&Vec::<u8>::from_hex(&tx).unwrap()).unwrap(),
                (Some(_), Some(_)) => panic!("Both `psbt` and `tx` options not allowed"),
                (None, None) => panic!("Missing `psbt` and `tx` option"),
            };

            let txid = maybe_await!(wallet.broadcast(tx))?;
            Ok(json!({ "txid": txid }))
        }
    }
}

#[cfg_attr(not(doc), allow(missing_docs))]
#[cfg_attr(
    doc,
    doc = r#"
Key sub-command

Provides basic key operations that are not related to a specific wallet such as generating a
new random master extended key or restoring a master extended key from mnemonic words.

These sub-commands are **EXPERIMENTAL** and should only be used for testing. Do not use this
feature to create keys that secure actual funds on the Bitcoin mainnet.
"#
)]
#[derive(Debug, StructOpt, Clone, PartialEq)]
#[structopt(rename_all = "snake")]
pub enum KeySubCommand {
    /// Generates new random seed mnemonic phrase and corresponding master extended key
    Generate {
        /// Entropy level based on number of random seed mnemonic words
        #[structopt(
        name = "WORD_COUNT",
        short = "e",
        long = "entropy",
        default_value = "24",
        possible_values = &["12","24"],
        )]
        word_count: usize,
        /// Seed password
        #[structopt(name = "PASSWORD", short = "p", long = "password")]
        password: Option<String>,
    },
    /// Restore a master extended key from seed backup mnemonic words
    Restore {
        /// Seed mnemonic words, must be quoted (eg. "word1 word2 ...")
        #[structopt(name = "MNEMONIC", short = "m", long = "mnemonic")]
        mnemonic: String,
        /// Seed password
        #[structopt(name = "PASSWORD", short = "p", long = "password")]
        password: Option<String>,
    },
    /// Derive a child key pair from a master extended key and a derivation path string (eg. "m/84'/1'/0'/0" or "m/84h/1h/0h/0")
    Derive {
        /// Extended private key to derive from
        #[structopt(name = "XPRV", short = "x", long = "xprv")]
        xprv: ExtendedPrivKey,
        /// Path to use to derive extended public key from extended private key
        #[structopt(name = "PATH", short = "p", long = "path")]
        path: DerivationPath,
    },
}

/// Execute a key sub-command
///
/// Key sub-commands are described in [`KeySubCommand`].
pub fn handle_key_subcommand(
    network: Network,
    subcommand: KeySubCommand,
) -> Result<serde_json::Value, Error> {
    let secp = Secp256k1::new();

    match subcommand {
        KeySubCommand::Generate {
            word_count,
            password,
        } => {
            let mnemonic_type = match word_count {
                12 => MnemonicType::Words12,
                _ => MnemonicType::Words24,
            };
            let mnemonic: GeneratedKey<_, miniscript::BareCtx> =
                Mnemonic::generate((mnemonic_type, Language::English)).unwrap();
            //.map_err(|e| KeyError::from(e.unwrap()))?;
            let mnemonic = mnemonic.into_key();
            let xkey: ExtendedKey = (mnemonic.clone(), password).into_extended_key()?;
            let xprv = xkey.into_xprv(network).unwrap();
            let fingerprint = xprv.fingerprint(&secp);
            Ok(
                json!({ "mnemonic": mnemonic.phrase(), "xprv": xprv.to_string(), "fingerprint": fingerprint.to_string() }),
            )
        }
        KeySubCommand::Restore { mnemonic, password } => {
            let mnemonic = Mnemonic::from_phrase(mnemonic.as_ref(), Language::English).unwrap();
            //     .map_err(|e| {
            //     KeyError::from(e.downcast::<bdk::keys::bip39::ErrorKind>().unwrap())
            // })?;
            let xkey: ExtendedKey = (mnemonic, password).into_extended_key()?;
            let xprv = xkey.into_xprv(network).unwrap();
            let fingerprint = xprv.fingerprint(&secp);

            Ok(json!({ "xprv": xprv.to_string(), "fingerprint": fingerprint.to_string() }))
        }
        KeySubCommand::Derive { xprv, path } => {
            if xprv.network != network {
                return Err(Error::Key(InvalidNetwork));
            }
            let derived_xprv = &xprv.derive_priv(&secp, &path)?;

            let origin: KeySource = (xprv.fingerprint(&secp), path);

            let derived_xprv_desc_key: DescriptorKey<Segwitv0> =
                derived_xprv.into_descriptor_key(Some(origin), DerivationPath::default())?;

            if let Secret(desc_seckey, _, _) = derived_xprv_desc_key {
                let desc_pubkey = desc_seckey.as_public(&secp).unwrap();
                Ok(json!({"xpub": desc_pubkey.to_string(), "xprv": desc_seckey.to_string()}))
            } else {
                Err(Error::Key(Message("Invalid key variant".to_string())))
            }
        }
    }
}

/// Execute the miniscript compiler sub-command
///
/// Compiler options are described in [`CliSubCommand::Compile`].
#[cfg(feature = "compiler")]
pub fn handle_compile_subcommand(
    _network: Network,
    policy: String,
    script_type: String,
) -> Result<serde_json::Value, Error> {
    let policy = Concrete::<String>::from_str(policy.as_str())?;
    let legacy_policy: Miniscript<String, Legacy> = policy
        .compile()
        .map_err(|e| Error::Generic(e.to_string()))?;
    let segwit_policy: Miniscript<String, Segwitv0> = policy
        .compile()
        .map_err(|e| Error::Generic(e.to_string()))?;

    let descriptor = match script_type.as_str() {
        "sh" => Descriptor::new_sh(legacy_policy),
        "wsh" => Descriptor::new_wsh(segwit_policy),
        "sh-wsh" => Descriptor::new_sh_wsh(segwit_policy),
        _ => panic!("Invalid type"),
    }
    .map_err(Error::Miniscript)?;

    Ok(json!({"descriptor": descriptor.to_string()}))
}

#[cfg(test)]
mod test {
    use super::{CliOpts, WalletOpts};
    #[cfg(feature = "compiler")]
    use crate::handle_compile_subcommand;
    #[cfg(feature = "compact_filters")]
    use crate::CompactFilterOpts;
    #[cfg(feature = "electrum")]
    use crate::ElectrumOpts;
    #[cfg(feature = "esplora")]
    use crate::EsploraOpts;
    use crate::OfflineWalletSubCommand::{CreateTx, GetNewAddress};
    #[cfg(any(
        feature = "electrum",
        feature = "esplora",
        feature = "compact_filters",
        feature = "rpc"
    ))]
    use crate::OnlineWalletSubCommand::{Broadcast, Sync};
    #[cfg(any(feature = "compact_filters", feature = "electrum", feature = "esplora"))]
    use crate::ProxyOpts;
    #[cfg(feature = "rpc")]
    use crate::RpcOpts;
    use crate::{handle_key_subcommand, CliSubCommand, KeySubCommand, WalletSubCommand};

    use bdk::bitcoin::util::bip32::{DerivationPath, ExtendedPrivKey};
    use bdk::bitcoin::{Address, Network, OutPoint};
    use bdk::miniscript::bitcoin::network::constants::Network::Testnet;
    use std::str::FromStr;
    use structopt::StructOpt;

    #[test]
    fn test_parse_wallet_get_new_address() {
        let cli_args = vec!["bdk-cli", "--network", "bitcoin", "wallet",
                            "--descriptor", "wpkh(xpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/0/*)",
                            "--change_descriptor", "wpkh(xpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/1/*)",
                            "get_new_address"];

        let cli_opts = CliOpts::from_iter(&cli_args);

        let expected_cli_opts = CliOpts {
            network: Network::Bitcoin,
            subcommand: CliSubCommand::Wallet {
                wallet_opts: WalletOpts {
                    wallet: "main".to_string(),
                    verbose: false,
                    descriptor: "wpkh(xpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/0/*)".to_string(),
                    change_descriptor: Some("wpkh(xpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/1/*)".to_string()),
                    #[cfg(feature = "electrum")]
                    electrum_opts: ElectrumOpts {
                        timeout: None,
                        server: "ssl://electrum.blockstream.info:60002".to_string(),
                        stop_gap: 10,
                    },
                    #[cfg(feature = "esplora-ureq")]
                    esplora_opts: EsploraOpts {
                        server: "https://blockstream.info/testnet/api/".to_string(),
                        read_timeout: 5,
                        write_timeout: 5,
                        stop_gap: 10,
                    },
                    #[cfg(feature = "esplora-reqwest")]
                    esplora_opts: EsploraOpts {
                        server: "https://blockstream.info/testnet/api/".to_string(),
                        conc: 4,
                        stop_gap: 10,
                    },
                    #[cfg(feature = "compact_filters")]
                    compactfilter_opts: CompactFilterOpts{
                        address: vec!["127.0.0.1:18444".to_string()],
                        conn_count: 4,
                        skip_blocks: 0,
                    },
                    #[cfg(any(feature="compact_filters", feature="electrum", feature="esplora"))]
                    proxy_opts: ProxyOpts{
                        proxy: None,
                        proxy_auth: None,
                        retries: 5,
                    },
                    #[cfg(feature = "rpc")]
                    rpc_opts: RpcOpts {
                        address: "127.0.0.1:18443".to_string(),
                        auth: ("user".to_string(), "password".to_string()),
                        skip_blocks: None,
                    },
                },
                subcommand: WalletSubCommand::OfflineWalletSubCommand(GetNewAddress),
            },
        };

        assert_eq!(expected_cli_opts, cli_opts);
    }

    #[cfg(feature = "electrum")]
    #[test]
    fn test_parse_wallet_electrum() {
        let cli_args = vec!["bdk-cli", "--network", "testnet", "wallet",
                            "--proxy", "127.0.0.1:9150", "--retries", "3", "--timeout", "10",
                            "--descriptor", "wpkh(tpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/0/*)",
                            "--change_descriptor", "wpkh(tpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/1/*)",
                            "--server","ssl://electrum.blockstream.info:50002",
                            "--stop_gap", "20",
                            "get_new_address"];

        let cli_opts = CliOpts::from_iter(&cli_args);

        let expected_cli_opts = CliOpts {
            network: Network::Testnet,
            subcommand: CliSubCommand::Wallet {
                wallet_opts: WalletOpts {
                    wallet: "main".to_string(),
                    verbose: false,
                    descriptor: "wpkh(tpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/0/*)".to_string(),
                    change_descriptor: Some("wpkh(tpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/1/*)".to_string()),
                    electrum_opts: ElectrumOpts {
                        timeout: Some(10),
                        server: "ssl://electrum.blockstream.info:50002".to_string(),
                        stop_gap: 20
                    },
                    proxy_opts: ProxyOpts{
                        proxy: Some("127.0.0.1:9150".to_string()),
                        proxy_auth: None,
                        retries: 3,
                    },
                    #[cfg(feature = "rpc")]
                    rpc_opts: RpcOpts {
                        address: "127.0.0.1:18443".to_string(),
                        auth: ("user".to_string(), "password".to_string()),
                        skip_blocks: None,
                    }
                },
                subcommand: WalletSubCommand::OfflineWalletSubCommand(GetNewAddress),
            },
        };

        assert_eq!(expected_cli_opts, cli_opts);
    }

    #[cfg(feature = "esplora-ureq")]
    #[test]
    fn test_parse_wallet_esplora() {
        let cli_args = vec!["bdk-cli", "--network", "bitcoin", "wallet",
                            "--descriptor", "wpkh(xpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/0/*)",
                            "--change_descriptor", "wpkh(xpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/1/*)",
                            "--server", "https://blockstream.info/api/",
                            "--read_timeout", "10",
                            "--write_timeout", "10",
                            "--stop_gap", "20",
                            "get_new_address"];

        let cli_opts = CliOpts::from_iter(&cli_args);

        let expected_cli_opts = CliOpts {
            network: Network::Bitcoin,
            subcommand: CliSubCommand::Wallet {
                wallet_opts: WalletOpts {
                    wallet: "main".to_string(),
                    verbose: false,
                    descriptor: "wpkh(xpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/0/*)".to_string(),
                    change_descriptor: Some("wpkh(xpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/1/*)".to_string()),
                    esplora_opts: EsploraOpts {
                        server: "https://blockstream.info/api/".to_string(),
                        read_timeout: 10,
                        write_timeout: 10,
                        stop_gap: 20
                    },
                    proxy_opts: ProxyOpts{
                        proxy: None,
                        proxy_auth: None,
                        retries: 5,
                    }
                },
                subcommand: WalletSubCommand::OfflineWalletSubCommand(GetNewAddress),
            },
        };

        assert_eq!(expected_cli_opts, cli_opts);
    }

    #[cfg(feature = "esplora-reqwest")]
    #[test]
    fn test_parse_wallet_esplora() {
        let cli_args = vec!["bdk-cli", "--network", "bitcoin", "wallet",
                            "--descriptor", "wpkh(xpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/0/*)",
                            "--change_descriptor", "wpkh(xpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/1/*)",
                            "--server", "https://blockstream.info/api/",
                            "--conc", "10",
                            "--stop_gap", "20",
                            "get_new_address"];

        let cli_opts = CliOpts::from_iter(&cli_args);

        let expected_cli_opts = CliOpts {
            network: Network::Bitcoin,
            subcommand: CliSubCommand::Wallet {
                wallet_opts: WalletOpts {
                    wallet: "main".to_string(),
                    verbose: false,
                    descriptor: "wpkh(xpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/0/*)".to_string(),
                    change_descriptor: Some("wpkh(xpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/1/*)".to_string()),
                    esplora_opts: EsploraOpts {
                        server: "https://blockstream.info/api/".to_string(),
                        conc: 10,
                        stop_gap: 20
                    },
                    proxy_opts: ProxyOpts{
                        proxy: None,
                        proxy_auth: None,
                        retries: 5,
                    }
                },
                subcommand: WalletSubCommand::OfflineWalletSubCommand(GetNewAddress),
            },
        };

        assert_eq!(expected_cli_opts, cli_opts);
    }

    #[cfg(feature = "rpc")]
    #[test]
    fn test_parse_wallet_rpc() {
        let cli_args = vec!["bdk-cli", "--network", "bitcoin", "wallet",
                            "--descriptor", "wpkh(xpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/0/*)",
                            "--change_descriptor", "wpkh(xpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/1/*)",
                            "--node", "125.67.89.101:56678",
                            "--auth", "user:password",
                            "--skip-blocks", "5",
                            "get_new_address"];

        let cli_opts = CliOpts::from_iter(&cli_args);

        let expected_cli_opts = CliOpts {
            network: Network::Bitcoin,
            subcommand: CliSubCommand::Wallet {
                wallet_opts: WalletOpts {
                    wallet: "main".to_string(),
                    verbose: false,
                    descriptor: "wpkh(xpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/0/*)".to_string(),
                    change_descriptor: Some("wpkh(xpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/1/*)".to_string()),
                    #[cfg(feature = "electrum")]
                    electrum_opts: ElectrumOpts {
                        timeout: None,
                        server: "ssl://electrum.blockstream.info:60002".to_string(),
                    },
                    #[cfg(feature = "esplora")]
                    esplora_opts: EsploraOpts {
                        server: "https://blockstream.info/api/".to_string(),
                        concurrency: 5,
                    },
                    #[cfg(feature = "compact_filters")]
                    compactfilter_opts: CompactFilterOpts{
                        address: vec!["127.0.0.1:18444".to_string()],
                        skip_blocks: 0,
                        conn_count: 4,
                    },
                    #[cfg(any(feature="compact_filters", feature="electrum"))]
                    proxy_opts: ProxyOpts{
                        proxy: None,
                        proxy_auth: None,
                        retries: 5,
                    },
                    #[cfg(feature = "rpc")]
                    rpc_opts: RpcOpts {
                        address: "125.67.89.101:56678".to_string(),
                        auth: ("user".to_string(), "password".to_string()),
                        skip_blocks: Some(5),
                    },
                },
                subcommand: WalletSubCommand::OfflineWalletSubCommand(GetNewAddress),
            },
        };

        assert_eq!(expected_cli_opts, cli_opts);
    }

    #[cfg(feature = "compact_filters")]
    #[test]
    fn test_parse_wallet_compact_filters() {
        let cli_args = vec!["bdk-cli", "--network", "bitcoin", "wallet",
                            "--descriptor", "wpkh(xpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/0/*)",
                            "--change_descriptor", "wpkh(xpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/1/*)",
                            "--proxy", "127.0.0.1:9005",
                            "--proxy_auth", "random_user:random_passwd",
                            "--node", "127.0.0.1:18444", "127.2.3.1:19695",
                            "--conn_count", "4",
                            "--skip_blocks", "5",
                            "get_new_address"];

        let cli_opts = CliOpts::from_iter(&cli_args);

        let expected_cli_opts = CliOpts {
            network: Network::Bitcoin,
            subcommand: CliSubCommand::Wallet {
                wallet_opts: WalletOpts {
                    wallet: "main".to_string(),
                    verbose: false,
                    descriptor: "wpkh(xpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/0/*)".to_string(),
                    change_descriptor: Some("wpkh(xpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/1/*)".to_string()),
                    compactfilter_opts: CompactFilterOpts{
                        address: vec!["127.0.0.1:18444".to_string(), "127.2.3.1:19695".to_string()],
                        conn_count: 4,
                        skip_blocks: 5,
                    },
                    proxy_opts: ProxyOpts{
                        proxy: Some("127.0.0.1:9005".to_string()),
                        proxy_auth: Some(("random_user".to_string(), "random_passwd".to_string())),
                        retries: 5,
                    }
                },
                subcommand: WalletSubCommand::OfflineWalletSubCommand(GetNewAddress),
            },
        };

        assert_eq!(expected_cli_opts, cli_opts);
    }

    #[cfg(any(
        feature = "electrum",
        feature = "esplora",
        feature = "compact_filters",
        feature = "rpc"
    ))]
    #[test]
    fn test_parse_wallet_sync() {
        let cli_args = vec!["bdk-cli", "--network", "testnet", "wallet",
                            "--descriptor", "wpkh(tpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/0/*)",
                            "sync", "--max_addresses", "50"];

        let cli_opts = CliOpts::from_iter(&cli_args);

        let expected_cli_opts = CliOpts {
            network: Network::Testnet,
            subcommand: CliSubCommand::Wallet {
                wallet_opts: WalletOpts {
                    wallet: "main".to_string(),
                    verbose: false,
                    descriptor: "wpkh(tpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/0/*)".to_string(),
                    change_descriptor: None,
                    #[cfg(feature = "electrum")]
                    electrum_opts: ElectrumOpts {
                        timeout: None,
                        server: "ssl://electrum.blockstream.info:60002".to_string(),
                        stop_gap: 10,
                    },
                    #[cfg(feature = "esplora-ureq")]
                    esplora_opts: EsploraOpts {
                        server: "https://blockstream.info/testnet/api/".to_string(),
                        read_timeout: 5,
                        write_timeout: 5,
                        stop_gap: 10,
                    },
                    #[cfg(feature = "esplora-reqwest")]
                    esplora_opts: EsploraOpts {
                        server: "https://blockstream.info/testnet/api/".to_string(),
                        conc: 4,
                        stop_gap: 10,
                    },
                    #[cfg(feature = "compact_filters")]
                    compactfilter_opts: CompactFilterOpts{
                        address: vec!["127.0.0.1:18444".to_string()],
                        conn_count: 4,
                        skip_blocks: 0,
                    },
                    #[cfg(any(feature="compact_filters", feature="electrum", feature="esplora"))]
                    proxy_opts: ProxyOpts{
                        proxy: None,
                        proxy_auth: None,
                        retries: 5,
                    },
                    #[cfg(feature = "rpc")]
                    rpc_opts: RpcOpts {
                        address: "127.0.0.1:18443".to_string(),
                        auth: ("user".to_string(), "password".to_string()),
                        skip_blocks: None,
                    },
                },
                subcommand: WalletSubCommand::OnlineWalletSubCommand(Sync {
                    max_addresses: Some(50)
                }),
            },
        };

        assert_eq!(expected_cli_opts, cli_opts);
    }

    #[test]
    fn test_parse_wallet_create_tx() {
        let cli_args = vec!["bdk-cli", "--network", "testnet", "wallet",
                            "--descriptor", "wpkh(tpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/0/*)",
                            "--change_descriptor", "wpkh(tpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/1/*)",
                            "create_tx", "--to", "n2Z3YNXtceeJhFkTknVaNjT1mnCGWesykJ:123456","mjDZ34icH4V2k9GmC8niCrhzVuR3z8Mgkf:78910",
                            "--utxos","87345e46bfd702d24d54890cc094d08a005f773b27c8f965dfe0eb1e23eef88e:1",
                            "--utxos","87345e46bfd702d24d54890cc094d08a005f773b27c8f965dfe0eb1e23eef88e:2"];

        let cli_opts = CliOpts::from_iter(&cli_args);

        let script1 = Address::from_str("n2Z3YNXtceeJhFkTknVaNjT1mnCGWesykJ")
            .unwrap()
            .script_pubkey();
        let script2 = Address::from_str("mjDZ34icH4V2k9GmC8niCrhzVuR3z8Mgkf")
            .unwrap()
            .script_pubkey();
        let outpoint1 = OutPoint::from_str(
            "87345e46bfd702d24d54890cc094d08a005f773b27c8f965dfe0eb1e23eef88e:1",
        )
        .unwrap();
        let outpoint2 = OutPoint::from_str(
            "87345e46bfd702d24d54890cc094d08a005f773b27c8f965dfe0eb1e23eef88e:2",
        )
        .unwrap();

        let expected_cli_opts = CliOpts {
            network: Network::Testnet,
            subcommand: CliSubCommand::Wallet {
                wallet_opts: WalletOpts {
                    wallet: "main".to_string(),
                    verbose: false,
                    descriptor: "wpkh(tpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/0/*)".to_string(),
                    change_descriptor: Some("wpkh(tpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/1/*)".to_string()),
                    #[cfg(feature = "electrum")]
                    electrum_opts: ElectrumOpts {
                        timeout: None,
                        server: "ssl://electrum.blockstream.info:60002".to_string(),
                        stop_gap: 10,
                    },
                    #[cfg(feature = "esplora-ureq")]
                    esplora_opts: EsploraOpts {
                        server: "https://blockstream.info/testnet/api/".to_string(),
                        read_timeout: 5,
                        write_timeout: 5,
                        stop_gap: 10,
                    },
                    #[cfg(feature = "esplora-reqwest")]
                    esplora_opts: EsploraOpts {
                        server: "https://blockstream.info/testnet/api/".to_string(),
                        conc: 4,
                        stop_gap: 10,
                    },
                    #[cfg(feature = "compact_filters")]
                    compactfilter_opts: CompactFilterOpts{
                        address: vec!["127.0.0.1:18444".to_string()],
                        conn_count: 4,
                        skip_blocks: 0,
                    },
                    #[cfg(any(feature="compact_filters", feature="electrum", feature="esplora"))]
                    proxy_opts: ProxyOpts{
                        proxy: None,
                        proxy_auth: None,
                        retries: 5,
                    },
                    #[cfg(feature = "rpc")]
                    rpc_opts: RpcOpts {
                        address: "127.0.0.1:18443".to_string(),
                        auth: ("user".to_string(), "password".to_string()),
                        skip_blocks: None,
                    },
                },
                subcommand: WalletSubCommand::OfflineWalletSubCommand(CreateTx {
                    recipients: vec![(script1, 123456), (script2, 78910)],
                    send_all: false,
                    enable_rbf: false,
                    offline_signer: false,
                    utxos: Some(vec!(outpoint1, outpoint2)),
                    unspendable: None,
                    fee_rate: None,
                    external_policy: None,
                    internal_policy: None,
                }),
            },
        };

        assert_eq!(expected_cli_opts, cli_opts);
    }

    #[cfg(any(
        feature = "electrum",
        feature = "esplora",
        feature = "compact_filters",
        feature = "rpc"
    ))]
    #[test]
    fn test_parse_wallet_broadcast() {
        let cli_args = vec!["bdk-cli", "--network", "testnet", "wallet",
                            "--descriptor", "wpkh(tpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/0/*)",
                            "broadcast",
                            "--psbt", "cHNidP8BAEICAAAAASWhGE1AhvtO+2GjJHopssFmgfbq+WweHd8zN/DeaqmDAAAAAAD/////AQAAAAAAAAAABmoEAAECAwAAAAAAAAA="];

        let cli_opts = CliOpts::from_iter(&cli_args);

        let expected_cli_opts = CliOpts {
            network: Network::Testnet,
            subcommand: CliSubCommand::Wallet {
                wallet_opts: WalletOpts {
                    wallet: "main".to_string(),
                    verbose: false,
                    descriptor: "wpkh(tpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/0/*)".to_string(),
                    change_descriptor: None,
                    #[cfg(feature = "electrum")]
                    electrum_opts: ElectrumOpts {
                        timeout: None,
                        server: "ssl://electrum.blockstream.info:60002".to_string(),
                        stop_gap: 10,
                    },
                    #[cfg(feature = "esplora-ureq")]
                    esplora_opts: EsploraOpts {
                        server: "https://blockstream.info/testnet/api/".to_string(),
                        read_timeout: 5,
                        write_timeout: 5,
                        stop_gap: 10,
                    },
                    #[cfg(feature = "esplora-reqwest")]
                    esplora_opts: EsploraOpts {
                        server: "https://blockstream.info/testnet/api/".to_string(),
                        conc: 4,
                        stop_gap: 10,
                    },
                    #[cfg(feature = "compact_filters")]
                    compactfilter_opts: CompactFilterOpts{
                        address: vec!["127.0.0.1:18444".to_string()],
                        conn_count: 4,
                        skip_blocks: 0,
                    },
                    #[cfg(any(feature="compact_filters", feature="electrum", feature="esplora"))]
                    proxy_opts: ProxyOpts{
                        proxy: None,
                        proxy_auth: None,
                        retries: 5,
                    },
                    #[cfg(feature = "rpc")]
                    rpc_opts: RpcOpts {
                        address: "127.0.0.1:18443".to_string(),
                        auth: ("user".to_string(), "password".to_string()),
                        skip_blocks: None,
                    },
                },
                subcommand: WalletSubCommand::OnlineWalletSubCommand(Broadcast {
                    psbt: Some("cHNidP8BAEICAAAAASWhGE1AhvtO+2GjJHopssFmgfbq+WweHd8zN/DeaqmDAAAAAAD/////AQAAAAAAAAAABmoEAAECAwAAAAAAAAA=".to_string()),
                    tx: None
                }),
            },
        };

        assert_eq!(expected_cli_opts, cli_opts);
    }

    #[test]
    fn test_parse_wrong_network() {
        let cli_args = vec!["repl", "--network", "badnet", "wallet",
                            "--descriptor", "wpkh(tpubDEnoLuPdBep9bzw5LoGYpsxUQYheRQ9gcgrJhJEcdKFB9cWQRyYmkCyRoTqeD4tJYiVVgt6A3rN6rWn9RYhR9sBsGxji29LYWHuKKbdb1ev/0/*)",
                            "sync", "--max_addresses", "50"];

        let cli_opts = CliOpts::from_iter_safe(&cli_args);
        assert!(cli_opts.is_err());
    }

    #[test]
    fn test_key_generate() {
        let network = Testnet;
        let key_generate_cmd = KeySubCommand::Generate {
            word_count: 12,
            password: Some("test123".to_string()),
        };

        let result = handle_key_subcommand(network, key_generate_cmd).unwrap();
        let result_obj = result.as_object().unwrap();

        let mnemonic = result_obj.get("mnemonic").unwrap().as_str().unwrap();
        let mnemonic: Vec<&str> = mnemonic.split(' ').collect();
        let xprv = result_obj.get("xprv").unwrap().as_str().unwrap();

        assert_eq!(mnemonic.len(), 12);
        assert_eq!(&xprv[0..4], "tprv");
    }

    #[test]
    fn test_key_restore() {
        let network = Testnet;
        let key_generate_cmd = KeySubCommand::Restore {
            mnemonic: "payment battle unit sword token broccoli era violin purse trip blood hire"
                .to_string(),
            password: Some("test123".to_string()),
        };

        let result = handle_key_subcommand(network, key_generate_cmd).unwrap();
        let result_obj = result.as_object().unwrap();

        let fingerprint = result_obj.get("fingerprint").unwrap().as_str().unwrap();
        let xprv = result_obj.get("xprv").unwrap().as_str().unwrap();

        assert_eq!(&fingerprint, &"828af366");
        assert_eq!(&xprv, &"tprv8ZgxMBicQKsPd18TeiFknZKqaZFwpdX9tvvKh8eeHSSPBQi5g9xPHztBg411o78G8XkrhQb6Q1cVvBJ1a9xuFHpmWgvQsvkJkNxBjfGoqhK");
    }

    #[test]
    fn test_key_derive() {
        let network = Testnet;
        let key_generate_cmd = KeySubCommand::Derive {
            xprv: ExtendedPrivKey::from_str("tprv8ZgxMBicQKsPfQjJy8ge2cvBfDjLxJSkvNLVQiw7BQ5gTjKadG2rrcQB5zjcdaaUTz5EDNJaS77q4DzjqjogQBfMsaXFFNP3UqoBnwt2kyT").unwrap(),
            path: DerivationPath::from_str("m/84'/1'/0'/0").unwrap(),
        };

        let result = handle_key_subcommand(network, key_generate_cmd).unwrap();
        let result_obj = result.as_object().unwrap();

        let xpub = result_obj.get("xpub").unwrap().as_str().unwrap();
        let xprv = result_obj.get("xprv").unwrap().as_str().unwrap();

        assert_eq!(&xpub, &"[566844c5/84'/1'/0'/0]tpubDFeqiDkfwR1tAhPxsXSZMfEmfpDhwhLyhLKZgmeBvuBkZQusoWeL62oGg2oTNGcENeKdwuGepAB85eMvyLemabYe9PSqv6cr5mFXktHc3Ka/*");
        assert_eq!(&xprv, &"[566844c5/84'/1'/0'/0]tprv8ixoZoiRo3LDHENAysmxxFaf6nhmnNA582inQFbtWdPMivf7B7pjuYBQVuLC5bkM7tJZEDbfoivENsGZPBnQg1n52Kuc1P8X2Ei3XJuJX7c/*");
    }

    #[cfg(feature = "compiler")]
    #[test]
    fn test_parse_compile() {
        let cli_args = vec![
            "bdk-cli",
            "compile",
            "thresh(3,pk(Alice),pk(Bob),pk(Carol),older(2))",
            "--type",
            "sh-wsh",
        ];

        let cli_opts = CliOpts::from_iter(&cli_args);

        let expected_cli_opts = CliOpts {
            network: Network::Testnet,
            subcommand: CliSubCommand::Compile {
                policy: "thresh(3,pk(Alice),pk(Bob),pk(Carol),older(2))".to_string(),
                script_type: "sh-wsh".to_string(),
            },
        };

        assert_eq!(expected_cli_opts, cli_opts);
    }

    #[cfg(feature = "compiler")]
    #[test]
    fn test_compile() {
        let result = handle_compile_subcommand(
            Network::Testnet,
            "thresh(3,pk(Alice),pk(Bob),pk(Carol),older(2))".to_string(),
            "sh-wsh".to_string(),
        )
        .unwrap();
        let result_obj = result.as_object().unwrap();

        let descriptor = result_obj.get("descriptor").unwrap().as_str().unwrap();
        assert_eq!(
            &descriptor,
            &"sh(wsh(thresh(3,pk(Alice),s:pk(Bob),s:pk(Carol),sdv:older(2))))#l4qaawgv"
        );
    }
}