bitcoind-async-client 0.12.0

BitcoinD JSON-RPC Async Client
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
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
//! This module contains the implementation of the [`Client`] for Bitcoin Core v29.

use std::env::var;

use bitcoin::{
    bip32::Xpriv,
    block::Header,
    consensus::{self, encode::serialize_hex},
    Address, Block, BlockHash, Network, Transaction, Txid,
};
use corepc_types::model;
use corepc_types::v29::{
    CreateWallet, GetAddressInfo, GetBlockHeader, GetBlockVerboseOne, GetBlockVerboseZero,
    GetBlockchainInfo, GetMempoolInfo, GetNewAddress, GetRawMempool, GetRawMempoolVerbose,
    GetRawTransaction, GetRawTransactionVerbose, GetTransaction, GetTxOut, ImportDescriptors,
    ListDescriptors, ListTransactions, ListUnspent, PsbtBumpFee, SignRawTransactionWithWallet,
    SubmitPackage, TestMempoolAccept, WalletCreateFundedPsbt, WalletProcessPsbt,
};
use serde_json::value::{RawValue, Value};
use tracing::*;

use crate::{
    client::Client,
    error::ClientError,
    to_value,
    traits::{Broadcaster, Reader, Signer, Wallet},
    types::{
        CreateRawTransactionArguments, CreateRawTransactionInput, CreateRawTransactionOutput,
        CreateWalletArguments, ImportDescriptorInput, ListUnspentQueryOptions,
        PreviousTransactionOutput, PsbtBumpFeeOptions, SighashType, WalletCreateFundedPsbtOptions,
    },
    ClientResult,
};

/// Minimum relay fee rate: 1 sat/vB = 0.00001 BTC/kvB
const MIN_FEE_RATE_BTC_VKB: f64 = 0.00001;

impl Reader for Client {
    async fn estimate_smart_fee(&self, conf_target: u16) -> ClientResult<u64> {
        let result = self
            .call::<Box<RawValue>>("estimatesmartfee", &[to_value(conf_target)?])
            .await?
            .to_string();

        let result_map: Value = result.parse::<Value>()?;

        let btc_vkb = result_map
            .get("feerate")
            .and_then(|v| v.as_f64())
            .unwrap_or(MIN_FEE_RATE_BTC_VKB); // Default to minimum if missing or invalid

        // Ensure fee rate is positive and non-zero
        if btc_vkb <= 0.0 {
            return Err(ClientError::Other(
                "Invalid fee rate: must be positive".to_string(),
            ));
        }

        // Convert BTC/vB to sat/vB
        let sat_vb = (btc_vkb * 100_000_000.0 / 1_000.0) as u64;

        Ok(sat_vb)
    }

    async fn get_block_header(&self, hash: &BlockHash) -> ClientResult<Header> {
        let get_block_header = self
            .call::<GetBlockHeader>(
                "getblockheader",
                &[to_value(hash.to_string())?, to_value(false)?],
            )
            .await?;
        let header = get_block_header
            .block_header()
            .map_err(|err| ClientError::Other(format!("header decode: {err}")))?;
        Ok(header)
    }

    async fn get_block(&self, hash: &BlockHash) -> ClientResult<Block> {
        let get_block = self
            .call::<GetBlockVerboseZero>("getblock", &[to_value(hash.to_string())?, to_value(0)?])
            .await?;
        let block = get_block
            .into_model()
            .map_err(|e| ClientError::Parse(e.to_string()))?
            .0;
        Ok(block)
    }

    async fn get_block_height(&self, hash: &BlockHash) -> ClientResult<u64> {
        let block_verobose = self
            .call::<GetBlockVerboseOne>("getblock", &[to_value(hash.to_string())?])
            .await?;

        let block_height = block_verobose.height as u64;
        Ok(block_height)
    }

    async fn get_block_header_at(&self, height: u64) -> ClientResult<Header> {
        let hash = self.get_block_hash(height).await?;
        self.get_block_header(&hash).await
    }

    async fn get_block_at(&self, height: u64) -> ClientResult<Block> {
        let hash = self.get_block_hash(height).await?;
        self.get_block(&hash).await
    }

    async fn get_block_count(&self) -> ClientResult<u64> {
        self.call::<u64>("getblockcount", &[]).await
    }

    async fn get_block_hash(&self, height: u64) -> ClientResult<BlockHash> {
        self.call::<BlockHash>("getblockhash", &[to_value(height)?])
            .await
    }

    async fn get_blockchain_info(&self) -> ClientResult<model::GetBlockchainInfo> {
        let res = self
            .call::<GetBlockchainInfo>("getblockchaininfo", &[])
            .await?;
        res.into_model()
            .map_err(|e| ClientError::Parse(e.to_string()))
    }

    async fn get_current_timestamp(&self) -> ClientResult<u32> {
        let best_block_hash = self.call::<BlockHash>("getbestblockhash", &[]).await?;
        let block = self.get_block(&best_block_hash).await?;
        Ok(block.header.time)
    }

