-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathimplementation.rs
More file actions
2037 lines (1807 loc) · 73.8 KB
/
Copy pathimplementation.rs
File metadata and controls
2037 lines (1807 loc) · 73.8 KB
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
use std::any::Any;
use std::collections::{HashMap, HashSet};
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::str::FromStr;
use base64::{engine::general_purpose, Engine as _};
use bdk::bitcoin::absolute::LockTime;
use bdk::bitcoin::bip32::{
DerivationPath as BdkDerivationPath, ExtendedPrivKey as BdkExtendedPrivKey, ExtendedPubKey,
};
use bdk::bitcoin::consensus::{deserialize, serialize};
use bdk::bitcoin::psbt::PartiallySignedTransaction as Psbt;
use bdk::bitcoin::secp256k1::Secp256k1;
use bdk::bitcoin::{
Address as BdkAddress, Network as BdkNetwork, OutPoint, PrivateKey as BdkPrivateKey,
PublicKey as BdkPublicKey, ScriptBuf, Sequence, Transaction, TxIn, TxOut, Txid, Witness,
};
use bdk::blockchain::ElectrumBlockchain;
use bdk::database::MemoryDatabase;
use bdk::electrum_client::ElectrumApi;
use bdk::keys::bip39::Mnemonic as BdkMnemonic;
use bdk::template::{Bip44, Bip49, Bip86, P2Wpkh};
use bdk::wallet::signer::SignOptions;
use bdk::wallet::{AddressIndex as BdkAddressIndex, SyncOptions, Wallet};
use bdk::KeychainKind;
use bip39::Mnemonic as Bip39Mnemonic;
use bitcoin::address::{Address, NetworkUnchecked};
use bitcoin::bip32::{DerivationPath, Xpriv, Xpub};
use bitcoin::{Network, NetworkKind};
use bitcoin_address_generator;
use super::errors::AccountInfoError;
use super::types::{
classify_tx, AccountAddresses, AccountInfoResult, AccountType, AccountUtxo, AddressInfo,
AddressType, ComposeAccount, HistoryTransaction, LegacyRnCloseRecoveryScanResult,
LegacyRnCloseRecoverySweepPreview, Network as OnchainNetwork, SingleAddressInfoResult,
TransactionDetail, TransactionHistoryResult, TxDetailInput, TxDetailOutput, ValidationResult,
WalletBalance,
};
use crate::modules::scanner::NetworkType;
use crate::onchain::types::{
GetAddressResponse, GetAddressesResponse, SweepResult, SweepTransactionPreview,
SweepableBalances, WordCount,
};
use crate::onchain::{AddressError, BroadcastError, SweepError};
struct SweepWallets {
legacy_wallet: Wallet<MemoryDatabase>,
p2sh_wallet: Wallet<MemoryDatabase>,
taproot_wallet: Wallet<MemoryDatabase>,
}
pub struct BitcoinAddressValidator;
impl BitcoinAddressValidator {
pub fn validate_address(address: &str) -> Result<ValidationResult, AddressError> {
println!("\nValidating address: {}", address);
let unchecked_addr = match parse_address(address) {
Ok(addr) => addr,
Err(e) => return Err(e),
};
let expected_network = match determine_network(address) {
Ok(n) => n,
Err(e) => return Err(e),
};
match verify_network(unchecked_addr, expected_network.into()) {
Ok(_) => {}
Err(e) => return Err(e),
}
let address_type = get_address_type(address)?;
println!("✓ Validation successful!");
Ok(ValidationResult {
address: address.to_string(),
network: NetworkType::from(expected_network),
address_type,
})
}
pub fn genenerate_mnemonic(word_count: Option<WordCount>) -> Result<String, AddressError> {
let external_word_count = word_count.map(|wc| wc.into());
let mnemonic = bitcoin_address_generator::generate_mnemonic(external_word_count, None);
match mnemonic {
Ok(mnemonic) => {
println!("✓ Generated mnemonic: {}", mnemonic);
Ok(mnemonic)
}
Err(e) => {
println!("✗ Failed to generate mnemonic: {:?}", e);
Err(AddressError::MnemonicGenerationFailed)
}
}
}
pub fn validate_mnemonic(mnemonic_phrase: &str) -> Result<(), AddressError> {
bitcoin_address_generator::validate_mnemonic(mnemonic_phrase)
.map_err(|_| AddressError::InvalidMnemonic)
}
pub fn is_valid_bip39_word(word: &str) -> bool {
bitcoin_address_generator::is_valid_bip39_word(word, None)
}
pub fn get_bip39_suggestions(partial_word: &str, limit: usize) -> Vec<String> {
bitcoin_address_generator::get_bip39_suggestions(partial_word, limit, None)
}
pub fn get_bip39_wordlist() -> Vec<String> {
bitcoin_address_generator::get_bip39_wordlist(None)
}
pub fn mnemonic_to_entropy(mnemonic_phrase: &str) -> Result<Vec<u8>, AddressError> {
bitcoin_address_generator::mnemonic_to_entropy(mnemonic_phrase)
.map_err(|_| AddressError::InvalidMnemonic)
}
pub fn entropy_to_mnemonic(entropy: &[u8]) -> Result<String, AddressError> {
bitcoin_address_generator::entropy_to_mnemonic(entropy, None)
.map_err(|_| AddressError::InvalidEntropy)
}
pub fn mnemonic_to_seed(
mnemonic_phrase: &str,
passphrase: Option<&str>,
) -> Result<Vec<u8>, AddressError> {
bitcoin_address_generator::mnemonic_to_seed(mnemonic_phrase, passphrase)
.map_err(|_| AddressError::InvalidMnemonic)
}
pub fn derive_bitcoin_address(
mnemonic_phrase: &str,
derivation_path_str: Option<&str>,
network: Option<Network>,
bip39_passphrase: Option<&str>,
) -> Result<GetAddressResponse, AddressError> {
let address = bitcoin_address_generator::derive_bitcoin_address(
mnemonic_phrase,
derivation_path_str,
network.into(),
bip39_passphrase,
)
.map_err(|e| {
println!("✗ Failed to derive address: {:?}", e);
AddressError::AddressDerivationFailed
})?;
Ok(address.into())
}
pub fn derive_bitcoin_addresses(
mnemonic_phrase: &str,
derivation_path_str: Option<&str>,
network: Option<Network>,
bip39_passphrase: Option<&str>,
is_change: Option<bool>,
start_index: Option<u32>,
count: Option<u32>,
) -> Result<GetAddressesResponse, AddressError> {
let addresses = bitcoin_address_generator::derive_bitcoin_addresses(
mnemonic_phrase,
derivation_path_str,
network.into(),
bip39_passphrase,
is_change,
start_index,
count,
)
.map_err(|e| {
println!("✗ Failed to derive addresses: {:?}", e);
AddressError::AddressDerivationFailed
})?;
Ok(addresses.into())
}
pub fn derive_private_key(
mnemonic_phrase: &str,
derivation_path_str: Option<&str>,
network: Option<Network>,
bip39_passphrase: Option<&str>,
) -> Result<String, AddressError> {
let private_key = bitcoin_address_generator::derive_private_key(
mnemonic_phrase,
derivation_path_str,
network.into(),
bip39_passphrase,
)
.map_err(|e| {
println!("✗ Failed to derive private key: {:?}", e);
AddressError::AddressDerivationFailed
})?;
Ok(private_key)
}
pub fn derive_onchain_descriptor(
mnemonic_phrase: &str,
network: Network,
bip39_passphrase: Option<&str>,
account_type: AccountType,
account_index: u32,
) -> Result<String, AddressError> {
let bdk_network = onchain_to_bdk_network(network.into());
let derivation_path = derive_base_path(account_type, bdk_network, account_index);
let mnemonic =
Bip39Mnemonic::parse(mnemonic_phrase).map_err(|_| AddressError::InvalidMnemonic)?;
let seed = mnemonic.to_seed(bip39_passphrase.unwrap_or(""));
let path = DerivationPath::from_str(&derivation_path)
.map_err(|_| AddressError::AddressDerivationFailed)?;
let secp = bitcoin::secp256k1::Secp256k1::new();
let root =
Xpriv::new_master(network, &seed).map_err(|_| AddressError::AddressDerivationFailed)?;
let account = root
.derive_priv(&secp, &path)
.map_err(|_| AddressError::AddressDerivationFailed)?;
let master_fingerprint = root.fingerprint(&secp).to_string();
let mut account_xpub = Xpub::from_priv(&secp, &account);
// Export standard xpub descriptors; the key origin path still carries
// the selected network's coin type.
account_xpub.network = NetworkKind::Main;
let account_xpub = account_xpub.to_string();
let key_origin_path = derivation_path
.strip_prefix("m/")
.unwrap_or(&derivation_path);
let (external_descriptor, _) = build_descriptors(
&account_xpub,
account_type,
Some((&master_fingerprint, key_origin_path)),
);
Ok(external_descriptor)
}
fn create_sweep_wallets(
mnemonic_phrase: &str,
network: Network,
bip39_passphrase: Option<&str>,
) -> Result<SweepWallets, SweepError> {
let bdk_network = onchain_to_bdk_network(network.into());
let mnemonic =
BdkMnemonic::from_str(mnemonic_phrase).map_err(|_| SweepError::InvalidMnemonic)?;
let key = (mnemonic.clone(), bip39_passphrase.map(String::from));
let legacy_wallet = Wallet::new(
Bip44(key.clone(), KeychainKind::External),
Some(Bip44(key.clone(), KeychainKind::Internal)),
bdk_network,
MemoryDatabase::new(),
)
.map_err(|e| SweepError::SweepFailed(format!("Failed to create legacy wallet: {}", e)))?;
let p2sh_wallet = Wallet::new(
Bip49(key.clone(), KeychainKind::External),
Some(Bip49(key.clone(), KeychainKind::Internal)),
bdk_network,
MemoryDatabase::new(),
)
.map_err(|e| SweepError::SweepFailed(format!("Failed to create P2SH wallet: {}", e)))?;
let taproot_wallet = Wallet::new(
Bip86(key.clone(), KeychainKind::External),
Some(Bip86(key, KeychainKind::Internal)),
bdk_network,
MemoryDatabase::new(),
)
.map_err(|e| SweepError::SweepFailed(format!("Failed to create Taproot wallet: {}", e)))?;
Ok(SweepWallets {
legacy_wallet,
p2sh_wallet,
taproot_wallet,
})
}
fn create_electrum_client(
electrum_url: &str,
) -> Result<bdk::electrum_client::Client, SweepError> {
bdk::electrum_client::Client::new(electrum_url)
.map_err(|e| SweepError::SweepFailed(format!("Failed to connect to Electrum: {}", e)))
}
fn create_electrum_backend(electrum_url: &str) -> Result<ElectrumBlockchain, SweepError> {
let client = Self::create_electrum_client(electrum_url)?;
Ok(ElectrumBlockchain::from(client))
}
fn sync_wallets(
wallets: &mut SweepWallets,
backend: &ElectrumBlockchain,
) -> Result<(), SweepError> {
wallets
.legacy_wallet
.sync(backend, SyncOptions::default())
.map_err(|e| SweepError::SweepFailed(format!("Failed to sync legacy wallet: {}", e)))?;
wallets
.p2sh_wallet
.sync(backend, SyncOptions::default())
.map_err(|e| SweepError::SweepFailed(format!("Failed to sync P2SH wallet: {}", e)))?;
wallets
.taproot_wallet
.sync(backend, SyncOptions::default())
.map_err(|e| {
SweepError::SweepFailed(format!("Failed to sync Taproot wallet: {}", e))
})?;
Ok(())
}
fn sign_psbt(wallets: &SweepWallets, psbt: &mut Psbt) -> Result<(), SweepError> {
let sign_options = SignOptions {
trust_witness_utxo: true,
allow_all_sighashes: true,
..Default::default()
};
wallets
.legacy_wallet
.sign(psbt, sign_options.clone())
.map_err(|e| {
SweepError::SweepFailed(format!("Failed to sign with legacy wallet: {}", e))
})?;
wallets
.p2sh_wallet
.sign(psbt, sign_options.clone())
.map_err(|e| {
SweepError::SweepFailed(format!("Failed to sign with P2SH wallet: {}", e))
})?;
wallets
.taproot_wallet
.sign(psbt, sign_options)
.map_err(|e| {
SweepError::SweepFailed(format!("Failed to sign with Taproot wallet: {}", e))
})?;
Ok(())
}
}
// ------------------------------------------------------------------------
// Legacy RN P2WPKH-from-legacy-or-nested-key close recovery
// ------------------------------------------------------------------------
// One-time recovery path for legacy React Native channel close funds that were
// paid to P2WPKH scripts derived from legacy or nested-SegWit selected keys.
pub(super) struct LegacyRnNativeSegwitRecoverySpendable {
pub(super) derivation_path: String,
pub(super) txid: String,
pub(super) vout: u32,
pub(super) output: TxOut,
}
impl BitcoinAddressValidator {
pub(super) fn legacy_rn_p2wpkh_from_selected_purpose_script_map(
mnemonic_phrase: &str,
index_limit: u32,
network: Network,
bip39_passphrase: Option<&str>,
) -> Result<HashMap<Vec<u8>, String>, SweepError> {
let bdk_network = onchain_to_bdk_network(network.into());
let mnemonic =
Bip39Mnemonic::from_str(mnemonic_phrase).map_err(|_| SweepError::InvalidMnemonic)?;
let seed = mnemonic.to_seed(bip39_passphrase.unwrap_or(""));
let secp = Secp256k1::new();
let master = BdkExtendedPrivKey::new_master(bdk_network, &seed).map_err(|e| {
SweepError::SweepFailed(format!("Failed to derive legacy RN master key: {}", e))
})?;
let mut scripts = HashMap::new();
let coin_type = if network == Network::Bitcoin { 0 } else { 1 };
for purpose in [44, 49] {
for index in 0..index_limit {
for chain in 0..=1 {
let derivation_path =
format!("m/{}'/{}'/0'/{}/{}", purpose, coin_type, chain, index);
let child_path =
BdkDerivationPath::from_str(&derivation_path).map_err(|e| {
SweepError::SweepFailed(format!(
"Invalid legacy RN derivation path {}: {}",
derivation_path, e
))
})?;
let child = master.derive_priv(&secp, &child_path).map_err(|e| {
SweepError::SweepFailed(format!(
"Failed to derive legacy RN private key {}: {}",
derivation_path, e
))
})?;
let public_key =
BdkPublicKey::new(bdk::bitcoin::secp256k1::PublicKey::from_secret_key(
&secp,
&child.private_key,
));
let script =
ScriptBuf::new_v0_p2wpkh(&public_key.wpubkey_hash().ok_or_else(|| {
SweepError::SweepFailed(format!(
"Legacy RN public key {} is not compressed",
derivation_path
))
})?);
scripts.insert(script.to_bytes(), derivation_path);
}
}
}
Ok(scripts)
}
fn legacy_rn_native_segwit_recovery_spendables(
mnemonic_phrase: &str,
network: Network,
electrum_client: &bdk::electrum_client::Client,
index_limit: u32,
bip39_passphrase: Option<&str>,
) -> Result<Vec<LegacyRnNativeSegwitRecoverySpendable>, SweepError> {
let scripts = Self::legacy_rn_p2wpkh_from_selected_purpose_script_map(
mnemonic_phrase,
index_limit,
network,
bip39_passphrase,
)?;
let mut spendables = Vec::new();
let mut seen_outpoints = HashSet::new();
let script_entries = scripts.into_iter().collect::<Vec<_>>();
for chunk in script_entries.chunks(100) {
let electrum_scripts = chunk
.iter()
.map(|(script_pubkey, _)| ScriptBuf::from_bytes(script_pubkey.clone()))
.collect::<Vec<_>>();
let electrum_script_refs = electrum_scripts
.iter()
.map(|script| script.as_script())
.collect::<Vec<_>>();
let unspent_batches = electrum_client
.batch_script_list_unspent(electrum_script_refs)
.map_err(|e| {
SweepError::SweepFailed(format!(
"Failed to scan legacy RN recovery addresses: {}",
e
))
})?;
for ((script_pubkey, derivation_path), unspent_outputs) in
chunk.iter().zip(unspent_batches.into_iter())
{
for utxo in unspent_outputs {
let vout_u32 = u32::try_from(utxo.tx_pos).map_err(|_| {
SweepError::SweepFailed(format!(
"Legacy RN recovery output index {} is invalid",
utxo.tx_pos
))
})?;
let outpoint_key = format!("{}:{}", utxo.tx_hash, utxo.tx_pos);
if !seen_outpoints.insert(outpoint_key) {
continue;
}
spendables.push(LegacyRnNativeSegwitRecoverySpendable {
derivation_path: derivation_path.clone(),
txid: utxo.tx_hash.to_string(),
vout: vout_u32,
output: TxOut {
value: utxo.value,
script_pubkey: ScriptBuf::from_bytes(script_pubkey.clone()),
},
});
}
}
}
Ok(spendables)
}
fn sign_legacy_rn_native_segwit_recovery_psbt(
psbt: &mut Psbt,
spendables: &[LegacyRnNativeSegwitRecoverySpendable],
mnemonic_phrase: &str,
network: Network,
bip39_passphrase: Option<&str>,
) -> Result<(), SweepError> {
let bdk_network = onchain_to_bdk_network(network.into());
let mnemonic =
Bip39Mnemonic::from_str(mnemonic_phrase).map_err(|_| SweepError::InvalidMnemonic)?;
let seed = mnemonic.to_seed(bip39_passphrase.unwrap_or(""));
let secp = Secp256k1::new();
let master = BdkExtendedPrivKey::new_master(bdk_network, &seed).map_err(|e| {
SweepError::SweepFailed(format!("Failed to derive legacy RN master key: {}", e))
})?;
let sign_options = SignOptions {
trust_witness_utxo: true,
allow_all_sighashes: true,
..Default::default()
};
for item in spendables {
let derivation_path =
BdkDerivationPath::from_str(&item.derivation_path).map_err(|e| {
SweepError::SweepFailed(format!(
"Invalid legacy RN derivation path {}: {}",
item.derivation_path, e
))
})?;
let child = master.derive_priv(&secp, &derivation_path).map_err(|e| {
SweepError::SweepFailed(format!(
"Failed to derive legacy RN private key {}: {}",
item.derivation_path, e
))
})?;
let public_key = BdkPublicKey::new(
bdk::bitcoin::secp256k1::PublicKey::from_secret_key(&secp, &child.private_key),
);
let expected_script =
ScriptBuf::new_v0_p2wpkh(&public_key.wpubkey_hash().ok_or_else(|| {
SweepError::SweepFailed(format!(
"Legacy RN public key {} is not compressed",
item.derivation_path
))
})?);
if expected_script != item.output.script_pubkey {
return Err(SweepError::SweepFailed(format!(
"Derived script for {} does not match recovery output {}:{}",
item.derivation_path, item.txid, item.vout
)));
}
let wallet = Wallet::new(
P2Wpkh(BdkPrivateKey::new(child.private_key, bdk_network)),
None,
bdk_network,
MemoryDatabase::new(),
)
.map_err(|e| {
SweepError::SweepFailed(format!(
"Failed to create recovery signer for {}: {}",
item.derivation_path, e
))
})?;
wallet.ensure_addresses_cached(1).map_err(|e| {
SweepError::SweepFailed(format!(
"Failed to cache recovery signer address {}: {}",
item.derivation_path, e
))
})?;
wallet.sign(psbt, sign_options.clone()).map_err(|e| {
SweepError::SweepFailed(format!(
"Failed to sign recovery output {}:{}: {}",
item.txid, item.vout, e
))
})?;
}
for input in &psbt.inputs {
if input.final_script_sig.is_none() && input.final_script_witness.is_none() {
return Err(SweepError::SweepFailed(
"Recovery transaction signing incomplete - some inputs not finalized"
.to_string(),
));
}
}
Ok(())
}
pub(super) fn build_legacy_rn_native_segwit_recovery_sweep_tx(
mnemonic_phrase: &str,
spendables: &[LegacyRnNativeSegwitRecoverySpendable],
network: Network,
destination_address: &str,
fee_rate_sats_per_vbyte: Option<u32>,
bip39_passphrase: Option<&str>,
) -> Result<LegacyRnCloseRecoverySweepPreview, SweepError> {
if spendables.is_empty() {
return Err(SweepError::NoUtxosFound);
}
let bdk_network = onchain_to_bdk_network(network.into());
let dest_addr = BdkAddress::from_str(destination_address)
.map_err(|e| SweepError::SweepFailed(format!("Invalid destination address: {}", e)))?
.require_network(bdk_network)
.map_err(|e| {
SweepError::SweepFailed(format!("Network mismatch for destination address: {}", e))
})?;
let total_amount = spendables.iter().map(|item| item.output.value).sum::<u64>();
let fee_rate_sats = fee_rate_sats_per_vbyte.unwrap_or(1) as u64;
let build_psbt = |output_value: u64| -> Result<Psbt, SweepError> {
let inputs = spendables
.iter()
.map(|item| {
let txid = Txid::from_str(&item.txid).map_err(|e| {
SweepError::SweepFailed(format!(
"Invalid legacy RN recovery txid {}: {}",
item.txid, e
))
})?;
Ok(TxIn {
previous_output: OutPoint {
txid,
vout: item.vout,
},
script_sig: ScriptBuf::new(),
sequence: Sequence::MAX,
witness: Witness::new(),
})
})
.collect::<Result<Vec<_>, SweepError>>()?;
let tx = Transaction {
version: 2,
lock_time: LockTime::from_consensus(0),
input: inputs,
output: vec![TxOut {
value: output_value,
script_pubkey: dest_addr.script_pubkey(),
}],
};
let mut psbt = Psbt::from_unsigned_tx(tx)
.map_err(|e| SweepError::SweepFailed(format!("Failed to create PSBT: {}", e)))?;
for (input, item) in psbt.inputs.iter_mut().zip(spendables.iter()) {
input.witness_utxo = Some(item.output.clone());
}
Ok(psbt)
};
let mut probe_psbt = build_psbt(total_amount)?;
Self::sign_legacy_rn_native_segwit_recovery_psbt(
&mut probe_psbt,
spendables,
mnemonic_phrase,
network,
bip39_passphrase,
)?;
let estimated_vsize = probe_psbt.extract_tx().weight().to_vbytes_ceil();
let estimated_fee = estimated_vsize.saturating_mul(fee_rate_sats);
if estimated_fee >= total_amount {
return Err(SweepError::SweepFailed(format!(
"Recovery amount {} sats is too small to sweep at {} sat/vB",
total_amount, fee_rate_sats
)));
}
let amount_after_fees = total_amount - estimated_fee;
let mut final_psbt = build_psbt(amount_after_fees)?;
Self::sign_legacy_rn_native_segwit_recovery_psbt(
&mut final_psbt,
spendables,
mnemonic_phrase,
network,
bip39_passphrase,
)?;
let tx = final_psbt.extract_tx();
Ok(LegacyRnCloseRecoverySweepPreview {
tx_hex: hex::encode(serialize(&tx)),
txid: tx.txid().to_string(),
total_amount,
estimated_fee,
estimated_vsize,
outputs_count: u32::try_from(spendables.len()).unwrap_or(u32::MAX),
destination_address: destination_address.to_string(),
amount_after_fees,
})
}
pub async fn scan_legacy_rn_native_segwit_recovery_funds(
mnemonic_phrase: &str,
network: Network,
electrum_url: &str,
index_limit: u32,
bip39_passphrase: Option<&str>,
) -> Result<LegacyRnCloseRecoveryScanResult, SweepError> {
let mnemonic_phrase = mnemonic_phrase.to_string();
let electrum_url = electrum_url.to_string();
let bip39_passphrase = bip39_passphrase.map(str::to_string);
tokio::task::spawn_blocking(move || {
let electrum_client = Self::create_electrum_client(&electrum_url)?;
let spendables = Self::legacy_rn_native_segwit_recovery_spendables(
&mnemonic_phrase,
network,
&electrum_client,
index_limit,
bip39_passphrase.as_deref(),
)?;
Ok::<_, SweepError>(LegacyRnCloseRecoveryScanResult {
total_amount: spendables.iter().map(|item| item.output.value).sum(),
outputs_count: u32::try_from(spendables.len()).unwrap_or(u32::MAX),
})
})
.await
.map_err(|e| {
SweepError::SweepFailed(format!("Legacy RN recovery scan task failed: {}", e))
})?
}
pub async fn prepare_legacy_rn_native_segwit_recovery_sweep(
mnemonic_phrase: &str,
network: Network,
electrum_url: &str,
destination_address: &str,
fee_rate_sats_per_vbyte: Option<u32>,
index_limit: u32,
bip39_passphrase: Option<&str>,
) -> Result<LegacyRnCloseRecoverySweepPreview, SweepError> {
let mnemonic_phrase = mnemonic_phrase.to_string();
let electrum_url = electrum_url.to_string();
let destination_address = destination_address.to_string();
let bip39_passphrase = bip39_passphrase.map(str::to_string);
tokio::task::spawn_blocking(move || {
let electrum_client = Self::create_electrum_client(&electrum_url)?;
let spendables = Self::legacy_rn_native_segwit_recovery_spendables(
&mnemonic_phrase,
network,
&electrum_client,
index_limit,
bip39_passphrase.as_deref(),
)?;
Self::build_legacy_rn_native_segwit_recovery_sweep_tx(
&mnemonic_phrase,
&spendables,
network,
&destination_address,
fee_rate_sats_per_vbyte,
bip39_passphrase.as_deref(),
)
})
.await
.map_err(|e| {
SweepError::SweepFailed(format!("Legacy RN recovery sweep task failed: {}", e))
})?
}
// ------------------------------------------------------------------------
// Standard wallet sweep
// ------------------------------------------------------------------------
pub async fn check_sweepable_balances(
mnemonic_phrase: &str,
network: Network,
bip39_passphrase: Option<&str>,
electrum_url: &str,
) -> Result<SweepableBalances, SweepError> {
let wallets = Self::create_sweep_wallets(mnemonic_phrase, network, bip39_passphrase)?;
let electrum_url = electrum_url.to_string();
let wallets = tokio::task::spawn_blocking(move || {
let backend = Self::create_electrum_backend(&electrum_url)?;
let mut wallets = wallets;
Self::sync_wallets(&mut wallets, &backend)?;
Ok::<_, SweepError>(wallets)
})
.await
.map_err(|e| SweepError::SweepFailed(format!("Sync task failed: {}", e)))??;
let legacy_utxos = wallets
.legacy_wallet
.list_unspent()
.map_err(|e| SweepError::SweepFailed(format!("Failed to list legacy UTXOs: {}", e)))?;
let p2sh_utxos = wallets
.p2sh_wallet
.list_unspent()
.map_err(|e| SweepError::SweepFailed(format!("Failed to list P2SH UTXOs: {}", e)))?;
let taproot_utxos = wallets
.taproot_wallet
.list_unspent()
.map_err(|e| SweepError::SweepFailed(format!("Failed to list Taproot UTXOs: {}", e)))?;
let legacy_balance: u64 = legacy_utxos.iter().map(|u| u.txout.value).sum();
let p2sh_balance: u64 = p2sh_utxos.iter().map(|u| u.txout.value).sum();
let taproot_balance: u64 = taproot_utxos.iter().map(|u| u.txout.value).sum();
Ok(SweepableBalances {
legacy_balance,
p2sh_balance,
taproot_balance,
total_balance: legacy_balance + p2sh_balance + taproot_balance,
legacy_utxos_count: legacy_utxos.len() as u32,
p2sh_utxos_count: p2sh_utxos.len() as u32,
taproot_utxos_count: taproot_utxos.len() as u32,
total_utxos_count: (legacy_utxos.len() + p2sh_utxos.len() + taproot_utxos.len()) as u32,
})
}
pub async fn prepare_sweep_transaction(
mnemonic_phrase: &str,
network: Network,
bip39_passphrase: Option<&str>,
electrum_url: &str,
destination_address: &str,
fee_rate_sats_per_vbyte: Option<u32>,
) -> Result<SweepTransactionPreview, SweepError> {
let bdk_network = onchain_to_bdk_network(network.into());
let wallets = Self::create_sweep_wallets(mnemonic_phrase, network, bip39_passphrase)?;
let dest_addr = BdkAddress::from_str(destination_address)
.map_err(|e| SweepError::SweepFailed(format!("Invalid destination address: {}", e)))?
.require_network(bdk_network)
.map_err(|e| {
SweepError::SweepFailed(format!("Network mismatch for destination address: {}", e))
})?;
let electrum_url_owned = electrum_url.to_string();
let (wallets, electrum_client) = tokio::task::spawn_blocking(move || {
let backend = Self::create_electrum_backend(&electrum_url_owned)?;
let mut wallets = wallets;
Self::sync_wallets(&mut wallets, &backend)?;
let tx_client = Self::create_electrum_client(&electrum_url_owned)?;
Ok::<_, SweepError>((wallets, tx_client))
})
.await
.map_err(|e| SweepError::SweepFailed(format!("Sync task failed: {}", e)))??;
let legacy_utxos: Vec<_> = wallets
.legacy_wallet
.list_unspent()
.map_err(|e| SweepError::SweepFailed(format!("Failed to list legacy UTXOs: {}", e)))?;
let p2sh_utxos: Vec<_> = wallets
.p2sh_wallet
.list_unspent()
.map_err(|e| SweepError::SweepFailed(format!("Failed to list P2SH UTXOs: {}", e)))?;
let taproot_utxos: Vec<_> = wallets
.taproot_wallet
.list_unspent()
.map_err(|e| SweepError::SweepFailed(format!("Failed to list Taproot UTXOs: {}", e)))?;
let mut all_utxos: Vec<_> = legacy_utxos.iter().collect();
all_utxos.extend(p2sh_utxos.iter());
all_utxos.extend(taproot_utxos.iter());
if all_utxos.is_empty() {
return Err(SweepError::NoUtxosFound);
}
let total_amount: u64 = all_utxos.iter().map(|u| u.txout.value).sum();
let legacy_count = legacy_utxos.len();
let p2sh_count = p2sh_utxos.len();
let build_psbt = |output_value: u64| -> Result<Psbt, SweepError> {
let inputs: Vec<TxIn> = all_utxos
.iter()
.map(|utxo| TxIn {
previous_output: OutPoint {
txid: utxo.outpoint.txid,
vout: utxo.outpoint.vout,
},
script_sig: ScriptBuf::new(),
sequence: Sequence::MAX,
witness: Witness::new(),
})
.collect();
let tx = Transaction {
version: 2,
lock_time: LockTime::from_consensus(0),
input: inputs,
output: vec![TxOut {
value: output_value,
script_pubkey: dest_addr.script_pubkey(),
}],
};
let mut psbt = Psbt::from_unsigned_tx(tx)
.map_err(|e| SweepError::SweepFailed(format!("Failed to create PSBT: {}", e)))?;
for (i, utxo) in all_utxos.iter().enumerate() {
psbt.inputs[i].witness_utxo = Some(utxo.txout.clone());
if i < legacy_count + p2sh_count {
let tx_bytes = electrum_client
.transaction_get_raw(&utxo.outpoint.txid)
.map_err(|e| {
SweepError::SweepFailed(format!(
"Failed to fetch tx {}: {}",
utxo.outpoint.txid, e
))
})?;
let tx: Transaction = deserialize(&tx_bytes).map_err(|e| {
SweepError::SweepFailed(format!(
"Failed to deserialize tx {}: {}",
utxo.outpoint.txid, e
))
})?;
psbt.inputs[i].non_witness_utxo = Some(tx);
}
}
Ok(psbt)
};
let mut probe_psbt = build_psbt(total_amount)?;
Self::sign_psbt(&wallets, &mut probe_psbt)?;
let actual_vsize = probe_psbt.extract_tx().weight().to_vbytes_ceil();
let fee_rate_sats = fee_rate_sats_per_vbyte.unwrap_or(1) as u64;
let estimated_fee = actual_vsize * fee_rate_sats;
let amount_after_fees = total_amount.saturating_sub(estimated_fee);
let final_psbt = build_psbt(amount_after_fees)?;
let psbt_base64 = general_purpose::STANDARD.encode(final_psbt.serialize());
Ok(SweepTransactionPreview {
psbt: psbt_base64,
total_amount,
estimated_fee,
estimated_vsize: actual_vsize,
utxos_count: all_utxos.len() as u32,
destination_address: dest_addr.to_string(),
amount_after_fees,
})
}
pub async fn broadcast_sweep_transaction(
psbt_base64: &str,
mnemonic_phrase: &str,
network: Network,
bip39_passphrase: Option<&str>,
electrum_url: &str,
) -> Result<SweepResult, SweepError> {
let psbt_bytes = general_purpose::STANDARD
.decode(psbt_base64)
.map_err(|e| SweepError::SweepFailed(format!("Failed to decode PSBT: {}", e)))?;
let psbt = Psbt::deserialize(&psbt_bytes)
.map_err(|e| SweepError::SweepFailed(format!("Failed to deserialize PSBT: {}", e)))?;
if psbt.unsigned_tx.output.len() != 1 {
return Err(SweepError::SweepFailed(format!(
"PSBT must have exactly 1 output, found {}",
psbt.unsigned_tx.output.len()
)));
}
let total_input: u64 = psbt
.inputs
.iter()
.filter_map(|i| i.witness_utxo.as_ref())
.map(|u| u.value)
.sum();
let output_amount = psbt.unsigned_tx.output[0].value;
let fee_amount = total_input.saturating_sub(output_amount);
let utxos_count = psbt.inputs.len() as u32;
let wallets = Self::create_sweep_wallets(mnemonic_phrase, network, bip39_passphrase)?;
let electrum_url_owned = electrum_url.to_string();
let wallets = tokio::task::spawn_blocking(move || {
let backend = Self::create_electrum_backend(&electrum_url_owned)?;
let mut wallets = wallets;
Self::sync_wallets(&mut wallets, &backend)?;
Ok::<_, SweepError>(wallets)
})
.await
.map_err(|e| SweepError::SweepFailed(format!("Sync task failed: {}", e)))??;
let mut signing_psbt = psbt;
Self::sign_psbt(&wallets, &mut signing_psbt)?;
for input in &signing_psbt.inputs {
if input.final_script_sig.is_none() && input.final_script_witness.is_none() {
return Err(SweepError::SweepFailed(
"Transaction signing incomplete - some inputs not finalized".to_string(),
));
}
}
let final_tx = signing_psbt.extract_tx();
let txid = final_tx.txid();
let electrum_url_owned = electrum_url.to_string();
tokio::task::spawn_blocking(move || {
use bdk::blockchain::Blockchain;
let backend = Self::create_electrum_backend(&electrum_url_owned)?;
backend
.broadcast(&final_tx)
.map_err(|e| SweepError::SweepFailed(format!("Broadcast failed: {}", e)))
})
.await
.map_err(|e| SweepError::SweepFailed(format!("Broadcast task panicked: {}", e)))??;
Ok(SweepResult {