-
Notifications
You must be signed in to change notification settings - Fork 75
/
wallet_sync.rs
1459 lines (1329 loc) · 52.2 KB
/
wallet_sync.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
// this file contains code handling the wallet and sync'ing the wallet
// for now the wallet is only sync'd via bitcoin core's RPC
// makers will only ever sync this way, but one day takers may sync in other
// ways too such as a lightweight wallet method
use std::fs::File;
use std::io;
use std::io::Read;
use std::path::Path;
use std::str::FromStr;
use std::sync::Arc;
use std::collections::{HashMap, HashSet};
use itertools::izip;
use bitcoin_wallet::mnemonic;
use bitcoin::{
blockdata::{
opcodes::all,
script::{Builder, Script},
},
hashes::{
hash160::Hash as Hash160,
hex::{FromHex, ToHex},
},
secp256k1,
secp256k1::{Secp256k1, SecretKey, Signature},
util::{
bip143::SigHashCache,
bip32::{ChildNumber, DerivationPath, ExtendedPrivKey, ExtendedPubKey},
key::PublicKey,
psbt::serialize::Serialize,
},
Address, Amount, Network, OutPoint, SigHashType, Transaction, TxIn, TxOut, Txid,
};
use bitcoincore_rpc::json::{
ImportMultiOptions, ImportMultiRequest, ImportMultiRequestScriptPubkey, ImportMultiRescanSince,
ListUnspentResultEntry, WalletCreateFundedPsbtOptions,
};
use bitcoincore_rpc::{Client, RpcApi};
use serde_json::json;
use serde_json::Value;
use rand::rngs::OsRng;
use rand::RngCore;
use crate::contracts;
use crate::contracts::{read_hashvalue_from_contract, read_locktime_from_contract, SwapCoin};
use crate::error::Error;
use crate::messages::Preimage;
//these subroutines are coded so that as much as possible they keep all their
//data in the bitcoin core wallet
//for example which privkey corresponds to a scriptpubkey is stored in hd paths
//TODO this goes in the config file
pub const NETWORK: Network = Network::Regtest; //not configurable for now
const DERIVATION_PATH: &str = "m/84'/1'/0'";
const WALLET_FILE_VERSION: u32 = 0;
#[cfg(not(test))]
const INITIAL_ADDRESS_IMPORT_COUNT: usize = 5000;
#[cfg(test)]
const INITIAL_ADDRESS_IMPORT_COUNT: usize = 6;
//TODO the wallet file format is probably best handled with sqlite
#[derive(serde::Serialize, serde::Deserialize)]
struct WalletFileData {
version: u32,
seedphrase: String,
extension: String,
external_index: u32,
incoming_swap_coins: Vec<IncomingSwapCoin>,
outgoing_swap_coins: Vec<OutgoingSwapCoin>,
prevout_to_contract_map: HashMap<OutPoint, Script>,
}
pub struct Wallet {
master_key: ExtendedPrivKey,
wallet_file_name: String,
external_index: u32,
incoming_swap_coins: HashMap<Script, IncomingSwapCoin>,
outgoing_swap_coins: HashMap<Script, OutgoingSwapCoin>,
}
pub enum CoreAddressLabelType {
Wallet,
WatchOnlySwapCoin,
}
const WATCH_ONLY_SWAPCOIN_LABEL: &str = "watchonly_swapcoin_label";
//swapcoins are UTXOs + metadata which are not from the deterministic wallet
//they are made in the process of a coinswap
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
pub struct IncomingSwapCoin {
pub my_privkey: SecretKey,
pub other_pubkey: PublicKey,
pub other_privkey: Option<SecretKey>,
pub contract_tx: Transaction,
pub contract_redeemscript: Script,
pub hashlock_privkey: SecretKey,
pub funding_amount: u64,
pub others_contract_sig: Option<Signature>,
pub hash_preimage: Option<Preimage>,
}
//swapcoins are UTXOs + metadata which are not from the deterministic wallet
//they are made in the process of a coinswap
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
pub struct OutgoingSwapCoin {
pub my_privkey: SecretKey,
pub other_pubkey: PublicKey,
pub contract_tx: Transaction,
pub contract_redeemscript: Script,
pub timelock_privkey: SecretKey,
pub funding_amount: u64,
pub others_contract_sig: Option<Signature>,
pub hash_preimage: Option<Preimage>,
}
impl IncomingSwapCoin {
pub fn new(
my_privkey: SecretKey,
other_pubkey: PublicKey,
contract_tx: Transaction,
contract_redeemscript: Script,
hashlock_privkey: SecretKey,
funding_amount: u64,
) -> Self {
let secp = Secp256k1::new();
let hashlock_pubkey = PublicKey {
compressed: true,
key: secp256k1::PublicKey::from_secret_key(&secp, &hashlock_privkey),
};
assert!(
hashlock_pubkey
== contracts::read_hashlock_pubkey_from_contract(&contract_redeemscript).unwrap()
);
Self {
my_privkey,
other_pubkey,
other_privkey: None,
contract_tx,
contract_redeemscript,
hashlock_privkey,
funding_amount,
others_contract_sig: None,
hash_preimage: None,
}
}
fn sign_transaction_input(
&self,
index: usize,
tx: &Transaction,
input: &mut TxIn,
redeemscript: &Script,
) -> Result<(), &'static str> {
if self.other_privkey.is_none() {
return Err("unable to sign: incomplete coinswap for this input");
}
let secp = Secp256k1::new();
let my_pubkey = self.get_my_pubkey();
let sighash = secp256k1::Message::from_slice(
&SigHashCache::new(tx).signature_hash(
index,
redeemscript,
self.funding_amount,
SigHashType::All,
)[..],
)
.unwrap();
let sig_mine = secp.sign(&sighash, &self.my_privkey);
let sig_other = secp.sign(&sighash, &self.other_privkey.unwrap());
apply_two_signatures_to_2of2_multisig_spend(
&my_pubkey,
&self.other_pubkey,
&sig_mine,
&sig_other,
input,
redeemscript,
);
Ok(())
}
}
impl OutgoingSwapCoin {
pub fn new(
my_privkey: SecretKey,
other_pubkey: PublicKey,
contract_tx: Transaction,
contract_redeemscript: Script,
timelock_privkey: SecretKey,
funding_amount: u64,
) -> Self {
let secp = Secp256k1::new();
let timelock_pubkey = PublicKey {
compressed: true,
key: secp256k1::PublicKey::from_secret_key(&secp, &timelock_privkey),
};
assert!(
timelock_pubkey
== contracts::read_timelock_pubkey_from_contract(&contract_redeemscript).unwrap()
);
Self {
my_privkey,
other_pubkey,
contract_tx,
contract_redeemscript,
timelock_privkey,
funding_amount,
others_contract_sig: None,
hash_preimage: None,
}
}
pub fn get_fully_signed_contract_tx(&self) -> Transaction {
if self.others_contract_sig.is_none() {
panic!("invalid state: others_contract_sig not known");
}
let my_pubkey = self.get_my_pubkey();
let multisig_redeemscript = create_multisig_redeemscript(&my_pubkey, &self.other_pubkey);
let index = 0;
let secp = Secp256k1::new();
let sighash = secp256k1::Message::from_slice(
&SigHashCache::new(&self.contract_tx).signature_hash(
index,
&multisig_redeemscript,
self.funding_amount,
SigHashType::All,
)[..],
)
.unwrap();
let sig_mine = secp.sign(&sighash, &self.my_privkey);
let mut signed_contract_tx = self.contract_tx.clone();
apply_two_signatures_to_2of2_multisig_spend(
&my_pubkey,
&self.other_pubkey,
&sig_mine,
&self.others_contract_sig.unwrap(),
&mut signed_contract_tx.input[index],
&multisig_redeemscript,
);
signed_contract_tx
}
}
pub trait WalletSwapCoin {
fn get_my_pubkey(&self) -> PublicKey;
fn get_other_pubkey(&self) -> &PublicKey;
}
impl WalletSwapCoin for IncomingSwapCoin {
fn get_my_pubkey(&self) -> PublicKey {
let secp = Secp256k1::new();
PublicKey {
compressed: true,
key: secp256k1::PublicKey::from_secret_key(&secp, &self.my_privkey),
}
}
fn get_other_pubkey(&self) -> &PublicKey {
&self.other_pubkey
}
}
impl WalletSwapCoin for OutgoingSwapCoin {
fn get_my_pubkey(&self) -> PublicKey {
let secp = Secp256k1::new();
PublicKey {
compressed: true,
key: secp256k1::PublicKey::from_secret_key(&secp, &self.my_privkey),
}
}
fn get_other_pubkey(&self) -> &PublicKey {
&self.other_pubkey
}
}
impl Wallet {
pub fn print_wallet_key_data(&self) {
println!(
"master key = {}, external_index = {}",
self.master_key, self.external_index
);
for (multisig_redeemscript, swapcoin) in &self.incoming_swap_coins {
Self::print_script_and_coin(multisig_redeemscript, swapcoin);
}
for (multisig_redeemscript, swapcoin) in &self.outgoing_swap_coins {
Self::print_script_and_coin(multisig_redeemscript, swapcoin);
}
println!(
"swapcoin count = {}",
self.incoming_swap_coins.len() + self.outgoing_swap_coins.len()
);
}
fn print_script_and_coin(script: &Script, coin: &dyn SwapCoin) {
let contract_tx = coin.get_contract_tx();
println!(
"{} {}:{} {}",
Address::p2wsh(script, NETWORK),
contract_tx.input[0].previous_output.txid,
contract_tx.input[0].previous_output.vout,
if coin.is_hash_preimage_known() {
" known"
} else {
"unknown"
}
)
}
pub fn save_new_wallet_file<P: AsRef<Path>>(
wallet_file_name: P,
seedphrase: String,
extension: String,
) -> Result<(), Error> {
let wallet_file_data = WalletFileData {
version: WALLET_FILE_VERSION,
seedphrase,
extension,
external_index: 0,
incoming_swap_coins: Vec::new(),
outgoing_swap_coins: Vec::new(),
prevout_to_contract_map: HashMap::<OutPoint, Script>::new(),
};
let wallet_file = File::create(wallet_file_name)?;
serde_json::to_writer(wallet_file, &wallet_file_data).map_err(|e| io::Error::from(e))?;
Ok(())
}
fn load_wallet_file_data<P: AsRef<Path>>(wallet_file_name: P) -> Result<WalletFileData, Error> {
let mut wallet_file = File::open(wallet_file_name)?;
let mut wallet_file_str = String::new();
wallet_file.read_to_string(&mut wallet_file_str)?;
Ok(serde_json::from_str::<WalletFileData>(&wallet_file_str)
.map_err(|e| io::Error::from(e))?)
}
pub fn load_wallet_from_file<P: AsRef<Path>>(wallet_file_name: P) -> Result<Wallet, Error> {
let wallet_file_name = wallet_file_name
.as_ref()
.as_os_str()
.to_string_lossy()
.to_string();
let wallet_file_data = Wallet::load_wallet_file_data(&wallet_file_name)?;
let mnemonic_ret = mnemonic::Mnemonic::from_str(&wallet_file_data.seedphrase);
if mnemonic_ret.is_err() {
return Err(Error::Disk(io::Error::new(
io::ErrorKind::Other,
"invalid seed phrase",
)));
}
let seed = mnemonic_ret
.unwrap()
.to_seed(Some(&wallet_file_data.extension));
let xprv = ExtendedPrivKey::new_master(NETWORK, &seed.0).unwrap();
let wallet = Wallet {
master_key: xprv,
wallet_file_name,
external_index: wallet_file_data.external_index,
incoming_swap_coins: wallet_file_data
.incoming_swap_coins
.iter()
.map(|sc| (sc.get_multisig_redeemscript(), sc.clone()))
.collect::<HashMap<Script, IncomingSwapCoin>>(),
outgoing_swap_coins: wallet_file_data
.outgoing_swap_coins
.iter()
.map(|sc| (sc.get_multisig_redeemscript(), sc.clone()))
.collect::<HashMap<Script, OutgoingSwapCoin>>(),
};
Ok(wallet)
}
pub fn update_external_index(&mut self, new_external_index: u32) -> Result<(), Error> {
self.external_index = new_external_index;
let mut wallet_file_data = Wallet::load_wallet_file_data(&self.wallet_file_name)?;
wallet_file_data.external_index = new_external_index;
let wallet_file = File::create(&self.wallet_file_name[..])?;
serde_json::to_writer(wallet_file, &wallet_file_data).map_err(|e| io::Error::from(e))?;
Ok(())
}
#[cfg(test)]
pub fn get_external_index(&self) -> u32 {
self.external_index
}
pub fn update_swap_coins_list(&self) -> Result<(), Error> {
let mut wallet_file_data = Wallet::load_wallet_file_data(&self.wallet_file_name)?;
wallet_file_data.incoming_swap_coins = self
.incoming_swap_coins
.values()
.cloned()
.collect::<Vec<IncomingSwapCoin>>();
wallet_file_data.outgoing_swap_coins = self
.outgoing_swap_coins
.values()
.cloned()
.collect::<Vec<OutgoingSwapCoin>>();
let wallet_file = File::create(&self.wallet_file_name[..])?;
serde_json::to_writer(wallet_file, &wallet_file_data).map_err(|e| io::Error::from(e))?;
Ok(())
}
pub fn find_incoming_swapcoin(
&self,
multisig_redeemscript: &Script,
) -> Option<&IncomingSwapCoin> {
self.incoming_swap_coins.get(multisig_redeemscript)
}
pub fn find_outgoing_swapcoin(
&self,
multisig_redeemscript: &Script,
) -> Option<&OutgoingSwapCoin> {
self.outgoing_swap_coins.get(multisig_redeemscript)
}
pub fn find_incoming_swapcoin_mut(
&mut self,
multisig_redeemscript: &Script,
) -> Option<&mut IncomingSwapCoin> {
self.incoming_swap_coins.get_mut(multisig_redeemscript)
}
pub fn find_outgoing_swapcoin_mut(
&mut self,
multisig_redeemscript: &Script,
) -> Option<&mut OutgoingSwapCoin> {
self.outgoing_swap_coins.get_mut(multisig_redeemscript)
}
pub fn add_incoming_swapcoin(&mut self, coin: IncomingSwapCoin) {
self.incoming_swap_coins
.insert(coin.get_multisig_redeemscript(), coin);
}
pub fn add_outgoing_swapcoin(&mut self, coin: OutgoingSwapCoin) {
self.outgoing_swap_coins
.insert(coin.get_multisig_redeemscript(), coin);
}
#[cfg(test)]
pub fn get_swap_coins_count(&self) -> usize {
self.incoming_swap_coins.len() + self.outgoing_swap_coins.len()
}
//this function is used in two places
//once when maker has received message signsendercontracttx
//again when maker receives message proofoffunding
//
//cases when receiving signsendercontracttx
//case 1: prevout in cache doesnt have any contract => ok
//case 2: prevout has a contract and it matches given contract => ok
//case 3: prevout has a contract and it doesnt match contract => reject
//
//cases when receiving proofoffunding
//case 1: prevout doesnt have an entry => weird, how did they get a sig
//case 2: prevout has an entry which matches contract => ok
//case 3: prevout has an entry which doesnt match contract => reject
//
//so the two cases are the same except for case 1 for proofoffunding which
//shouldnt happen at all
//
//only time it returns false is when prevout doesnt match cached contract
pub fn does_prevout_match_cached_contract(
&self,
prevout: &OutPoint,
contract_scriptpubkey: &Script,
) -> Result<bool, Error> {
let wallet_file_data = Wallet::load_wallet_file_data(&self.wallet_file_name[..])?;
Ok(
match wallet_file_data.prevout_to_contract_map.get(prevout) {
Some(c) => c == contract_scriptpubkey,
None => true,
},
)
}
pub fn add_prevout_and_contract_to_cache(
&mut self,
prevout: OutPoint,
contract: Script,
) -> Result<(), Error> {
let mut wallet_file_data = Wallet::load_wallet_file_data(&self.wallet_file_name[..])?;
wallet_file_data
.prevout_to_contract_map
.insert(prevout, contract);
let wallet_file = File::create(&self.wallet_file_name[..])?;
serde_json::to_writer(wallet_file, &wallet_file_data).map_err(|e| io::Error::from(e))?;
Ok(())
}
//pub fn get_recovery_phrase_from_file()
fn is_xpub_descriptor_imported(&self, rpc: &Client, descriptor: &str) -> Result<bool, Error> {
let first_addr = rpc.derive_addresses(&descriptor, Some([0, 0]))?[0].clone();
let last_index = (INITIAL_ADDRESS_IMPORT_COUNT - 1) as u32;
let last_addr =
rpc.derive_addresses(&descriptor, Some([last_index, last_index]))?[0].clone();
//this issue
// https://github.com/rust-bitcoin/rust-bitcoincore-rpc/issues/123
//means that we cant use get_address_info() instead we have to
// parse the json ourselves
let first_addr_imported = rpc.call::<serde_json::Value>(
"getaddressinfo",
&[Value::String(first_addr.to_string())],
)?["iswatchonly"]
.as_bool()
.unwrap();
let last_addr_imported = rpc
.call::<serde_json::Value>("getaddressinfo", &[Value::String(last_addr.to_string())])?
["iswatchonly"]
.as_bool()
.unwrap();
Ok(first_addr_imported && last_addr_imported)
}
fn is_swapcoin_descriptor_imported(&self, rpc: &Client, descriptor: &str) -> bool {
let addr = rpc.derive_addresses(&descriptor, None).unwrap()[0].clone();
rpc.call::<serde_json::Value>("getaddressinfo", &[Value::String(addr.to_string())])
.unwrap()["iswatchonly"]
.as_bool()
.unwrap()
}
pub fn get_hd_wallet_descriptors(&self, rpc: &Client) -> Result<Vec<String>, Error> {
let secp = Secp256k1::new();
let wallet_xpub = ExtendedPubKey::from_private(
&secp,
&self
.master_key
.derive_priv(&secp, &DerivationPath::from_str(DERIVATION_PATH).unwrap())
.unwrap(),
);
let address_type = [0, 1];
let descriptors: Result<Vec<String>, bitcoincore_rpc::Error> = address_type
.iter()
.map(|at| {
rpc.get_descriptor_info(&format!("wpkh({}/{}/*)", wallet_xpub, at))
.map(|getdescriptorinfo_result| getdescriptorinfo_result.descriptor)
})
.collect();
descriptors.map_err(|e| Error::Rpc(e))
}
fn get_core_wallet_label(&self) -> String {
let secp = Secp256k1::new();
let m_xpub = ExtendedPubKey::from_private(&secp, &self.master_key);
m_xpub.fingerprint().to_string()
}
pub fn import_initial_addresses(
&self,
rpc: &Client,
hd_descriptors_to_import: &[&String],
swapcoin_descriptors_to_import: &[String],
) -> Result<(), Error> {
let address_label = self.get_core_wallet_label();
let import_requests = hd_descriptors_to_import
.iter()
.map(|desc| ImportMultiRequest {
timestamp: ImportMultiRescanSince::Now,
descriptor: Some(desc),
range: Some((0, INITIAL_ADDRESS_IMPORT_COUNT - 1)),
watchonly: Some(true),
label: Some(&address_label),
..Default::default()
})
.chain(
swapcoin_descriptors_to_import
.iter()
.map(|desc| ImportMultiRequest {
timestamp: ImportMultiRescanSince::Now,
descriptor: Some(desc),
watchonly: Some(true),
label: Some(&address_label),
..Default::default()
}),
)
.collect::<Vec<ImportMultiRequest>>();
let result = rpc.import_multi(
&import_requests,
Some(&ImportMultiOptions {
rescan: Some(false),
}),
)?;
for r in result {
if !r.success {
return Err(Error::Rpc(bitcoincore_rpc::Error::UnexpectedStructure));
}
}
Ok(())
}
pub fn startup_sync(&mut self, rpc: &Client) -> Result<(), Error> {
//TODO many of these unwraps to be replaced with proper error handling
let hd_descriptors = self.get_hd_wallet_descriptors(rpc)?;
let hd_descriptors_to_import = hd_descriptors
.iter()
.filter(|d| !self.is_xpub_descriptor_imported(rpc, &d).unwrap())
.collect::<Vec<&String>>();
let mut swapcoin_descriptors_to_import = self
.incoming_swap_coins
.values()
.map(|sc| {
format!(
"wsh(sortedmulti(2,{},{}))",
sc.get_other_pubkey(),
sc.get_my_pubkey()
)
})
.map(|d| rpc.get_descriptor_info(&d).unwrap().descriptor)
.filter(|d| !self.is_swapcoin_descriptor_imported(rpc, &d))
.collect::<Vec<String>>();
swapcoin_descriptors_to_import.extend(
self.outgoing_swap_coins
.values()
.map(|sc| {
format!(
"wsh(sortedmulti(2,{},{}))",
sc.get_other_pubkey(),
sc.get_my_pubkey()
)
})
.map(|d| rpc.get_descriptor_info(&d).unwrap().descriptor)
.filter(|d| !self.is_swapcoin_descriptor_imported(rpc, &d)),
);
if hd_descriptors_to_import.is_empty() && swapcoin_descriptors_to_import.is_empty() {
return Ok(());
}
log::trace!(target: "wallet", "new wallet detected, synchronizing balance...");
self.import_initial_addresses(
rpc,
&hd_descriptors_to_import,
&swapcoin_descriptors_to_import,
)?;
rpc.call::<Value>("scantxoutset", &[json!("abort")])?;
let desc_list = hd_descriptors_to_import
.iter()
.map(|d| {
json!(
{"desc": d,
"range": INITIAL_ADDRESS_IMPORT_COUNT-1})
})
.chain(swapcoin_descriptors_to_import.iter().map(|d| json!(d)))
.collect::<Vec<Value>>();
let scantxoutset_result: Value =
rpc.call("scantxoutset", &[json!("start"), json!(desc_list)])?;
if !scantxoutset_result["success"].as_bool().unwrap() {
return Err(Error::Rpc(bitcoincore_rpc::Error::UnexpectedStructure));
}
for unspent in scantxoutset_result["unspents"].as_array().unwrap() {
let blockhash = rpc.get_block_hash(unspent["height"].as_u64().unwrap())?;
let txid = Txid::from_hex(unspent["txid"].as_str().unwrap()).unwrap();
let rawtx = rpc.get_raw_transaction_hex(&txid, Some(&blockhash));
if let Ok(rawtx_hex) = rawtx {
let merkleproof = rpc.get_tx_out_proof(&[txid], Some(&blockhash))?.to_hex();
rpc.call(
"importprunedfunds",
&[Value::String(rawtx_hex), Value::String(merkleproof)],
)?;
} else {
log::error!(target: "wallet", "block pruned, TODO add UTXO to wallet file");
panic!("teleport doesnt work with pruning yet, try rescanning");
}
}
let max_external_index = self.find_hd_next_index(rpc, 0)?;
self.update_external_index(max_external_index)?;
Ok(())
}
fn create_contract_scriptpubkey_swapcoin_hashmap(&self) -> HashMap<Script, &OutgoingSwapCoin> {
self.outgoing_swap_coins
.values()
.map(|osc| {
(
Address::p2wsh(&osc.contract_redeemscript, NETWORK).script_pubkey(),
osc,
)
})
.collect::<HashMap<Script, &OutgoingSwapCoin>>()
}
fn is_utxo_ours_and_spendable(
&self,
u: &ListUnspentResultEntry,
contract_scriptpubkeys_outgoing_swapcoins: &HashMap<Script, &OutgoingSwapCoin>,
) -> bool {
if u.descriptor.is_none() {
let swapcoin = contract_scriptpubkeys_outgoing_swapcoins.get(&u.script_pub_key);
if swapcoin.is_none() {
return false;
}
let swapcoin = swapcoin.unwrap();
let timelock = read_locktime_from_contract(&swapcoin.contract_redeemscript);
if timelock.is_none() {
return false;
}
let timelock = timelock.unwrap();
return u.confirmations >= timelock.into();
}
let descriptor = u.descriptor.as_ref().unwrap();
if let Some(ret) = self.get_hd_path_from_descriptor(&descriptor) {
//utxo is in a hd wallet
let (fingerprint, _, _) = ret;
let secp = Secp256k1::new();
let master_private_key = self
.master_key
.derive_priv(&secp, &DerivationPath::from_str(DERIVATION_PATH).unwrap())
.unwrap();
fingerprint == master_private_key.fingerprint(&secp).to_string()
} else {
//utxo might be one of our swapcoins
self.find_incoming_swapcoin(
u.witness_script
.as_ref()
.unwrap_or(&Script::from(Vec::from_hex("").unwrap())),
)
.map_or(false, |sc| sc.other_privkey.is_some())
|| self
.find_outgoing_swapcoin(
u.witness_script
.as_ref()
.unwrap_or(&Script::from(Vec::from_hex("").unwrap())),
)
.map_or(false, |sc| sc.hash_preimage.is_some())
}
}
pub fn lock_all_nonwallet_unspents(&self, rpc: &Client) -> Result<(), Error> {
//rpc.unlock_unspent(&[])?;
//https://github.com/rust-bitcoin/rust-bitcoincore-rpc/issues/148
rpc.call::<Value>("lockunspent", &[Value::Bool(true)])?;
let contract_scriptpubkeys_outgoing_swapcoins =
self.create_contract_scriptpubkey_swapcoin_hashmap();
let all_unspents = rpc.list_unspent(None, None, None, None, None)?;
let utxos_to_lock = &all_unspents
.into_iter()
.filter(|u| {
!self.is_utxo_ours_and_spendable(u, &contract_scriptpubkeys_outgoing_swapcoins)
})
.map(|u| OutPoint {
txid: u.txid,
vout: u.vout,
})
.collect::<Vec<OutPoint>>();
rpc.lock_unspent(utxos_to_lock)?;
Ok(())
}
pub fn list_unspent_from_wallet(
&self,
rpc: &Client,
) -> Result<Vec<ListUnspentResultEntry>, Error> {
let contract_scriptpubkeys_outgoing_swapcoins =
self.create_contract_scriptpubkey_swapcoin_hashmap();
rpc.call::<Value>("lockunspent", &[Value::Bool(true)])
.map_err(|e| Error::Rpc(e))?;
Ok(rpc
.list_unspent(None, None, None, None, None)?
.iter()
.filter(|u| {
self.is_utxo_ours_and_spendable(u, &contract_scriptpubkeys_outgoing_swapcoins)
})
.cloned()
.collect::<Vec<ListUnspentResultEntry>>())
}
pub fn find_incomplete_coinswaps(
&self,
rpc: &Client,
) -> Result<
HashMap<
Hash160,
(
Vec<(ListUnspentResultEntry, &IncomingSwapCoin)>,
Vec<(ListUnspentResultEntry, &OutgoingSwapCoin)>,
),
>,
Error,
> {
rpc.call::<Value>("lockunspent", &[Value::Bool(true)])
.map_err(|e| Error::Rpc(e))?;
let completed_coinswap_hashvalues = self
.incoming_swap_coins
.values()
.filter(|sc| sc.other_privkey.is_some())
.map(|sc| read_hashvalue_from_contract(&sc.contract_redeemscript).unwrap())
.collect::<HashSet<Hash160>>();
//TODO make this read_hashvalue_from_contract() a struct function of WalletCoinSwap
let mut incomplete_swapcoin_groups = HashMap::<
Hash160,
(
Vec<(ListUnspentResultEntry, &IncomingSwapCoin)>,
Vec<(ListUnspentResultEntry, &OutgoingSwapCoin)>,
),
>::new();
let get_hashvalue = |s: &dyn SwapCoin| {
if s.is_hash_preimage_known() {
return None;
}
let swapcoin_hashvalue = read_hashvalue_from_contract(&s.get_contract_redeemscript())
.expect("unable to read hashvalue from contract_redeemscript");
if completed_coinswap_hashvalues.contains(&swapcoin_hashvalue) {
return None;
}
Some(swapcoin_hashvalue)
};
for utxo in rpc.list_unspent(None, None, None, None, None)? {
if utxo.descriptor.is_none() {
continue;
}
let multisig_redeemscript = if let Some(rs) = utxo.witness_script.as_ref() {
rs
} else {
continue;
};
if let Some(s) = self.find_incoming_swapcoin(multisig_redeemscript) {
if let Some(swapcoin_hashvalue) = get_hashvalue(s) {
incomplete_swapcoin_groups
.entry(swapcoin_hashvalue)
.or_insert((
Vec::<(ListUnspentResultEntry, &IncomingSwapCoin)>::new(),
Vec::<(ListUnspentResultEntry, &OutgoingSwapCoin)>::new(),
))
.0
.push((utxo, s));
}
} else if let Some(s) = self.find_outgoing_swapcoin(multisig_redeemscript) {
if let Some(swapcoin_hashvalue) = get_hashvalue(s) {
incomplete_swapcoin_groups
.entry(swapcoin_hashvalue)
.or_insert((
Vec::<(ListUnspentResultEntry, &IncomingSwapCoin)>::new(),
Vec::<(ListUnspentResultEntry, &OutgoingSwapCoin)>::new(),
))
.1
.push((utxo, s));
}
} else {
continue;
};
}
Ok(incomplete_swapcoin_groups)
}
// live contract refers to a contract tx which has been broadcast
// i.e. where there are UTXOs protected by contract_redeemscript's that we know about
pub fn find_live_contract_unspents(
&self,
rpc: &Client,
) -> Result<
(
Vec<(&IncomingSwapCoin, ListUnspentResultEntry)>,
Vec<(&OutgoingSwapCoin, ListUnspentResultEntry)>,
),
Error,
> {
// populate hashmaps where key is contract scriptpubkey and value is the swapcoin
let contract_scriptpubkeys_incoming_swapcoins = self
.incoming_swap_coins
.values()
.map(|isc| {
(
Address::p2wsh(&isc.contract_redeemscript, NETWORK).script_pubkey(),
isc,
)
})
.collect::<HashMap<Script, &IncomingSwapCoin>>();
let contract_scriptpubkeys_outgoing_swapcoins =
self.create_contract_scriptpubkey_swapcoin_hashmap();
rpc.call::<Value>("lockunspent", &[Value::Bool(true)])
.map_err(|e| Error::Rpc(e))?;
let listunspent = rpc.list_unspent(None, None, None, None, None)?;
let (incoming_swap_coins_utxos, outgoing_swap_coins_utxos): (Vec<_>, Vec<_>) = listunspent
.iter()
.map(|u| {
(
contract_scriptpubkeys_incoming_swapcoins.get(&u.script_pub_key),
contract_scriptpubkeys_outgoing_swapcoins.get(&u.script_pub_key),
u,
)
})
.filter(|isc_osc_u| isc_osc_u.0.is_some() || isc_osc_u.1.is_some())
.partition(|isc_osc_u| isc_osc_u.0.is_some());
Ok((
incoming_swap_coins_utxos
.iter()
.map(|isc_osc_u| (*isc_osc_u.0.unwrap(), isc_osc_u.2.clone()))
.collect::<Vec<(&IncomingSwapCoin, ListUnspentResultEntry)>>(),
outgoing_swap_coins_utxos
.iter()
.map(|isc_osc_u| (*isc_osc_u.1.unwrap(), isc_osc_u.2.clone()))
.collect::<Vec<(&OutgoingSwapCoin, ListUnspentResultEntry)>>(),
))
}
// returns None if not a hd descriptor (but possibly a swapcoin (multisig) descriptor instead)
fn get_hd_path_from_descriptor<'a>(&self, descriptor: &'a str) -> Option<(&'a str, u32, i32)> {
//e.g
//"desc": "wpkh([a945b5ca/1/1]029b77637989868dcd502dbc07d6304dc2150301693ae84a60b379c3b696b289ad)#aq759em9",
let open = descriptor.find('[');
let close = descriptor.find(']');
if open.is_none() || close.is_none() {
//unexpected, so printing it to stdout
println!("unknown descriptor = {}", descriptor);
return None;
}
let path = &descriptor[open.unwrap() + 1..close.unwrap()];
let path_chunks: Vec<&str> = path.split('/').collect();
if path_chunks.len() != 3 {
return None;
//unexpected descriptor = wsh(multi(2,[f67b69a3]0245ddf535f08a04fd86d794b76f8e3949f27f7ae039b641bf277c6a4552b4c387,[dbcd3c6e]030f781e9d2a6d3a823cee56be2d062ed4269f5a6294b20cb8817eb540c641d9a2))#8f70vn2q
}
let addr_type = path_chunks[1].parse::<u32>();
if addr_type.is_err() {
log::trace!(target: "wallet", "unexpected address_type = {}", path);
return None;
}
let index = path_chunks[2].parse::<i32>();
if index.is_err() {
return None;
}
Some((path_chunks[0], addr_type.unwrap(), index.unwrap()))
}
fn find_hd_next_index(&self, rpc: &Client, address_type: u32) -> Result<u32, Error> {
let mut max_index: i32 = -1;
//TODO error handling
let utxos = self.list_unspent_from_wallet(rpc)?;
for utxo in utxos {
if utxo.descriptor.is_none() {
continue;
}
let descriptor = utxo.descriptor.unwrap();
let ret = self.get_hd_path_from_descriptor(&descriptor);
if ret.is_none() {
continue;
}
let (_, addr_type, index) = ret.unwrap();
if addr_type != address_type {
continue;
}
max_index = std::cmp::max(max_index, index);
}
Ok((max_index + 1) as u32)
}
pub fn get_next_external_address(&mut self, rpc: &Client) -> Result<Address, Error> {
let receive_branch_descriptor = &self.get_hd_wallet_descriptors(rpc)?[0];
let receive_address = rpc.derive_addresses(
receive_branch_descriptor,
Some([self.external_index, self.external_index]),
)?[0]
.clone();
self.update_external_index(self.external_index + 1)?;
Ok(receive_address)
}
pub fn get_offer_maxsize(&self, rpc: Arc<Client>) -> Result<u64, Error> {
let utxos = self.list_unspent_from_wallet(&rpc)?;
let balance: Amount = utxos.iter().fold(Amount::ZERO, |acc, u| acc + u.amount);
Ok(balance.as_sat())
}