    async fn get_raw_mempool(&self) -> ClientResult<model::GetRawMempool> {
        let resp = self.call::<GetRawMempool>("getrawmempool", &[]).await?;
        resp.into_model()
            .map_err(|e| ClientError::Parse(e.to_string()))
    }

    async fn get_raw_mempool_verbose(&self) -> ClientResult<model::GetRawMempoolVerbose> {
        let resp = self
            .call::<GetRawMempoolVerbose>("getrawmempool", &[to_value(true)?])
            .await?;

        resp.into_model()
            .map_err(|e| ClientError::Parse(e.to_string()))
    }

    async fn get_mempool_info(&self) -> ClientResult<model::GetMempoolInfo> {
        let resp = self.call::<GetMempoolInfo>("getmempoolinfo", &[]).await?;
        resp.into_model()
            .map_err(|e| ClientError::Parse(e.to_string()))
    }

    async fn get_raw_transaction_verbosity_zero(
        &self,
        txid: &Txid,
    ) -> ClientResult<model::GetRawTransaction> {
        let resp = self
            .call::<GetRawTransaction>(
                "getrawtransaction",
                &[to_value(txid.to_string())?, to_value(0)?],
            )
            .await?;
        resp.into_model()
            .map_err(|e| ClientError::Parse(e.to_string()))
    }

    async fn get_raw_transaction_verbosity_one(
        &self,
        txid: &Txid,
    ) -> ClientResult<model::GetRawTransactionVerbose> {
        let resp = self
            .call::<GetRawTransactionVerbose>(
                "getrawtransaction",
                &[to_value(txid.to_string())?, to_value(1)?],
            )
            .await?;
        resp.into_model()
            .map_err(|e| ClientError::Parse(e.to_string()))
    }

    async fn get_tx_out(
        &self,
        txid: &Txid,
        vout: u32,
        include_mempool: bool,
    ) -> ClientResult<model::GetTxOut> {
        let resp = self
            .call::<GetTxOut>(
                "gettxout",
                &[
                    to_value(txid.to_string())?,
                    to_value(vout)?,
                    to_value(include_mempool)?,
                ],
            )
            .await?;
        resp.into_model()
            .map_err(|e| ClientError::Parse(e.to_string()))
    }

    async fn network(&self) -> ClientResult<Network> {
        let chain = self
            .call::<GetBlockchainInfo>("getblockchaininfo", &[])
            .await?
            .chain;
        Network::from_core_arg(&chain).map_err(|e| ClientError::Parse(e.to_string()))
    }
}

impl Broadcaster for Client {
    async fn send_raw_transaction(&self, tx: &Transaction) -> ClientResult<Txid> {
        let txstr = serialize_hex(tx);
        trace!(txstr = %txstr, "Sending raw transaction");
        match self
            .call::<Txid>("sendrawtransaction", &[to_value(txstr)?])
            .await
        {
            Ok(txid) => {
                trace!(?txid, "Transaction sent");
                Ok(txid)
            }
            Err(err @ ClientError::Server(_, _)) if err.is_rpc_verify_already_in_utxo_set() => {
                Ok(tx.compute_txid())
            }
            Err(err @ ClientError::Server(_, _)) => Err(err),
            Err(e) => Err(ClientError::Other(e.to_string())),
        }
    }

    async fn test_mempool_accept(
        &self,
        tx: &Transaction,
    ) -> ClientResult<model::TestMempoolAccept> {
        let txstr = serialize_hex(tx);
        trace!(%txstr, "Testing mempool accept");
        let resp = self
            .call::<TestMempoolAccept>("testmempoolaccept", &[to_value([txstr])?])
            .await?;
        resp.into_model()
            .map_err(|e| ClientError::Parse(e.to_string()))
    }

    async fn submit_package(&self, txs: &[Transaction]) -> ClientResult<model::SubmitPackage> {
        let txstrs: Vec<String> = txs.iter().map(serialize_hex).collect();
        let resp = self
            .call::<SubmitPackage>("submitpackage", &[to_value(txstrs)?])
            .await?;
        trace!(?resp, "Got submit package response");

        resp.into_model()
            .map_err(|e| ClientError::Parse(e.to_string()))
    }
}

impl Wallet for Client {
    async fn get_new_address(&self) -> ClientResult<Address> {
        let address_unchecked = self
            .call::<GetNewAddress>("getnewaddress", &[])
            .await?
            .0
            .parse::<Address<_>>()
            .map_err(|e| ClientError::Parse(e.to_string()))?
            .assume_checked();
        Ok(address_unchecked)
    }
    async fn get_transaction(&self, txid: &Txid) -> ClientResult<model::GetTransaction> {
        let resp = self
            .call::<GetTransaction>("gettransaction", &[to_value(txid.to_string())?])
            .await?;
        resp.into_model()
            .map_err(|e| ClientError::Parse(e.to_string()))
    }

    async fn list_transactions(
        &self,
        count: Option<usize>,
    ) -> ClientResult<model::ListTransactions> {
        let resp = self
            .call::<ListTransactions>("listtransactions", &[to_value(count)?])
            .await?;
        resp.into_model()
            .map_err(|e| ClientError::Parse(e.to_string()))
    }

