forked from rust-bitcoin/rust-bitcoincore-rpc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.rs
1557 lines (1389 loc) · 54.1 KB
/
client.rs
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
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication
// along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
//
use log::Level::{Debug, Trace, Warn};
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::iter::FromIterator;
use std::path::PathBuf;
use std::{fmt, result};
use crate::transport::ReqwestTransport;
use crate::{bitcoin, deserialize_hex};
use async_trait::async_trait;
use bitcoin::hex::DisplayHex;
use jsonrpc_async::Client as JsonRpcClient;
use serde::{self, Serialize};
use url::Url;
use crate::bitcoin::address::{NetworkChecked, NetworkUnchecked};
use crate::bitcoin::hashes::hex::FromHex;
use crate::bitcoin::secp256k1::ecdsa::Signature;
use crate::bitcoin::{
Address, Amount, Block, OutPoint, PrivateKey, PublicKey, Script, Transaction,
};
use crate::error::*;
use crate::json;
use crate::queryable;
/// Crate-specific Result type, shorthand for `std::result::Result` with our
/// crate-specific Error type;
pub type Result<T> = result::Result<T, Error>;
#[derive(Debug, Serialize, Deserialize)]
pub struct PackageSubmissionFees {
pub base: f64,
#[serde(rename = "effective-feerate", skip_serializing_if = "Option::is_none")]
pub effective_feerate: Option<f64>,
#[serde(rename = "effective-includes", skip_serializing_if = "Option::is_none")]
pub effective_includes: Option<Vec<String>>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PackageTransactionResult {
pub txid: String,
#[serde(rename = "other-wtxid", skip_serializing_if = "Option::is_none")]
pub other_wtxid: Option<String>,
pub vsize: u32,
pub fees: PackageSubmissionFees,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PackageSubmissionResult {
#[serde(rename = "tx-results")]
pub tx_results: HashMap<String, PackageTransactionResult>,
#[serde(rename = "replaced-transactions", skip_serializing_if = "Option::is_none")]
pub replaced_transactions: Option<Vec<String>>,
}
/// Outpoint that serializes and deserializes as a map, instead of a string,
/// for use as RPC arguments
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct JsonOutPoint {
pub txid: bitcoin::Txid,
pub vout: u32,
}
impl From<OutPoint> for JsonOutPoint {
fn from(o: OutPoint) -> JsonOutPoint {
JsonOutPoint {
txid: o.txid,
vout: o.vout,
}
}
}
impl Into<OutPoint> for JsonOutPoint {
fn into(self) -> OutPoint {
OutPoint {
txid: self.txid,
vout: self.vout,
}
}
}
/// Shorthand for converting a variable into a serde_json::Value.
fn into_json<T>(val: T) -> Result<serde_json::Value>
where
T: serde::ser::Serialize,
{
Ok(serde_json::to_value(val)?)
}
/// Shorthand for converting an Option into an Option<serde_json::Value>.
fn opt_into_json<T>(opt: Option<T>) -> Result<serde_json::Value>
where
T: serde::ser::Serialize,
{
match opt {
Some(val) => Ok(into_json(val)?),
None => Ok(serde_json::Value::Null),
}
}
/// Shorthand for `serde_json::Value::Null`.
fn null() -> serde_json::Value {
serde_json::Value::Null
}
/// Shorthand for an empty serde_json::Value array.
fn empty_arr() -> serde_json::Value {
serde_json::Value::Array(vec![])
}
/// Shorthand for an empty serde_json object.
fn empty_obj() -> serde_json::Value {
serde_json::Value::Object(Default::default())
}
/// Handle default values in the argument list
///
/// Substitute `Value::Null`s with corresponding values from `defaults` table,
/// except when they are trailing, in which case just skip them altogether
/// in returned list.
///
/// Note, that `defaults` corresponds to the last elements of `args`.
///
/// ```norust
/// arg1 arg2 arg3 arg4
/// def1 def2
/// ```
///
/// Elements of `args` without corresponding `defaults` value, won't
/// be substituted, because they are required.
fn handle_defaults<'a, 'b>(
args: &'a mut [serde_json::Value],
defaults: &'b [serde_json::Value],
) -> &'a [serde_json::Value] {
assert!(args.len() >= defaults.len());
// Pass over the optional arguments in backwards order, filling in defaults after the first
// non-null optional argument has been observed.
let mut first_non_null_optional_idx = None;
for i in 0..defaults.len() {
let args_i = args.len() - 1 - i;
let defaults_i = defaults.len() - 1 - i;
if args[args_i] == serde_json::Value::Null {
if first_non_null_optional_idx.is_some() {
if defaults[defaults_i] == serde_json::Value::Null {
panic!("Missing `default` for argument idx {}", args_i);
}
args[args_i] = defaults[defaults_i].clone();
}
} else if first_non_null_optional_idx.is_none() {
first_non_null_optional_idx = Some(args_i);
}
}
let required_num = args.len() - defaults.len();
if let Some(i) = first_non_null_optional_idx {
&args[..i + 1]
} else {
&args[..required_num]
}
}
/// Convert a possible-null result into an Option.
fn opt_result<T: for<'a> serde::de::Deserialize<'a>>(
result: serde_json::Value,
) -> Result<Option<T>> {
if result == serde_json::Value::Null {
Ok(None)
} else {
Ok(serde_json::from_value(result)?)
}
}
/// Used to pass raw txs into the API.
pub trait RawTx: Sized + Clone + Send {
fn raw_hex(self) -> String;
}
impl<'a> RawTx for &'a Transaction {
fn raw_hex(self) -> String {
bitcoin::consensus::encode::serialize_hex(self)
}
}
impl<'a> RawTx for &'a [u8] {
fn raw_hex(self) -> String {
self.to_lower_hex_string()
}
}
impl<'a> RawTx for &'a Vec<u8> {
fn raw_hex(self) -> String {
self.to_lower_hex_string()
}
}
impl<'a> RawTx for &'a str {
fn raw_hex(self) -> String {
self.to_owned()
}
}
impl RawTx for String {
fn raw_hex(self) -> String {
self
}
}
/// The different authentication methods for the client.
#[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub enum Auth {
None,
UserPass(String, String),
CookieFile(PathBuf),
}
impl Auth {
/// Convert into the arguments that jsonrpc_async::Client needs.
pub fn get_user_pass(self) -> Result<(Option<String>, Option<String>)> {
match self {
Auth::None => Ok((None, None)),
Auth::UserPass(u, p) => Ok((Some(u), Some(p))),
Auth::CookieFile(path) => {
let line = BufReader::new(File::open(path)?)
.lines()
.next()
.ok_or(Error::InvalidCookieFile)??;
let colon = line.find(':').ok_or(Error::InvalidCookieFile)?;
Ok((Some(line[..colon].into()), Some(line[colon + 1..].into())))
}
}
}
}
#[async_trait]
pub trait RpcApi: Sized {
/// Call a `cmd` rpc with given `args` list
async fn call<T: for<'a> serde::de::Deserialize<'a>>(
&self,
cmd: &str,
args: &[serde_json::Value],
) -> Result<T>;
/// Query an object implementing `Querable` type
async fn get_by_id<T: queryable::Queryable<Self> + Sync + Send>(
&self,
id: &<T as queryable::Queryable<Self>>::Id,
) -> Result<T> {
T::query(&self, &id).await
}
async fn get_network_info(&self) -> Result<json::GetNetworkInfoResult> {
self.call("getnetworkinfo", &[]).await
}
async fn get_index_info(&self) -> Result<json::GetIndexInfoResult> {
self.call("getindexinfo", &[]).await
}
async fn version(&self) -> Result<usize> {
#[derive(Deserialize)]
struct Response {
pub version: usize,
}
let res: Response = self.call("getnetworkinfo", &[]).await?;
Ok(res.version)
}
async fn add_multisig_address(
&self,
nrequired: usize,
keys: &[json::PubKeyOrAddress],
label: Option<&str>,
address_type: Option<json::AddressType>,
) -> Result<json::AddMultiSigAddressResult> {
let mut args = [
into_json(nrequired)?,
into_json(keys)?,
opt_into_json(label)?,
opt_into_json(address_type)?,
];
self.call("addmultisigaddress", handle_defaults(&mut args, &[into_json("")?, null()])).await
}
async fn bump_fee(
&self,
txid: &bitcoin::Txid,
options: Option<&json::BumpFeeOptions>,
) -> Result<json::BumpFeeResult> {
let opts = match options {
Some(options) => Some(options.to_serializable(self.version().await?)),
None => None,
};
let mut args = [into_json(txid)?, opt_into_json(opts)?];
self.call("bumpfee", handle_defaults(&mut args, &[null()])).await
}
async fn psbt_bump_fee(
&self,
txid: &bitcoin::Txid,
options: Option<&json::BumpFeeOptions>,
) -> Result<json::BumpFeeResult> {
let opts = match options {
Some(options) => Some(options.to_serializable(self.version().await?)),
None => None,
};
let mut args = [into_json(txid)?, opt_into_json(opts)?];
self.call("psbtbumpfee", handle_defaults(&mut args, &[null()])).await
}
async fn load_wallet(&self, wallet: &str) -> Result<json::LoadWalletResult> {
self.call("loadwallet", &[wallet.into()]).await
}
async fn unload_wallet(
&self,
wallet: Option<&str>,
) -> Result<Option<json::UnloadWalletResult>> {
let mut args = [opt_into_json(wallet)?];
self.call("unloadwallet", handle_defaults(&mut args, &[null()])).await
}
async fn create_wallet(
&self,
wallet: &str,
disable_private_keys: Option<bool>,
blank: Option<bool>,
passphrase: Option<&str>,
avoid_reuse: Option<bool>,
) -> Result<json::LoadWalletResult> {
let mut args = [
wallet.into(),
opt_into_json(disable_private_keys)?,
opt_into_json(blank)?,
opt_into_json(passphrase)?,
opt_into_json(avoid_reuse)?,
];
self.call(
"createwallet",
handle_defaults(&mut args, &[false.into(), false.into(), into_json("")?, false.into()]),
)
.await
}
async fn list_wallets(&self) -> Result<Vec<String>> {
self.call("listwallets", &[]).await
}
async fn list_wallet_dir(&self) -> Result<Vec<String>> {
let result: json::ListWalletDirResult = self.call("listwalletdir", &[]).await?;
let names = result.wallets.into_iter().map(|x| x.name).collect();
Ok(names)
}
async fn get_wallet_info(&self) -> Result<json::GetWalletInfoResult> {
self.call("getwalletinfo", &[]).await
}
async fn backup_wallet(&self, destination: Option<&str>) -> Result<()> {
let mut args = [opt_into_json(destination)?];
self.call("backupwallet", handle_defaults(&mut args, &[null()])).await
}
async fn dump_private_key(&self, address: &Address) -> Result<PrivateKey> {
self.call("dumpprivkey", &[address.to_string().into()]).await
}
async fn encrypt_wallet(&self, passphrase: &str) -> Result<()> {
self.call("encryptwallet", &[into_json(passphrase)?]).await
}
async fn get_difficulty(&self) -> Result<f64> {
self.call("getdifficulty", &[]).await
}
async fn get_connection_count(&self) -> Result<usize> {
self.call("getconnectioncount", &[]).await
}
async fn get_block(&self, hash: &bitcoin::BlockHash) -> Result<Block> {
let hex: String = self.call("getblock", &[into_json(hash)?, 0.into()]).await?;
deserialize_hex(&hex)
}
async fn get_block_hex(&self, hash: &bitcoin::BlockHash) -> Result<String> {
self.call("getblock", &[into_json(hash)?, 0.into()]).await
}
async fn get_block_info(&self, hash: &bitcoin::BlockHash) -> Result<json::GetBlockResult> {
self.call("getblock", &[into_json(hash)?, 1.into()]).await
}
async fn get_block_verbose(
&self,
hash: &bitcoin::BlockHash,
) -> Result<json::GetBlockVerboseResult> {
self.call("getblock", &[into_json(hash)?, 2.into()]).await
}
async fn get_block_header(&self, hash: &bitcoin::BlockHash) -> Result<bitcoin::block::Header> {
let hex: String = self.call("getblockheader", &[into_json(hash)?, false.into()]).await?;
deserialize_hex(&hex)
}
async fn get_block_header_info(
&self,
hash: &bitcoin::BlockHash,
) -> Result<json::GetBlockHeaderResult> {
self.call("getblockheader", &[into_json(hash)?, true.into()]).await
}
async fn get_mining_info(&self) -> Result<json::GetMiningInfoResult> {
self.call("getmininginfo", &[]).await
}
async fn get_block_template(
&self,
mode: json::GetBlockTemplateModes,
rules: &[json::GetBlockTemplateRules],
capabilities: &[json::GetBlockTemplateCapabilities],
) -> Result<json::GetBlockTemplateResult> {
#[derive(Serialize)]
struct Argument<'a> {
mode: json::GetBlockTemplateModes,
rules: &'a [json::GetBlockTemplateRules],
capabilities: &'a [json::GetBlockTemplateCapabilities],
}
self.call(
"getblocktemplate",
&[into_json(Argument {
mode: mode,
rules: rules,
capabilities: capabilities,
})?],
)
.await
}
/// Returns a data structure containing various state info regarding
/// blockchain processing.
async fn get_blockchain_info(&self) -> Result<json::GetBlockchainInfoResult> {
let mut raw: serde_json::Value = self.call("getblockchaininfo", &[]).await?;
// The softfork fields are not backwards compatible:
// - 0.18.x returns a "softforks" array and a "bip9_softforks" map.
// - 0.19.x returns a "softforks" map.
Ok(if self.version().await? < 190000 {
use crate::Error::UnexpectedStructure as err;
// First, remove both incompatible softfork fields.
// We need to scope the mutable ref here for v1.29 borrowck.
let (bip9_softforks, old_softforks) = {
let map = raw.as_object_mut().ok_or(err)?;
let bip9_softforks = map.remove("bip9_softforks").ok_or(err)?;
let old_softforks = map.remove("softforks").ok_or(err)?;
// Put back an empty "softforks" field.
map.insert("softforks".into(), serde_json::Map::new().into());
(bip9_softforks, old_softforks)
};
let mut ret: json::GetBlockchainInfoResult = serde_json::from_value(raw)?;
// Then convert both softfork types and add them.
for sf in old_softforks.as_array().ok_or(err)?.iter() {
let json = sf.as_object().ok_or(err)?;
let id = json.get("id").ok_or(err)?.as_str().ok_or(err)?;
let reject = json.get("reject").ok_or(err)?.as_object().ok_or(err)?;
let active = reject.get("status").ok_or(err)?.as_bool().ok_or(err)?;
ret.softforks.insert(
id.into(),
json::Softfork {
type_: json::SoftforkType::Buried,
bip9: None,
height: None,
active: active,
},
);
}
for (id, sf) in bip9_softforks.as_object().ok_or(err)?.iter() {
#[derive(Deserialize)]
struct OldBip9SoftFork {
pub status: json::Bip9SoftforkStatus,
pub bit: Option<u8>,
#[serde(rename = "startTime")]
pub start_time: i64,
pub timeout: u64,
pub since: u32,
pub statistics: Option<json::Bip9SoftforkStatistics>,
}
let sf: OldBip9SoftFork = serde_json::from_value(sf.clone())?;
ret.softforks.insert(
id.clone(),
json::Softfork {
type_: json::SoftforkType::Bip9,
bip9: Some(json::Bip9SoftforkInfo {
status: sf.status,
bit: sf.bit,
start_time: sf.start_time,
timeout: sf.timeout,
since: sf.since,
statistics: sf.statistics,
}),
height: None,
active: sf.status == json::Bip9SoftforkStatus::Active,
},
);
}
ret
} else {
serde_json::from_value(raw)?
})
}
/// Returns the numbers of block in the longest chain.
async fn get_block_count(&self) -> Result<u64> {
self.call("getblockcount", &[]).await
}
/// Returns the hash of the best (tip) block in the longest blockchain.
async fn get_best_block_hash(&self) -> Result<bitcoin::BlockHash> {
self.call("getbestblockhash", &[]).await
}
/// Get block hash at a given height
async fn get_block_hash(&self, height: u64) -> Result<bitcoin::BlockHash> {
self.call("getblockhash", &[height.into()]).await
}
async fn get_block_stats(&self, height: u64) -> Result<json::GetBlockStatsResult> {
self.call("getblockstats", &[height.into()]).await
}
async fn get_block_stats_fields(
&self,
height: u64,
fields: &[json::BlockStatsFields],
) -> Result<json::GetBlockStatsResultPartial> {
self.call("getblockstats", &[height.into(), fields.into()]).await
}
async fn get_raw_transaction(
&self,
txid: &bitcoin::Txid,
block_hash: Option<&bitcoin::BlockHash>,
) -> Result<Transaction> {
let mut args = [into_json(txid)?, into_json(false)?, opt_into_json(block_hash)?];
let hex: String =
self.call("getrawtransaction", handle_defaults(&mut args, &[null()])).await?;
deserialize_hex(&hex)
}
async fn get_raw_transaction_hex(
&self,
txid: &bitcoin::Txid,
block_hash: Option<&bitcoin::BlockHash>,
) -> Result<String> {
let mut args = [into_json(txid)?, into_json(false)?, opt_into_json(block_hash)?];
self.call("getrawtransaction", handle_defaults(&mut args, &[null()])).await
}
async fn get_raw_transaction_info(
&self,
txid: &bitcoin::Txid,
block_hash: Option<&bitcoin::BlockHash>,
) -> Result<json::GetRawTransactionResult> {
let mut args = [into_json(txid)?, into_json(true)?, opt_into_json(block_hash)?];
self.call("getrawtransaction", handle_defaults(&mut args, &[null()])).await
}
async fn get_block_filter(
&self,
block_hash: &bitcoin::BlockHash,
) -> Result<json::GetBlockFilterResult> {
self.call("getblockfilter", &[into_json(block_hash)?]).await
}
async fn get_balance(
&self,
minconf: Option<usize>,
include_watchonly: Option<bool>,
) -> Result<Amount> {
let mut args = ["*".into(), opt_into_json(minconf)?, opt_into_json(include_watchonly)?];
Ok(Amount::from_btc(
self.call("getbalance", handle_defaults(&mut args, &[0.into(), null()])).await?,
)?)
}
async fn get_balances(&self) -> Result<json::GetBalancesResult> {
Ok(self.call("getbalances", &[]).await?)
}
async fn get_received_by_address(
&self,
address: &Address,
minconf: Option<u32>,
) -> Result<Amount> {
let mut args = [address.to_string().into(), opt_into_json(minconf)?];
Ok(Amount::from_btc(
self.call("getreceivedbyaddress", handle_defaults(&mut args, &[null()])).await?,
)?)
}
async fn get_transaction(
&self,
txid: &bitcoin::Txid,
include_watchonly: Option<bool>,
) -> Result<json::GetTransactionResult> {
let mut args = [into_json(txid)?, opt_into_json(include_watchonly)?];
self.call("gettransaction", handle_defaults(&mut args, &[null()])).await
}
async fn list_transactions(
&self,
label: Option<&str>,
count: Option<usize>,
skip: Option<usize>,
include_watchonly: Option<bool>,
) -> Result<Vec<json::ListTransactionResult>> {
let mut args = [
label.unwrap_or("*").into(),
opt_into_json(count)?,
opt_into_json(skip)?,
opt_into_json(include_watchonly)?,
];
self.call("listtransactions", handle_defaults(&mut args, &[10.into(), 0.into(), null()]))
.await
}
async fn list_since_block(
&self,
blockhash: Option<&bitcoin::BlockHash>,
target_confirmations: Option<usize>,
include_watchonly: Option<bool>,
include_removed: Option<bool>,
) -> Result<json::ListSinceBlockResult> {
let mut args = [
opt_into_json(blockhash)?,
opt_into_json(target_confirmations)?,
opt_into_json(include_watchonly)?,
opt_into_json(include_removed)?,
];
self.call("listsinceblock", handle_defaults(&mut args, &[null()])).await
}
async fn get_tx_out(
&self,
txid: &bitcoin::Txid,
vout: u32,
include_mempool: Option<bool>,
) -> Result<Option<json::GetTxOutResult>> {
let mut args = [into_json(txid)?, into_json(vout)?, opt_into_json(include_mempool)?];
opt_result(self.call("gettxout", handle_defaults(&mut args, &[null()])).await?)
}
async fn get_tx_out_proof(
&self,
txids: &[bitcoin::Txid],
block_hash: Option<&bitcoin::BlockHash>,
) -> Result<Vec<u8>> {
let mut args = [into_json(txids)?, opt_into_json(block_hash)?];
let hex: String = self.call("gettxoutproof", handle_defaults(&mut args, &[null()])).await?;
Ok(FromHex::from_hex(&hex)?)
}
async fn import_public_key(
&self,
pubkey: &PublicKey,
label: Option<&str>,
rescan: Option<bool>,
) -> Result<()> {
let mut args = [pubkey.to_string().into(), opt_into_json(label)?, opt_into_json(rescan)?];
self.call("importpubkey", handle_defaults(&mut args, &[into_json("")?, null()])).await
}
async fn import_private_key(
&self,
privkey: &PrivateKey,
label: Option<&str>,
rescan: Option<bool>,
) -> Result<()> {
let mut args = [privkey.to_string().into(), opt_into_json(label)?, opt_into_json(rescan)?];
self.call("importprivkey", handle_defaults(&mut args, &[into_json("")?, null()])).await
}
async fn import_address(
&self,
address: &Address,
label: Option<&str>,
rescan: Option<bool>,
) -> Result<()> {
let mut args = [address.to_string().into(), opt_into_json(label)?, opt_into_json(rescan)?];
self.call("importaddress", handle_defaults(&mut args, &[into_json("")?, null()])).await
}
async fn import_address_script(
&self,
script: &Script,
label: Option<&str>,
rescan: Option<bool>,
p2sh: Option<bool>,
) -> Result<()> {
let mut args = [
script.to_hex_string().into(),
opt_into_json(label)?,
opt_into_json(rescan)?,
opt_into_json(p2sh)?,
];
self.call(
"importaddress",
handle_defaults(&mut args, &[into_json("")?, true.into(), null()]),
)
.await
}
async fn import_multi(
&self,
requests: &[json::ImportMultiRequest],
options: Option<&json::ImportMultiOptions>,
) -> Result<Vec<json::ImportMultiResult>> {
let mut json_requests = Vec::with_capacity(requests.len());
for req in requests {
json_requests.push(serde_json::to_value(req)?);
}
let mut args = [json_requests.into(), opt_into_json(options)?];
self.call("importmulti", handle_defaults(&mut args, &[null()])).await
}
async fn import_descriptors(
&self,
req: json::ImportDescriptors,
) -> Result<Vec<json::ImportMultiResult>> {
let json_request = vec![serde_json::to_value(req)?];
self.call("importdescriptors", handle_defaults(&mut [json_request.into()], &[null()])).await
}
async fn set_label(&self, address: &Address, label: &str) -> Result<()> {
self.call("setlabel", &[address.to_string().into(), label.into()]).await
}
async fn key_pool_refill(&self, new_size: Option<usize>) -> Result<()> {
let mut args = [opt_into_json(new_size)?];
self.call("keypoolrefill", handle_defaults(&mut args, &[null()])).await
}
async fn list_unspent(
&self,
minconf: Option<usize>,
maxconf: Option<usize>,
addresses: Option<&[&Address<NetworkChecked>]>,
include_unsafe: Option<bool>,
query_options: Option<json::ListUnspentQueryOptions>,
) -> Result<Vec<json::ListUnspentResultEntry>> {
let mut args = [
opt_into_json(minconf)?,
opt_into_json(maxconf)?,
opt_into_json(addresses)?,
opt_into_json(include_unsafe)?,
opt_into_json(query_options)?,
];
let defaults = [into_json(0)?, into_json(9999999)?, empty_arr(), into_json(true)?, null()];
self.call("listunspent", handle_defaults(&mut args, &defaults)).await
}
/// To unlock, use [unlock_unspent].
async fn lock_unspent(&self, outputs: &[OutPoint]) -> Result<bool> {
let outputs: Vec<_> = outputs
.into_iter()
.map(|o| serde_json::to_value(JsonOutPoint::from(*o)).unwrap())
.collect();
self.call("lockunspent", &[false.into(), outputs.into()]).await
}
async fn unlock_unspent(&self, outputs: &[OutPoint]) -> Result<bool> {
let outputs: Vec<_> = outputs
.into_iter()
.map(|o| serde_json::to_value(JsonOutPoint::from(*o)).unwrap())
.collect();
self.call("lockunspent", &[true.into(), outputs.into()]).await
}
/// Unlock all unspent UTXOs.
async fn unlock_unspent_all(&self) -> Result<bool> {
self.call("lockunspent", &[true.into()]).await
}
async fn list_received_by_address(
&self,
address_filter: Option<&Address>,
minconf: Option<u32>,
include_empty: Option<bool>,
include_watchonly: Option<bool>,
) -> Result<Vec<json::ListReceivedByAddressResult>> {
let mut args = [
opt_into_json(minconf)?,
opt_into_json(include_empty)?,
opt_into_json(include_watchonly)?,
opt_into_json(address_filter)?,
];
let defaults = [1.into(), false.into(), false.into(), null()];
self.call("listreceivedbyaddress", handle_defaults(&mut args, &defaults)).await
}
async fn create_psbt(
&self,
inputs: &[json::CreateRawTransactionInput],
outputs: &HashMap<String, Amount>,
locktime: Option<i64>,
replaceable: Option<bool>,
) -> Result<String> {
let outs_converted = serde_json::Map::from_iter(
outputs.iter().map(|(k, v)| (k.clone(), serde_json::Value::from(v.to_btc()))),
);
self.call(
"createpsbt",
&[
into_json(inputs)?,
into_json(outs_converted)?,
into_json(locktime)?,
into_json(replaceable)?,
],
)
.await
}
async fn create_raw_transaction_hex(
&self,
utxos: &[json::CreateRawTransactionInput],
outs: &HashMap<String, Amount>,
locktime: Option<i64>,
replaceable: Option<bool>,
) -> Result<String> {
let outs_converted = serde_json::Map::from_iter(
outs.iter().map(|(k, v)| (k.clone(), serde_json::Value::from(v.to_btc()))),
);
let mut args = [
into_json(utxos)?,
into_json(outs_converted)?,
opt_into_json(locktime)?,
opt_into_json(replaceable)?,
];
let defaults = [into_json(0i64)?, null()];
self.call("createrawtransaction", handle_defaults(&mut args, &defaults)).await
}
async fn create_raw_transaction(
&self,
utxos: &[json::CreateRawTransactionInput],
outs: &HashMap<String, Amount>,
locktime: Option<i64>,
replaceable: Option<bool>,
) -> Result<Transaction> {
let hex: String =
self.create_raw_transaction_hex(utxos, outs, locktime, replaceable).await?;
deserialize_hex(&hex)
}
async fn decode_raw_transaction<R: RawTx>(
&self,
tx: R,
is_witness: Option<bool>,
) -> Result<json::DecodeRawTransactionResult> {
let mut args = [tx.raw_hex().into(), opt_into_json(is_witness)?];
let defaults = [null()];
self.call("decoderawtransaction", handle_defaults(&mut args, &defaults)).await
}
async fn fund_raw_transaction<R: RawTx>(
&self,
tx: R,
options: Option<&json::FundRawTransactionOptions>,
is_witness: Option<bool>,
) -> Result<json::FundRawTransactionResult> {
let mut args = [tx.raw_hex().into(), opt_into_json(options)?, opt_into_json(is_witness)?];
let defaults = [empty_obj(), null()];
self.call("fundrawtransaction", handle_defaults(&mut args, &defaults)).await
}
#[deprecated]
async fn sign_raw_transaction<R: RawTx>(
&self,
tx: R,
utxos: Option<&[json::SignRawTransactionInput]>,
private_keys: Option<&[PrivateKey]>,
sighash_type: Option<json::SigHashType>,
) -> Result<json::SignRawTransactionResult> {
let mut args = [
tx.raw_hex().into(),
opt_into_json(utxos)?,
opt_into_json(private_keys)?,
opt_into_json(sighash_type)?,
];
let defaults = [empty_arr(), empty_arr(), null()];
self.call("signrawtransaction", handle_defaults(&mut args, &defaults)).await
}
async fn sign_raw_transaction_with_wallet<R: RawTx>(
&self,
tx: R,
utxos: Option<&[json::SignRawTransactionInput]>,
sighash_type: Option<json::SigHashType>,
) -> Result<json::SignRawTransactionResult> {
let mut args = [tx.raw_hex().into(), opt_into_json(utxos)?, opt_into_json(sighash_type)?];
let defaults = [empty_arr(), null()];
self.call("signrawtransactionwithwallet", handle_defaults(&mut args, &defaults)).await
}
async fn sign_raw_transaction_with_key<R: RawTx>(
&self,
tx: R,
privkeys: &[PrivateKey],
prevtxs: Option<&[json::SignRawTransactionInput]>,
sighash_type: Option<json::SigHashType>,
) -> Result<json::SignRawTransactionResult> {
let mut args = [
tx.raw_hex().into(),
into_json(privkeys)?,
opt_into_json(prevtxs)?,
opt_into_json(sighash_type)?,
];
let defaults = [empty_arr(), null()];
self.call("signrawtransactionwithkey", handle_defaults(&mut args, &defaults)).await
}
async fn test_mempool_accept<R: RawTx + Send + Sync>(
&self,
rawtxs: &[R],
) -> Result<Vec<json::TestMempoolAcceptResult>> {
let hexes: Vec<serde_json::Value> =
rawtxs.to_vec().into_iter().map(|r| r.raw_hex().into()).collect();
self.call("testmempoolaccept", &[hexes.into()]).await
}
async fn submit_package<R: RawTx + Send + Sync>(&self, rawtxs: &[R]) -> Result<PackageSubmissionResult> {
let hexes: Vec<serde_json::Value> =
rawtxs.to_vec().into_iter().map(|r| r.raw_hex().into()).collect();
self.call("submitpackage", &[hexes.into()]).await
}
async fn stop(&self) -> Result<String> {
self.call("stop", &[]).await
}
async fn verify_message(
&self,
address: &Address,
signature: &Signature,
message: &str,
) -> Result<bool> {
let args = [address.to_string().into(), signature.to_string().into(), into_json(message)?];
self.call("verifymessage", &args).await
}
/// Generate new address under own control
async fn get_new_address(
&self,
label: Option<&str>,
address_type: Option<json::AddressType>,
) -> Result<Address<NetworkUnchecked>> {
self.call("getnewaddress", &[opt_into_json(label)?, opt_into_json(address_type)?]).await
}
/// Generate new address for receiving change
async fn get_raw_change_address(
&self,
address_type: Option<json::AddressType>,
) -> Result<Address<NetworkUnchecked>> {
self.call("getrawchangeaddress", &[opt_into_json(address_type)?]).await
}
async fn get_address_info(&self, address: &Address) -> Result<json::GetAddressInfoResult> {
self.call("getaddressinfo", &[address.to_string().into()]).await
}
/// Mine `block_num` blocks and pay coinbase to `address`
///
/// Returns hashes of the generated blocks
async fn generate_to_address(
&self,
block_num: u64,
address: &Address<NetworkChecked>,
) -> Result<Vec<bitcoin::BlockHash>> {
self.call("generatetoaddress", &[block_num.into(), address.to_string().into()]).await
}
/// Mine up to block_num blocks immediately (before the RPC call returns)
/// to an address in the wallet.
async fn generate(
&self,