    async fn list_wallets(&self) -> ClientResult<Vec<String>> {
        self.call::<Vec<String>>("listwallets", &[]).await
    }

    async fn create_raw_transaction(
        &self,
        raw_tx: CreateRawTransactionArguments,
    ) -> ClientResult<Transaction> {
        let raw_tx = self
            .call::<String>(
                "createrawtransaction",
                &[to_value(raw_tx.inputs)?, to_value(raw_tx.outputs)?],
            )
            .await?;
        trace!(%raw_tx, "Created raw transaction");
        consensus::encode::deserialize_hex(&raw_tx)
            .map_err(|e| ClientError::Other(format!("Failed to deserialize raw transaction: {e}")))
    }

    async fn wallet_create_funded_psbt(
        &self,
        inputs: &[CreateRawTransactionInput],
        outputs: &[CreateRawTransactionOutput],
        locktime: Option<u32>,
        options: Option<WalletCreateFundedPsbtOptions>,
        bip32_derivs: Option<bool>,
    ) -> ClientResult<model::WalletCreateFundedPsbt> {
        let resp = self
            .call::<WalletCreateFundedPsbt>(
                "walletcreatefundedpsbt",
                &[
                    to_value(inputs)?,
                    to_value(outputs)?,
                    to_value(locktime.unwrap_or(0))?,
                    to_value(options.unwrap_or_default())?,
                    to_value(bip32_derivs)?,
                ],
            )
            .await?;
        resp.into_model()
            .map_err(|e| ClientError::Parse(e.to_string()))
    }

    async fn get_address_info(&self, address: &Address) -> ClientResult<model::GetAddressInfo> {
        trace!(address = %address, "Getting address info");
        let resp = self
            .call::<GetAddressInfo>("getaddressinfo", &[to_value(address.to_string())?])
            .await?;
        resp.into_model()
            .map_err(|e| ClientError::Parse(e.to_string()))
    }

    async fn list_unspent(
        &self,
        min_conf: Option<u32>,
        max_conf: Option<u32>,
        addresses: Option<&[Address]>,
        include_unsafe: Option<bool>,
        query_options: Option<ListUnspentQueryOptions>,
    ) -> ClientResult<model::ListUnspent> {
        let addr_strings: Vec<String> = addresses
            .map(|addrs| addrs.iter().map(|a| a.to_string()).collect())
            .unwrap_or_default();

        let mut params = vec![
            to_value(min_conf.unwrap_or(1))?,
            to_value(max_conf.unwrap_or(9_999_999))?,
            to_value(addr_strings)?,
            to_value(include_unsafe.unwrap_or(true))?,
        ];

        if let Some(query_options) = query_options {
            params.push(to_value(query_options)?);
        }

        let resp = self.call::<ListUnspent>("listunspent", &params).await?;
        trace!(?resp, "Got UTXOs");

        resp.into_model()
            .map_err(|e| ClientError::Parse(e.to_string()))
    }
}

impl Signer for Client {
    async fn sign_raw_transaction_with_wallet(
        &self,
        tx: &Transaction,
        prev_outputs: Option<Vec<PreviousTransactionOutput>>,
    ) -> ClientResult<model::SignRawTransactionWithWallet> {
        let tx_hex = serialize_hex(tx);
        trace!(tx_hex = %tx_hex, "Signing transaction");
        trace!(?prev_outputs, "Signing transaction with previous outputs");
        let resp = self
            .call::<SignRawTransactionWithWallet>(
                "signrawtransactionwithwallet",
                &[to_value(tx_hex)?, to_value(prev_outputs)?],
            )
            .await?;
        resp.into_model()
            .map_err(|e| ClientError::Parse(e.to_string()))
    }

    async fn get_xpriv(&self) -> ClientResult<Option<Xpriv>> {
        // If the ENV variable `BITCOIN_XPRIV_RETRIEVABLE` is not set, we return `None`
        if var("BITCOIN_XPRIV_RETRIEVABLE").is_err() {
            return Ok(None);
        }

        let descriptors = self
            .call::<ListDescriptors>("listdescriptors", &[to_value(true)?]) // true is the xpriv, false is the xpub
            .await?
            .descriptors;
        if descriptors.is_empty() {
            return Err(ClientError::Other("No descriptors found".to_string()));
        }

        // We are only interested in the one that contains `tr(`
        let descriptor = descriptors
            .iter()
            .find(|d| d.descriptor.contains("tr("))
            .map(|d| d.descriptor.clone())
            .ok_or(ClientError::Xpriv)?;

        // Now we extract the xpriv from the `tr()` up to the first `/`
        let xpriv_str = descriptor
            .split("tr(")
            .nth(1)
            .ok_or(ClientError::Xpriv)?
            .split("/")
            .next()
            .ok_or(ClientError::Xpriv)?;

        let xpriv = xpriv_str.parse::<Xpriv>().map_err(|_| ClientError::Xpriv)?;
        Ok(Some(xpriv))
    }

    async fn import_descriptors(
        &self,
        descriptors: Vec<ImportDescriptorInput>,
        wallet_name: String,
    ) -> ClientResult<ImportDescriptors> {
        let wallet_args = CreateWalletArguments {
            name: wallet_name,
            load_on_startup: Some(true),
        };

        // TODO: this should check for -35 error code which is good,
        //       means that is already created
        let _wallet_create = self
            .call::<CreateWallet>("createwallet", &[to_value(wallet_args.clone())?])
            .await;
        // TODO: this should check for -35 error code which is good, -18 is bad.
        let _wallet_load = self
            .call::<CreateWallet>("loadwallet", &[to_value(wallet_args)?])
            .await;

        let result = self
            .call::<ImportDescriptors>("importdescriptors", &[to_value(descriptors)?])
            .await?;
        Ok(result)
    }

    async fn wallet_process_psbt(
        &self,
        psbt: &str,
        sign: Option<bool>,
        sighashtype: Option<SighashType>,
        bip32_derivs: Option<bool>,
    ) -> ClientResult<model::WalletProcessPsbt> {
        let mut params = vec![to_value(psbt)?, to_value(sign.unwrap_or(true))?];

        if let Some(sighashtype) = sighashtype {
            params.push(to_value(sighashtype)?);
        }

        if let Some(bip32_derivs) = bip32_derivs {
            params.push(to_value(bip32_derivs)?);
        }

        let resp = self
            .call::<WalletProcessPsbt>("walletprocesspsbt", &params)
            .await?;
        resp.into_model()
            .map_err(|e| ClientError::Parse(e.to_string()))
    }

    async fn psbt_bump_fee(
        &self,
        txid: &Txid,
        options: Option<PsbtBumpFeeOptions>,
    ) -> ClientResult<model::PsbtBumpFee> {
        let mut params = vec![to_value(txid.to_string())?];

        if let Some(options) = options {
            params.push(to_value(options)?);
        }

        let resp = self.call::<PsbtBumpFee>("psbtbumpfee", &params).await?;
        resp.into_model()
            .map_err(|e| ClientError::Parse(e.to_string()))
    }
}

#[cfg(test)]
mod test {

    use std::sync::Once;

    use bitcoin::{hashes::Hash, transaction, Amount, FeeRate, NetworkKind};
    use corepc_types::v29::ImportDescriptorsResult;
    use tracing_subscriber::{fmt, layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};

    use super::*;
    use crate::{
        test_utils::corepc_node_helpers::{get_bitcoind_and_client, mine_blocks},
        types::{CreateRawTransactionInput, CreateRawTransactionOutput},
        Auth,
    };

    /// 50 BTC in [`Network::Regtest`].
    const COINBASE_AMOUNT: Amount = Amount::from_sat(50 * 100_000_000);

    /// Only attempts to start tracing once.
    fn init_tracing() {
        static INIT: Once = Once::new();

        INIT.call_once(|| {
            tracing_subscriber::registry()
                .with(fmt::layer())
                .with(EnvFilter::from_default_env())
                .try_init()
                .ok();
        });
    }

    #[tokio::test()]
    async fn client_works() {
        init_tracing();

        let (bitcoind, client) = get_bitcoind_and_client();

        // network
        let got = client.network().await.unwrap();
        let expected = Network::Regtest;

        assert_eq!(expected, got);
        // get_blockchain_info
        let get_blockchain_info = client.get_blockchain_info().await.unwrap();
        assert_eq!(get_blockchain_info.blocks, 0);

        // get_current_timestamp
        let _ = client
            .get_current_timestamp()
            .await
            .expect("must be able to get current timestamp");

        let blocks = mine_blocks(&bitcoind, 101, None).unwrap();

        // get_block
        let expected = blocks.last().unwrap();
        let got = client.get_block(expected).await.unwrap().block_hash();
        assert_eq!(*expected, got);

        // get_block_at
        let target_height = blocks.len() as u64;
        let expected = blocks.last().unwrap();
        let got = client
            .get_block_at(target_height)
            .await
            .unwrap()
            .block_hash();
        assert_eq!(*expected, got);

        // get_block_count
        let expected = blocks.len() as u64;
        let got = client.get_block_count().await.unwrap();
        assert_eq!(expected, got);

        // get_block_hash
        let target_height = blocks.len() as u64;
        let expected = blocks.last().unwrap();
        let got = client.get_block_hash(target_height).await.unwrap();
        assert_eq!(*expected, got);

        // get_block_header_at
        let target_height = blocks.len() as u64;
        let expected = blocks.last().unwrap();
        let got = client.get_block_header_at(target_height).await.unwrap();
        assert_eq!(*expected, got.block_hash());

        // get_new_address
        let address = client.get_new_address().await.unwrap();
        let txid = client
            .call::<String>(
                "sendtoaddress",
                &[to_value(address.to_string()).unwrap(), to_value(1).unwrap()],
            )
            .await
            .unwrap()
            .parse::<Txid>()
            .unwrap();

        // get_transaction
        let tx = client.get_transaction(&txid).await.unwrap().tx;
        let got = client.send_raw_transaction(&tx).await.unwrap();
        let expected = txid; // Don't touch this!
        assert_eq!(expected, got);

        // get_raw_transaction_verbosity_zero
        let got = client
            .get_raw_transaction_verbosity_zero(&txid)
            .await
            .unwrap()
            .0
            .compute_txid();
        assert_eq!(expected, got);

        // get_raw_transaction_verbosity_one
        let got = client
            .get_raw_transaction_verbosity_one(&txid)
            .await
            .unwrap()
            .transaction
            .compute_txid();
        assert_eq!(expected, got);

        // get_raw_mempool
        let got = client.get_raw_mempool().await.unwrap();
        let expected = vec![txid];
        assert_eq!(expected, got.0);

        // get_raw_mempool_verbose
        let got = client.get_raw_mempool_verbose().await.unwrap();
        assert_eq!(got.0.len(), 1);
        assert_eq!(got.0.get(&txid).unwrap().height, 101);

        // get_mempool_info
        let got = client.get_mempool_info().await.unwrap();
        assert!(got.loaded.unwrap_or(false));
        assert_eq!(got.size, 1);
        assert_eq!(got.unbroadcast_count, Some(1));

        // estimate_smart_fee
        let got = client.estimate_smart_fee(1).await.unwrap();
        let expected = 1; // 1 sat/vB
        assert_eq!(expected, got);

        // sign_raw_transaction_with_wallet
        let got = client
            .sign_raw_transaction_with_wallet(&tx, None)
            .await
            .unwrap();
        assert!(got.complete);
        assert!(got.errors.is_empty());

        // test_mempool_accept
        let txids = client
            .test_mempool_accept(&tx)
            .await
            .expect("must be able to test mempool accept");
        let got = txids
            .results
            .first()
            .expect("there must be at least one txid");
        assert_eq!(
            got.txid,
            tx.compute_txid(),
            "txids must match in the mempool"
        );

        // send_raw_transaction
        let got = client.send_raw_transaction(&tx).await.unwrap();
        assert!(got.as_byte_array().len() == 32);

        // list_transactions
        let got = client.list_transactions(None).await.unwrap();
        assert_eq!(got.0.len(), 10);

        // list_unspent
        // let's mine one more block
        mine_blocks(&bitcoind, 1, None).unwrap();
        let got = client
            .list_unspent(None, None, None, None, None)
            .await
            .unwrap();
        assert_eq!(got.0.len(), 3);

        // listdescriptors
        let got = client.get_xpriv().await.unwrap().unwrap().network;
        let expected = NetworkKind::Test;
        assert_eq!(expected, got);

        // importdescriptors
        // taken from https://github.com/rust-bitcoin/rust-bitcoin/blob/bb38aeb786f408247d5bbc88b9fa13616c74c009/bitcoin/examples/taproot-psbt.rs#L18C38-L18C149
        let descriptor_string = "tr([e61b318f/20000'/20']tprv8ZgxMBicQKsPd4arFr7sKjSnKFDVMR2JHw9Y8L9nXN4kiok4u28LpHijEudH3mMYoL4pM5UL9Bgdz2M4Cy8EzfErmU9m86ZTw6hCzvFeTg7/101/*)#2plamwqs".to_owned();
        let timestamp = "now".to_owned();
        let list_descriptors = vec![ImportDescriptorInput {
            desc: descriptor_string,
            active: Some(true),
            timestamp,
        }];
        let got = client
            .import_descriptors(list_descriptors, "strata".to_owned())
            .await
            .unwrap()
            .0;
        let expected = vec![ImportDescriptorsResult {
            success: true,
            warnings: Some(vec![
                "Range not given, using default keypool range".to_string()
            ]),
            error: None,
        }];
        assert_eq!(expected, got);

        let psbt_address = client.get_new_address().await.unwrap();
        let psbt_outputs = vec![CreateRawTransactionOutput::AddressAmount {
            address: psbt_address.to_string(),
            amount: 1.0,
        }];

        let funded_psbt = client
            .wallet_create_funded_psbt(&[], &psbt_outputs, None, None, None)
            .await
            .unwrap();
        assert!(!funded_psbt.psbt.inputs.is_empty());
        assert!(funded_psbt.fee.to_sat() > 0);

        let processed_psbt = client
            .wallet_process_psbt(&funded_psbt.psbt.to_string(), None, None, None)
            .await
            .unwrap();
        assert!(!processed_psbt.psbt.inputs.is_empty());
        assert!(processed_psbt.complete);

        let finalized_psbt = client
            .wallet_process_psbt(&funded_psbt.psbt.to_string(), Some(true), None, None)
            .await
            .unwrap();
        assert!(finalized_psbt.complete);
        assert!(finalized_psbt.hex.is_some());
        let signed_tx = finalized_psbt.hex.as_ref().unwrap();
        let signed_txid = signed_tx.compute_txid();
        let got = client
            .test_mempool_accept(signed_tx)
            .await
            .unwrap()
            .results
            .first()
            .unwrap()
            .txid;
        assert_eq!(signed_txid, got);

        let info_address = client.get_new_address().await.unwrap();
        let address_info = client.get_address_info(&info_address).await.unwrap();
        assert_eq!(address_info.address, info_address.as_unchecked().clone());
        assert!(address_info.is_mine);
        assert!(address_info.solvable.unwrap_or(false));

        let unspent_address = client.get_new_address().await.unwrap();
        let unspent_txid = client
            .call::<String>(
                "sendtoaddress",
                &[
                    to_value(unspent_address.to_string()).unwrap(),
                    to_value(1.0).unwrap(),
                ],
            )
            .await
            .unwrap();
        mine_blocks(&bitcoind, 1, None).unwrap();

        let utxos = client
            .list_unspent(Some(1), Some(9_999_999), None, Some(true), None)
            .await
            .unwrap();
        assert!(!utxos.0.is_empty());

        let utxos_filtered = client
            .list_unspent(
                Some(1),
                Some(9_999_999),
                Some(std::slice::from_ref(&unspent_address)),
                Some(true),
                None,
            )
            .await
            .unwrap();
        assert!(!utxos_filtered.0.is_empty());
        let found_utxo = utxos_filtered.0.iter().any(|utxo| {
            utxo.txid.to_string() == unspent_txid
                && utxo.address.clone().assume_checked().to_string() == unspent_address.to_string()
        });
        assert!(found_utxo);

        let query_options = ListUnspentQueryOptions {
            minimum_amount: Some(Amount::from_btc(0.5).unwrap()),
            maximum_amount: Some(Amount::from_btc(2.0).unwrap()),
            maximum_count: Some(10),
        };
        let utxos_with_query = client
            .list_unspent(
                Some(1),
                Some(9_999_999),
                None,
                Some(true),
                Some(query_options),
            )
            .await
            .unwrap();
        assert!(!utxos_with_query.0.is_empty());
        for utxo in &utxos_with_query.0 {
            let amount_btc = utxo.amount.to_btc();
            assert!((0.5..=2.0).contains(&amount_btc));
        }

        let tx = finalized_psbt.hex.unwrap();
        assert!(!tx.input.is_empty());
        assert!(!tx.output.is_empty());
    }

    #[tokio::test()]
    async fn get_tx_out() {
        init_tracing();

        let (bitcoind, client) = get_bitcoind_and_client();

        // network sanity check
        let got = client.network().await.unwrap();
        let expected = Network::Regtest;
        assert_eq!(expected, got);

        let address = bitcoind.client.new_address().unwrap();
        let blocks = mine_blocks(&bitcoind, 101, Some(address)).unwrap();
        let last_block = client.get_block(blocks.first().unwrap()).await.unwrap();
        let coinbase_tx = last_block.coinbase().unwrap();

        // gettxout should work with a non-spent UTXO.
        let got = client
            .get_tx_out(&coinbase_tx.compute_txid(), 0, true)
            .await
            .unwrap();
        assert_eq!(got.tx_out.value, COINBASE_AMOUNT);

        // gettxout should fail with a spent UTXO.
        let new_address = bitcoind.client.new_address().unwrap();
        let send_amount = Amount::from_sat(COINBASE_AMOUNT.to_sat() - 2_000); // 2k sats as fees.
        let _send_tx = bitcoind
            .client
            .send_to_address(&new_address, send_amount)
            .unwrap()
            .txid()
            .unwrap();
        let result = client
            .get_tx_out(&coinbase_tx.compute_txid(), 0, true)
            .await;
        trace!(?result, "gettxout result");
        assert!(result.is_err());
    }

    /// Create two transactions.
    /// 1. Normal one: sends 1 BTC to an address that we control.
    /// 2. CFFP: replaces the first transaction with a different one that we also control.
    ///
    /// This is needed because we must SIGN all these transactions, and we can't sign a transaction
    /// that we don't control.
    #[tokio::test()]
    async fn submit_package() {
        init_tracing();

        let (bitcoind, client) = get_bitcoind_and_client();

        // network sanity check
        let got = client.network().await.unwrap();
        let expected = Network::Regtest;
        assert_eq!(expected, got);

        let blocks = mine_blocks(&bitcoind, 101, None).unwrap();
        let last_block = client.get_block(blocks.first().unwrap()).await.unwrap();
        let coinbase_tx = last_block.coinbase().unwrap();

        let destination = client.get_new_address().await.unwrap();
        let change_address = client.get_new_address().await.unwrap();
        let amount = Amount::from_btc(1.0).unwrap();
        let fees = Amount::from_btc(0.0001).unwrap();
        let change_amount = COINBASE_AMOUNT - amount - fees;
        let amount_minus_fees = Amount::from_sat(amount.to_sat() - 2_000);

        let send_back_address = client.get_new_address().await.unwrap();
        let parent_raw_tx = CreateRawTransactionArguments {
            inputs: vec![CreateRawTransactionInput {
                txid: coinbase_tx.compute_txid().to_string(),
                vout: 0,
            }],
            outputs: vec![
                // Destination
                CreateRawTransactionOutput::AddressAmount {
                    address: destination.to_string(),
                    amount: amount.to_btc(),
                },
                // Change
                CreateRawTransactionOutput::AddressAmount {
                    address: change_address.to_string(),
                    amount: change_amount.to_btc(),
                },
            ],
        };
        let parent = client.create_raw_transaction(parent_raw_tx).await.unwrap();
        let signed_parent = client
            .sign_raw_transaction_with_wallet(&parent, None)
            .await
            .unwrap()
            .tx;

        // sanity check
        let parent_submitted = client.send_raw_transaction(&signed_parent).await.unwrap();

        let child_raw_tx = CreateRawTransactionArguments {
            inputs: vec![CreateRawTransactionInput {
                txid: parent_submitted.to_string(),
                vout: 0,
            }],
            outputs: vec![
                // Send back
                CreateRawTransactionOutput::AddressAmount {
                    address: send_back_address.to_string(),
                    amount: amount_minus_fees.to_btc(),
                },
            ],
        };
        let child = client.create_raw_transaction(child_raw_tx).await.unwrap();
        let signed_child = client
            .sign_raw_transaction_with_wallet(&child, None)
            .await
            .unwrap()
            .tx;

        // Ok now we have a parent and a child transaction.
        let result = client
            .submit_package(&[signed_parent, signed_child])
            .await
            .unwrap();
        assert_eq!(result.tx_results.len(), 2);
        assert_eq!(result.package_msg, "success");
    }

    /// Similar to [`submit_package`], but with where the parent does not pay fees,
    /// and the child has to pay fees.
    ///
    /// This is called 1P1C because it has one parent and one child.
    /// See <https://bitcoinops.org/en/bitcoin-core-28-wallet-integration-guide/>
    /// for more information.
    #[tokio::test]
    async fn submit_package_1p1c() {
        init_tracing();

        let (bitcoind, client) = get_bitcoind_and_client();

        // 1p1c sanity check
        let server_version = bitcoind.client.server_version().unwrap();
        assert!(server_version > 28);

        let destination = client.get_new_address().await.unwrap();

        let blocks = mine_blocks(&bitcoind, 101, None).unwrap();
        let last_block = client.get_block(blocks.first().unwrap()).await.unwrap();
        let coinbase_tx = last_block.coinbase().unwrap();

        let parent_raw_tx = CreateRawTransactionArguments {
            inputs: vec![CreateRawTransactionInput {
                txid: coinbase_tx.compute_txid().to_string(),
                vout: 0,
            }],
            outputs: vec![CreateRawTransactionOutput::AddressAmount {
                address: destination.to_string(),
                amount: COINBASE_AMOUNT.to_btc(),
            }],
        };
        let mut parent = client.create_raw_transaction(parent_raw_tx).await.unwrap();
        parent.version = transaction::Version(3);
        assert_eq!(parent.version, transaction::Version(3));
        trace!(?parent, "parent:");
        let signed_parent = client
            .sign_raw_transaction_with_wallet(&parent, None)
            .await
            .unwrap()
            .tx;
        assert_eq!(signed_parent.version, transaction::Version(3));

        // Assert that the parent tx cannot be broadcasted.
        let parent_broadcasted = client.send_raw_transaction(&signed_parent).await;
        assert!(parent_broadcasted.is_err());

        // 5k sats as fees.
        let amount_minus_fees = Amount::from_sat(COINBASE_AMOUNT.to_sat() - 43_000);
        let child_raw_tx = CreateRawTransactionArguments {
            inputs: vec![CreateRawTransactionInput {
                txid: signed_parent.compute_txid().to_string(),
                vout: 0,
            }],
            outputs: vec![CreateRawTransactionOutput::AddressAmount {
                address: destination.to_string(),
                amount: amount_minus_fees.to_btc(),
            }],
        };
        let mut child = client.create_raw_transaction(child_raw_tx).await.unwrap();
        child.version = transaction::Version(3);
        assert_eq!(child.version, transaction::Version(3));
        trace!(?child, "child:");
        let prev_outputs = vec![PreviousTransactionOutput {
            txid: parent.compute_txid(),
            vout: 0,
            script_pubkey: parent.output[0].script_pubkey.to_hex_string(),
            redeem_script: None,
            witness_script: None,
            amount: Some(COINBASE_AMOUNT.to_btc()),
        }];
        let signed_child = client
            .sign_raw_transaction_with_wallet(&child, Some(prev_outputs))
            .await
            .unwrap()
            .tx;
        assert_eq!(signed_child.version, transaction::Version(3));

        // Assert that the child tx cannot be broadcasted.
        let child_broadcasted = client.send_raw_transaction(&signed_child).await;
        assert!(child_broadcasted.is_err());

        // Let's send as a package 1C1P.
        let result = client
            .submit_package(&[signed_parent, signed_child])
            .await
            .unwrap();
        assert_eq!(result.tx_results.len(), 2);
        assert_eq!(result.package_msg, "success");
    }

    #[tokio::test]
    async fn test_invalid_credentials_return_401_error() {
        init_tracing();

        let (bitcoind, _) = get_bitcoind_and_client();
        let url = bitcoind.rpc_url();

        let auth = Auth::UserPass("wrong_user".to_string(), "wrong_password".to_string());
        let invalid_client = Client::new(url, auth, None, None, None).unwrap();

        // Try to make any RPC call
        let result = invalid_client.get_blockchain_info().await;

        // Verify we get a 401 Status error, not a Parse error
        assert!(result.is_err());
        let error = result.unwrap_err();

        match error {
            ClientError::Status(status_code, message) => {
                assert_eq!(status_code, 401);
                assert!(message.contains("Unauthorized"));
            }
            _ => panic!("Expected Status(401, _) error, but got: {error:?}"),
        }
    }

    #[tokio::test]
    async fn test_send_raw_transaction_exposes_rpc_error_code_on_http_500() {
        init_tracing();

        let (_bitcoind, client) = get_bitcoind_and_client();

        let result = client
            .call::<String>("sendrawtransaction", &[to_value("deadbeef").unwrap()])
            .await;

        match result {
            Err(ClientError::Server(code, message)) => {
                assert_eq!(code, -22);
                assert!(
                    message.to_lowercase().contains("decode"),
                    "expected decode-related RPC error message, got: {message}"
                );
            }
            other => panic!("Expected Server(-22, _), got: {other:?}"),
        }
    }

    #[tokio::test]
    async fn test_get_raw_transaction_exposes_rpc_error_code_on_http_500() {
        init_tracing();

        let (_bitcoind, client) = get_bitcoind_and_client();
        let missing_txid = Txid::from_slice(&[0u8; 32]).expect("must be a valid txid");

        let error = client
            .get_raw_transaction_verbosity_zero(&missing_txid)
            .await
            .expect_err("missing txid must fail");

        assert!(
            !matches!(error, ClientError::Status(..) | ClientError::Parse(..)),
            "expected parsed RPC error, got transport/parsing error: {error:?}"
        );
        assert!(
            error.is_tx_not_found(),
            "expected tx-not-found classification, got: {error:?}"
        );
    }

    #[tokio::test]
    async fn psbt_bump_fee() {
        init_tracing();

        let (bitcoind, client) = get_bitcoind_and_client();

        // Mine blocks to have funds
        mine_blocks(&bitcoind, 101, None).unwrap();

        // Send to the next address
        let destination = client.get_new_address().await.unwrap();
        let amount = Amount::from_btc(0.001).unwrap(); // 0.001 BTC

        // Create transaction with RBF enabled
        let txid = bitcoind
            .client
            .send_to_address_rbf(&destination, amount)
            .unwrap()
            .txid()
            .unwrap();

        // Verify transaction is in mempool (unconfirmed)
        let mempool = client.get_raw_mempool().await.unwrap();
        assert!(
            mempool.0.contains(&txid),
            "Transaction should be in mempool for RBF"
        );

        // Test psbt_bump_fee with default options
        let signed_tx = client
            .psbt_bump_fee(&txid, None)
            .await
            .unwrap()
            .psbt
            .extract_tx()
            .unwrap();
        let signed_txid = signed_tx.compute_txid();
        let got = client
            .test_mempool_accept(&signed_tx)
            .await
            .unwrap()
            .results
            .first()
            .unwrap()
            .txid;
        assert_eq!(
            got, signed_txid,
            "Bumped transaction should be accepted in mempool"
        );

        // Test psbt_bump_fee with custom fee rate
        let options = PsbtBumpFeeOptions {
            fee_rate: Some(FeeRate::from_sat_per_kwu(20)), // 20 sat/vB - higher than default
            ..Default::default()
        };
        trace!(?options, "Calling psbt_bump_fee");
        let signed_tx = client
            .psbt_bump_fee(&txid, Some(options))
            .await
            .unwrap()
            .psbt
            .extract_tx()
            .unwrap();
        let signed_txid = signed_tx.compute_txid();
        let got = client
            .test_mempool_accept(&signed_tx)
            .await
            .unwrap()
            .results
            .first()
            .unwrap()
            .txid;
        assert_eq!(
            got, signed_txid,
            "Bumped transaction should be accepted in mempool"
        );
    }

    #[cfg(feature = "raw_rpc")]
    #[tokio::test]
    async fn call_raw() {
        init_tracing();

        let (bitcoind, client) = get_bitcoind_and_client();

        mine_blocks(&bitcoind, 5, None).unwrap();

        let expected = client.get_block_count().await.unwrap();

        let got: u64 = client.call_raw("getblockcount", &[]).await.unwrap();

        assert_eq!(expected, got);

        let height = 0;

        let expected_hash = client.get_block_hash(height).await.unwrap();

        let got_hash: BlockHash = client
            .call_raw("getblockhash", &[to_value(height).unwrap()])
            .await
            .unwrap();

        assert_eq!(expected_hash, got_hash);
    }

    #[test]
    fn test_network_chain_response() {
        let test_cases = vec![
            ("main", Network::Bitcoin),
            ("test", Network::Testnet),
            ("testnet4", Network::Testnet4),
            ("signet", Network::Signet),
            ("regtest", Network::Regtest),
        ];

        for (bitcoind_chain_str, expected_network) in test_cases {
            let result = Network::from_core_arg(bitcoind_chain_str);
            assert!(result.is_ok(), "failed for chain: {}", bitcoind_chain_str);
            assert_eq!(result.unwrap(), expected_network);
        }
    }
}