forked from lightningdevkit/ldk-node
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlib.rs
More file actions
1635 lines (1417 loc) · 54.8 KB
/
lib.rs
File metadata and controls
1635 lines (1417 loc) · 54.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
// This file is Copyright its original authors, visible in version control history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. You may not use this file except in
// accordance with one or both of these licenses.
//! A library that aggregates multiple BDK wallets into a single logical wallet
//! with unified balance, UTXO management, transaction building, and signing.
//!
//! # Overview
//!
//! [`AggregateWallet`] wraps a *primary* BDK wallet and zero or more
//! *secondary* wallets, keyed by a user-defined type `K` (e.g. an address-type
//! enum). The primary wallet is used for generating new addresses and change
//! outputs; secondary wallets are monitored for existing funds and their UTXOs
//! participate in transaction construction and signing.
pub mod rbf;
pub mod signing;
pub mod types;
pub mod utxo;
use std::collections::{HashMap, HashSet};
use std::fmt::Debug;
use std::hash::Hash;
use std::ops::{Deref, DerefMut};
use std::sync::Arc;
use bdk_chain::spk_client::{FullScanRequest, SyncRequest};
use bdk_wallet::event::WalletEvent;
use bdk_wallet::{Balance, KeychainKind, LocalOutput, PersistedWallet, Update, WalletPersister};
use bitcoin::blockdata::locktime::absolute::LockTime;
use bitcoin::hashes::Hash as _;
use bitcoin::psbt::Psbt;
use bitcoin::{
Address, Amount, Block, BlockHash, FeeRate, OutPoint, Script, ScriptBuf, Transaction, Txid,
WPubkeyHash,
};
pub use types::{CoinSelectionAlgorithm, Error, UtxoPsbtInfo};
/// A wallet aggregator that presents multiple BDK wallets as a single logical
/// wallet.
///
/// Generic over:
/// * `K` – the key type used to identify individual wallets (e.g. an
/// `AddressType` enum).
/// * `P` – the BDK `WalletPersister` implementation.
pub struct AggregateWallet<K, P>
where
K: Eq + Hash + Copy + Debug,
P: WalletPersister,
{
wallets: HashMap<K, PersistedWallet<P>>,
persisters: HashMap<K, P>,
primary: K,
}
/// Delegates to the primary wallet.
impl<K, P> Deref for AggregateWallet<K, P>
where
K: Eq + Hash + Copy + Debug,
P: WalletPersister,
{
type Target = PersistedWallet<P>;
fn deref(&self) -> &Self::Target {
self.wallets.get(&self.primary).expect("Primary wallet must always exist")
}
}
impl<K, P> DerefMut for AggregateWallet<K, P>
where
K: Eq + Hash + Copy + Debug,
P: WalletPersister,
{
fn deref_mut(&mut self) -> &mut Self::Target {
self.wallets.get_mut(&self.primary).expect("Primary wallet must always exist")
}
}
impl<K, P> AggregateWallet<K, P>
where
K: Eq + Hash + Copy + Debug,
P: WalletPersister,
P::Error: std::fmt::Display,
{
/// Create a new aggregate wallet.
///
/// * `primary_wallet` / `primary_persister` – the wallet used for new
/// address generation and change outputs.
/// * `primary_key` – the key identifying the primary wallet.
/// * `additional_wallets` – secondary wallets to monitor and use for
/// transaction construction.
pub fn new(
primary_wallet: PersistedWallet<P>, primary_persister: P, primary_key: K,
additional_wallets: Vec<(K, PersistedWallet<P>, P)>,
) -> Self {
let mut wallets = HashMap::new();
let mut persisters = HashMap::new();
wallets.insert(primary_key, primary_wallet);
persisters.insert(primary_key, primary_persister);
for (key, wallet, persister) in additional_wallets {
debug_assert!(
!wallets.contains_key(&key),
"duplicate wallet key in AggregateWallet::new"
);
wallets.insert(key, wallet);
persisters.insert(key, persister);
}
Self { wallets, persisters, primary: primary_key }
}
// ─── Accessors ──────────────────────────────────────────────────────
/// The primary wallet key.
pub fn primary_key(&self) -> K {
self.primary
}
/// All loaded wallet keys (primary + monitored).
pub fn loaded_keys(&self) -> Vec<K> {
self.wallets.keys().copied().collect()
}
/// Immutable access to the underlying wallet map.
pub fn wallets(&self) -> &HashMap<K, PersistedWallet<P>> {
&self.wallets
}
/// Mutable access to the underlying wallet map.
pub fn wallets_mut(&mut self) -> &mut HashMap<K, PersistedWallet<P>> {
&mut self.wallets
}
/// Immutable access to the persister map.
pub fn persisters(&self) -> &HashMap<K, P> {
&self.persisters
}
/// Mutable access to the underlying persister map.
pub fn persisters_mut(&mut self) -> &mut HashMap<K, P> {
&mut self.persisters
}
/// Get a reference to a specific wallet.
pub fn wallet(&self, key: &K) -> Option<&PersistedWallet<P>> {
self.wallets.get(key)
}
/// Get a mutable reference to a specific wallet.
pub fn wallet_mut(&mut self, key: &K) -> Option<&mut PersistedWallet<P>> {
self.wallets.get_mut(key)
}
/// Get a reference to the primary wallet.
pub fn primary_wallet(&self) -> &PersistedWallet<P> {
self.wallets.get(&self.primary).expect("Primary wallet must always exist")
}
/// Get a mutable reference to the primary wallet.
pub fn primary_wallet_mut(&mut self) -> &mut PersistedWallet<P> {
self.wallets.get_mut(&self.primary).expect("Primary wallet must always exist")
}
/// Get a mutable reference to the primary persister.
pub fn primary_persister_mut(&mut self) -> &mut P {
self.persisters.get_mut(&self.primary).expect("Primary persister must always exist")
}
/// Add a secondary wallet. Returns `Err(WalletAlreadyExists)` if key exists.
pub fn add_wallet(
&mut self, key: K, wallet: PersistedWallet<P>, persister: P,
) -> Result<(), Error> {
if self.wallets.contains_key(&key) {
return Err(Error::WalletAlreadyExists);
}
self.wallets.insert(key, wallet);
self.persisters.insert(key, persister);
Ok(())
}
/// Change the primary wallet. New primary must already be in the aggregate.
pub fn set_primary(&mut self, new_primary: K) -> Result<(), Error> {
if !self.wallets.contains_key(&new_primary) {
return Err(Error::WalletNotFound);
}
self.primary = new_primary;
Ok(())
}
/// Remove a secondary wallet. Returns `Err` if key is primary or not found.
pub fn remove_wallet(&mut self, key: K) -> Result<(), Error> {
if key == self.primary {
return Err(Error::CannotRemovePrimary);
}
if self.wallets.remove(&key).is_none() {
return Err(Error::WalletNotFound);
}
self.persisters.remove(&key).expect("persister must exist if wallet existed");
Ok(())
}
// ─── Balance ────────────────────────────────────────────────────────
/// Aggregate balance across all wallets.
pub fn balance(&self) -> Balance {
let mut total = Balance::default();
for wallet in self.wallets.values() {
let balance = wallet.balance();
total.confirmed += balance.confirmed;
total.trusted_pending += balance.trusted_pending;
total.untrusted_pending += balance.untrusted_pending;
total.immature += balance.immature;
}
total
}
/// Balance for a single wallet identified by key.
pub fn balance_for(&self, key: &K) -> Result<Balance, Error> {
self.wallets.get(key).map(|w| w.balance()).ok_or(Error::WalletNotFound)
}
// ─── UTXO Listing ───────────────────────────────────────────────────
/// List all unspent outputs across every wallet.
pub fn list_unspent(&self) -> Vec<LocalOutput> {
self.wallets.values().flat_map(|w| w.list_unspent()).collect()
}
/// List confirmed unspent outputs across all wallets.
///
/// Only returns UTXOs whose creating transaction is confirmed in at
/// least one wallet.
pub fn list_confirmed_unspent(&self) -> Vec<LocalOutput> {
let mut confirmed_txids = HashSet::new();
for wallet in self.wallets.values() {
for t in wallet.transactions().filter(|t| t.chain_position.is_confirmed()) {
confirmed_txids.insert(t.tx_node.txid);
}
}
self.list_unspent()
.into_iter()
.filter(|u| confirmed_txids.contains(&u.outpoint.txid))
.collect()
}
/// Derive the inner `WPubkeyHash` for a P2SH-wrapped P2WPKH UTXO.
///
/// For NestedSegwit wallets (BIP-49) the descriptor is `Sh(Wpkh(...))`.
/// This method finds the wallet that owns `utxo`, derives the script at
/// the UTXO's derivation index, and extracts the 20-byte witness
/// program hash from the inner redeemScript (`OP_0 <20-byte-wpkh>`).
///
/// Returns `None` if the UTXO is not owned by any wallet or if the
/// inner script cannot be parsed as P2WPKH.
pub fn derive_wpkh_for_p2sh(&self, utxo: &LocalOutput) -> Option<WPubkeyHash> {
for wallet in self.wallets.values() {
if wallet.get_utxo(utxo.outpoint).is_some() {
let descriptor = wallet.public_descriptor(utxo.keychain);
if let Ok(derived_desc) = descriptor.at_derivation_index(utxo.derivation_index) {
// For Sh(Wpkh(..)) descriptors, `explicit_script()` gives
// the inner P2WPKH redeemScript: OP_0 <20-byte-wpkh>.
if let Ok(explicit) = derived_desc.explicit_script() {
if explicit.len() == 22
&& explicit.as_bytes()[0] == 0x00
&& explicit.as_bytes()[1] == 0x14
{
return WPubkeyHash::from_slice(&explicit.as_bytes()[2..22]).ok();
}
}
}
break;
}
}
None
}
// ─── Transaction Lookup ─────────────────────────────────────────────
/// Find which wallet key contains a transaction.
pub fn find_wallet_for_tx(&self, txid: Txid) -> Option<K> {
self.wallets.iter().find_map(|(key, wallet)| wallet.get_tx(txid).map(|_| *key))
}
/// Find a transaction across all wallets.
pub fn find_tx(&self, txid: Txid) -> Option<Transaction> {
for wallet in self.wallets.values() {
if let Some(tx_node) = wallet.get_tx(txid) {
return Some((*tx_node.tx_node.tx).clone());
}
}
None
}
/// Check whether a transaction is confirmed in any wallet.
pub fn is_tx_confirmed(&self, txid: &Txid) -> bool {
for wallet in self.wallets.values() {
if let Some(tx_node) = wallet.get_tx(*txid) {
if tx_node.chain_position.is_confirmed() {
return true;
}
}
}
false
}
/// Aggregated sent and received amounts for a transaction across all wallets.
pub fn sent_and_received(&self, txid: Txid) -> Option<(u64, u64)> {
let tx = self.find_tx(txid)?;
let mut total_sent = 0u64;
let mut total_received = 0u64;
for wallet in self.wallets.values() {
if wallet.get_tx(txid).is_some() {
let (sent, received) = wallet.sent_and_received(&tx);
total_sent += sent.to_sat();
total_received += received.to_sat();
}
}
Some((total_sent, total_received))
}
/// Collect all cached transactions from all wallets, deduplicated by txid.
pub fn cached_txs(&self) -> Vec<Arc<Transaction>> {
let mut seen = HashSet::new();
self.wallets
.values()
.flat_map(|w| w.tx_graph().full_txs())
.filter(|tx_node| seen.insert(tx_node.txid))
.map(|tx_node| tx_node.tx)
.collect()
}
/// Collect all unconfirmed transaction IDs across wallets (deduplicated).
pub fn unconfirmed_txids(&self) -> Vec<Txid> {
let mut seen = HashSet::new();
self.wallets
.values()
.flat_map(|w| {
w.transactions()
.filter(|t| t.chain_position.is_unconfirmed())
.map(|t| t.tx_node.txid)
})
.filter(|txid| seen.insert(*txid))
.collect()
}
/// All transaction IDs across all wallets.
pub fn all_txids(&self) -> Vec<Txid> {
self.wallets.values().flat_map(|w| w.transactions().map(|wtx| wtx.tx_node.txid)).collect()
}
// ─── Chain Tip ──────────────────────────────────────────────────────
/// The latest checkpoint from the primary wallet, returned as
/// `(block_hash, height)`.
pub fn current_best_block(&self) -> (BlockHash, u32) {
let checkpoint = self.primary_wallet().latest_checkpoint();
(checkpoint.hash(), checkpoint.height())
}
// ─── Address Generation ─────────────────────────────────────────────
/// Generate a new receiving address from the primary wallet.
pub fn new_address(&mut self) -> Result<Address, Error> {
let key = self.primary;
self.new_address_for(&key)
}
/// Generate a new receiving address for a specific wallet.
pub fn new_address_for(&mut self, key: &K) -> Result<Address, Error> {
let wallet = self.wallets.get_mut(key).ok_or(Error::WalletNotFound)?;
let persister = self.persisters.get_mut(key).ok_or(Error::PersisterNotFound)?;
let address_info = wallet.reveal_next_address(KeychainKind::External);
wallet.persist(persister).map_err(|e| {
log::error!("Failed to persist wallet for {:?}: {}", key, e);
Error::PersistenceFailed
})?;
Ok(address_info.address)
}
/// Generate a new internal (change) address from the primary wallet.
pub fn new_internal_address(&mut self) -> Result<Address, Error> {
let primary = self.primary;
let wallet = self.wallets.get_mut(&primary).ok_or(Error::WalletNotFound)?;
let persister = self.persisters.get_mut(&primary).ok_or(Error::PersisterNotFound)?;
let address_info = wallet.next_unused_address(KeychainKind::Internal);
wallet.persist(persister).map_err(|e| {
log::error!("Failed to persist wallet: {}", e);
Error::PersistenceFailed
})?;
Ok(address_info.address)
}
// ─── Transaction Cancellation ───────────────────────────────────────
/// Cancel a transaction in all wallets that know about it.
pub fn cancel_tx(&mut self, tx: &Transaction) -> Result<(), Error> {
for (key, wallet) in self.wallets.iter_mut() {
wallet.cancel_tx(tx);
if let Some(persister) = self.persisters.get_mut(key) {
wallet.persist(persister).map_err(|e| {
log::error!("Failed to persist wallet {:?}: {}", key, e);
Error::PersistenceFailed
})?;
}
}
Ok(())
}
/// Cancel a dry-run transaction on the primary wallet without persisting.
///
/// Unmarks change addresses that were marked "used" by `finish()`, so
/// the next `finish()` reuses them instead of revealing new ones. The
/// reveal itself is left in the staged changeset and persists harmlessly.
///
/// Only targets the primary wallet. All current build paths use the primary.
pub fn cancel_dry_run_tx(&mut self, tx: &Transaction) {
let primary =
self.wallets.get_mut(&self.primary).expect("Primary wallet must always exist");
primary.cancel_tx(tx);
}
// ─── Fee Calculation ────────────────────────────────────────────────
/// Calculate the fee of a PSBT by summing input values and subtracting
/// output values.
pub fn calculate_fee_from_psbt(&self, psbt: &Psbt) -> Result<u64, Error> {
let mut total_input_value = 0u64;
for (i, txin) in psbt.unsigned_tx.input.iter().enumerate() {
if let Some(psbt_input) = psbt.inputs.get(i) {
if let Some(witness_utxo) = &psbt_input.witness_utxo {
total_input_value += witness_utxo.value.to_sat();
} else if let Some(non_witness_tx) = &psbt_input.non_witness_utxo {
if let Some(txout) =
non_witness_tx.output.get(txin.previous_output.vout as usize)
{
total_input_value += txout.value.to_sat();
} else {
return Err(Error::OnchainTxCreationFailed);
}
} else {
let mut found = false;
for wallet in self.wallets.values() {
if let Some(local_utxo) = wallet.get_utxo(txin.previous_output) {
total_input_value += local_utxo.txout.value.to_sat();
found = true;
break;
}
}
if !found {
return Err(Error::OnchainTxCreationFailed);
}
}
} else {
let mut found = false;
for wallet in self.wallets.values() {
if let Some(local_utxo) = wallet.get_utxo(txin.previous_output) {
total_input_value += local_utxo.txout.value.to_sat();
found = true;
break;
}
}
if !found {
return Err(Error::OnchainTxCreationFailed);
}
}
}
let total_output_value: u64 =
psbt.unsigned_tx.output.iter().map(|txout| txout.value.to_sat()).sum();
Ok(total_input_value.saturating_sub(total_output_value))
}
/// Calculate fee from PSBT with fallback to primary wallet calculation.
pub fn calculate_fee_with_fallback(&self, psbt: &Psbt) -> Result<u64, Error> {
self.calculate_fee_from_psbt(psbt).or_else(|_| {
self.primary_wallet()
.calculate_fee(&psbt.unsigned_tx)
.map(|f| f.to_sat())
.map_err(|_| Error::OnchainTxCreationFailed)
})
}
/// Calculate the drain amount from a PSBT using sent_and_received across
/// all wallets. Returns the net outgoing amount (sent - received) in sats.
///
/// For not-yet-broadcast PSBTs the transaction won't be in any wallet's
/// tx-graph, so we compute sent/received directly from the unsigned tx
/// against every wallet's script set.
pub fn drain_amount_from_psbt(&self, psbt: &Psbt) -> u64 {
let mut total_sent = Amount::ZERO;
let mut total_received = Amount::ZERO;
for wallet in self.wallets.values() {
let (s, r) = wallet.sent_and_received(&psbt.unsigned_tx);
total_sent += s;
total_received += r;
}
total_sent.to_sat().saturating_sub(total_received.to_sat())
}
// ─── Sync ───────────────────────────────────────────────────────────
/// Build a full scan request for a specific wallet.
pub fn wallet_full_scan_request(
&self, key: &K,
) -> Result<FullScanRequest<KeychainKind>, Error> {
let wallet = self.wallets.get(key).ok_or(Error::WalletNotFound)?;
Ok(wallet.start_full_scan().build())
}
/// Build an incremental sync request for a specific wallet.
pub fn wallet_incremental_sync_request(
&self, key: &K,
) -> Result<SyncRequest<(KeychainKind, u32)>, Error> {
let wallet = self.wallets.get(key).ok_or(Error::WalletNotFound)?;
Ok(wallet.start_sync_with_revealed_spks().build())
}
/// Apply a chain update to the primary wallet.
///
/// Returns the wallet events and a list of all transaction IDs in the
/// primary wallet (so the caller can update its payment store).
pub fn apply_update(
&mut self, update: impl Into<Update>,
) -> Result<(Vec<WalletEvent>, Vec<Txid>), Error> {
let update = update.into();
let primary = self.primary;
let wallet = self.wallets.get_mut(&primary).ok_or(Error::WalletNotFound)?;
let events = wallet.apply_update_events(update).map_err(|e| {
log::error!("Failed to apply update to primary wallet: {}", e);
Error::WalletOperationFailed
})?;
let persister = self.persisters.get_mut(&primary).ok_or(Error::PersisterNotFound)?;
wallet.persist(persister).map_err(|e| {
log::error!("Failed to persist primary wallet: {}", e);
Error::PersistenceFailed
})?;
let txids: Vec<Txid> = wallet.transactions().map(|wtx| wtx.tx_node.txid).collect();
Ok((events, txids))
}
/// Apply a chain update to a specific wallet.
///
/// Returns the wallet events and a list of all transaction IDs in that
/// wallet.
pub fn apply_update_to_wallet(
&mut self, key: K, update: impl Into<Update>,
) -> Result<(Vec<WalletEvent>, Vec<Txid>), Error> {
let update = update.into();
let wallet = self.wallets.get_mut(&key).ok_or(Error::WalletNotFound)?;
let events = wallet.apply_update_events(update).map_err(|e| {
log::error!("Failed to apply update to wallet {:?}: {}", key, e);
Error::WalletOperationFailed
})?;
let persister = self.persisters.get_mut(&key).ok_or(Error::PersisterNotFound)?;
wallet.persist(persister).map_err(|e| {
log::error!("Failed to persist wallet {:?}: {}", key, e);
Error::PersistenceFailed
})?;
let txids: Vec<Txid> = wallet.transactions().map(|wtx| wtx.tx_node.txid).collect();
Ok((events, txids))
}
/// Apply mempool (unconfirmed) transactions to all wallets.
pub fn apply_mempool_txs(
&mut self, unconfirmed_txs: Vec<(Transaction, u64)>, evicted_txids: Vec<(Txid, u64)>,
) -> Result<(), Error> {
for (key, wallet) in self.wallets.iter_mut() {
wallet.apply_unconfirmed_txs(unconfirmed_txs.clone());
wallet.apply_evicted_txs(evicted_txids.clone());
if let Some(persister) = self.persisters.get_mut(key) {
wallet.persist(persister).map_err(|e| {
log::error!("Failed to persist wallet {:?}: {}", key, e);
Error::PersistenceFailed
})?;
}
}
Ok(())
}
/// Apply a connected block to all wallets and persist.
///
/// Returns the set of all transaction IDs across all wallets.
pub fn apply_block(&mut self, block: &Block, height: u32) -> Result<HashSet<Txid>, Error> {
let pre_checkpoint = self.primary_wallet().latest_checkpoint();
if height > 0
&& (pre_checkpoint.height() != height - 1
|| pre_checkpoint.hash() != block.header.prev_blockhash)
{
log::debug!("Detected reorg while applying connected block at height {}", height);
}
for (key, wallet) in self.wallets.iter_mut() {
wallet.apply_block(block, height).map_err(|e| {
log::error!("Failed to apply connected block to wallet {:?}: {}", key, e);
Error::WalletOperationFailed
})?;
if let Some(persister) = self.persisters.get_mut(key) {
wallet.persist(persister).map_err(|e| {
log::error!("Failed to persist wallet {:?}: {}", key, e);
Error::PersistenceFailed
})?;
}
}
let mut all_txids = HashSet::new();
for wallet in self.wallets.values() {
for wtx in wallet.transactions() {
all_txids.insert(wtx.tx_node.txid);
}
}
Ok(all_txids)
}
// ─── UTXO Preparation Helpers ───────────────────────────────────────
/// Prepare local outputs for cross-wallet PSBT building.
pub fn prepare_utxos_for_psbt(
&self, utxos: &[LocalOutput],
) -> Result<Vec<UtxoPsbtInfo>, Error> {
utxo::prepare_utxos_for_psbt(utxos, &self.wallets, &self.primary)
}
/// Prepare outpoints for cross-wallet PSBT building.
pub fn prepare_outpoints_for_psbt(
&self, outpoints: &[OutPoint],
) -> Result<Vec<UtxoPsbtInfo>, Error> {
utxo::prepare_outpoints_for_psbt(outpoints, &self.wallets, &self.primary)
}
// ─── Signing ────────────────────────────────────────────────────────
/// Sign an unsigned transaction using all wallets that own inputs.
pub fn sign_owned_inputs(&mut self, unsigned_tx: Transaction) -> Result<Transaction, Error> {
signing::sign_owned_inputs(unsigned_tx, &mut self.wallets)
}
/// Sign a PSBT using all wallets that own inputs.
pub fn sign_psbt_all(&mut self, psbt: Psbt) -> Result<Transaction, Error> {
signing::sign_psbt_all_wallets(psbt, &mut self.wallets)
}
// ─── Cross-wallet RBF ───────────────────────────────────────────────
/// Build a cross-wallet RBF replacement, adding extra inputs if needed.
///
/// 1. Tries adjusting the change output only (no new inputs).
/// 2. If that is insufficient, selects minimum additional UTXOs from all
/// wallets and retries.
fn build_cross_wallet_rbf_with_fallback(
&mut self, original_tx: &Transaction, new_fee_rate: FeeRate,
) -> Result<Transaction, Error> {
// Attempt 1: change-only bump.
match rbf::build_cross_wallet_rbf(&mut self.wallets, original_tx, new_fee_rate, &[]) {
Ok(tx) => return Ok(tx),
Err(Error::InsufficientFunds) => {},
Err(e) => return Err(e),
}
// Attempt 2: select minimum additional UTXOs.
let original_fee = self.calculate_tx_fee(original_tx)?;
let new_fee = new_fee_rate.fee_wu(original_tx.weight()).unwrap_or(Amount::ZERO);
let fee_increase = new_fee.checked_sub(original_fee).unwrap_or(Amount::ZERO);
// Change value absorbable from the original tx.
let change_value: Amount = original_tx
.output
.iter()
.filter(|out| {
self.wallets.values().any(|w| {
w.list_unspent().any(|u| {
u.keychain == KeychainKind::Internal
&& u.txout.script_pubkey == out.script_pubkey
})
})
})
.map(|out| out.value)
.sum();
let deficit = fee_increase.checked_sub(change_value).unwrap_or(Amount::ZERO);
// Collect UTXOs from all wallets, excluding those already in the
// original tx and outputs created by the original tx.
let original_outpoints: HashSet<OutPoint> =
original_tx.input.iter().map(|i| i.previous_output).collect();
let original_txid = original_tx.compute_txid();
let available: Vec<LocalOutput> = self
.list_unspent()
.into_iter()
.filter(|u| !original_outpoints.contains(&u.outpoint))
.filter(|u| u.outpoint.txid != original_txid)
.collect();
if available.is_empty() {
return Err(Error::InsufficientFunds);
}
let drain_script =
self.primary_wallet().peek_address(KeychainKind::Internal, 0).address.script_pubkey();
let selected = utxo::select_utxos_with_algorithm(
deficit.to_sat(),
available,
new_fee_rate,
CoinSelectionAlgorithm::BranchAndBound,
&drain_script,
&[],
&self.wallets,
)?;
let extra_infos = self.prepare_outpoints_for_psbt(&selected)?;
if extra_infos.is_empty() {
return Err(Error::InsufficientFunds);
}
rbf::build_cross_wallet_rbf(&mut self.wallets, original_tx, new_fee_rate, &extra_infos)
}
/// Look up an input value across local wallets.
pub fn get_input_value(&self, outpoint: &OutPoint) -> Result<u64, Error> {
rbf::get_input_value(outpoint, &self.wallets)
}
// ─── Coin Selection ─────────────────────────────────────────────────
/// Run coin selection across all wallets.
pub fn select_utxos(
&self, target_amount: u64, available_utxos: Vec<LocalOutput>, fee_rate: FeeRate,
algorithm: CoinSelectionAlgorithm, drain_script: &Script, excluded_outpoints: &[OutPoint],
) -> Result<Vec<OutPoint>, Error> {
utxo::select_utxos_with_algorithm(
target_amount,
available_utxos,
fee_rate,
algorithm,
drain_script,
excluded_outpoints,
&self.wallets,
)
}
// ─── Fee Calculation ─────────────────────────────────────────────────
/// Calculate the fee of a transaction by looking up input values across
/// all wallets and subtracting total output values.
///
/// Tries BDK's native `calculate_fee` on each wallet first (works
/// reliably for transactions that were built by that wallet), then
/// falls back to manual input-value lookup across all wallets.
pub fn calculate_tx_fee(&self, tx: &Transaction) -> Result<Amount, Error> {
// Fast path: BDK knows the fee for transactions it built.
for wallet in self.wallets.values() {
if let Ok(fee) = wallet.calculate_fee(tx) {
return Ok(fee);
}
}
// Slow path: manually look up each input value.
let mut total_input = 0u64;
for txin in &tx.input {
total_input += self.get_input_value(&txin.previous_output)?;
}
let total_output: u64 = tx.output.iter().map(|o| o.value.to_sat()).sum();
Ok(Amount::from_sat(total_input.saturating_sub(total_output)))
}
// ─── High-Level Helpers ─────────────────────────────────────────────
/// Return prepared PSBT info for all non-primary UTXOs, suitable for
/// adding as foreign inputs to a transaction built on the primary wallet.
///
/// `excluded_txids` allows the caller to filter out UTXOs belonging to
/// specific transactions (e.g. channel funding transactions).
pub fn non_primary_foreign_utxos(
&self, excluded_txids: &HashSet<Txid>,
) -> Result<Vec<UtxoPsbtInfo>, Error> {
let primary_outpoints: HashSet<OutPoint> =
self.primary_wallet().list_unspent().map(|u| u.outpoint).collect();
let non_primary: Vec<LocalOutput> = self
.list_unspent()
.into_iter()
.filter(|u| !primary_outpoints.contains(&u.outpoint))
.filter(|u| !excluded_txids.contains(&u.outpoint.txid))
.collect();
if non_primary.is_empty() {
return Ok(Vec::new());
}
self.prepare_utxos_for_psbt(&non_primary)
}
/// Select the minimum set of non-primary foreign UTXOs needed to cover
/// `deficit`, using the given coin selection algorithm.
///
/// * `segwit_only` – if `true`, excludes bare P2PKH UTXOs (includes
/// P2SH-P2WPKH / NestedSegwit since those carry witness data).
/// * `algorithm` – the coin selection strategy to use.
///
/// Returns prepared `UtxoPsbtInfo` entries ready to add as foreign
/// inputs, or an empty vec if no non-primary UTXOs are available.
pub fn select_non_primary_foreign_utxos(
&self, deficit: Amount, fee_rate: FeeRate, excluded_txids: &HashSet<Txid>,
segwit_only: bool, algorithm: CoinSelectionAlgorithm,
) -> Result<Vec<UtxoPsbtInfo>, Error> {
let primary_outpoints: HashSet<OutPoint> =
self.primary_wallet().list_unspent().map(|u| u.outpoint).collect();
let non_primary: Vec<LocalOutput> = self
.list_unspent()
.into_iter()
.filter(|u| !primary_outpoints.contains(&u.outpoint))
.filter(|u| !excluded_txids.contains(&u.outpoint.txid))
.filter(|u| {
!segwit_only
|| u.txout.script_pubkey.witness_version().is_some()
|| u.txout.script_pubkey.is_p2sh()
})
.collect();
if non_primary.is_empty() {
return Ok(Vec::new());
}
let drain_script =
self.primary_wallet().peek_address(KeychainKind::Internal, 0).address.script_pubkey();
let selected_outpoints = utxo::select_utxos_with_algorithm(
deficit.to_sat(),
non_primary,
fee_rate,
algorithm,
&drain_script,
&[],
&self.wallets,
)?;
self.prepare_outpoints_for_psbt(&selected_outpoints)
}
/// Build a transaction using unified coin selection across all eligible
/// wallets.
///
/// Pools UTXOs from every wallet that passes `utxo_filter`, runs coin
/// selection once on the combined set, then builds a PSBT on the
/// `build_key` wallet with primary UTXOs as native inputs and foreign
/// UTXOs via `add_foreign_utxo`. Signs with all wallets and persists.
#[allow(deprecated, clippy::too_many_arguments)]
fn build_tx_unified(
&mut self, build_key: &K, output_script: ScriptBuf, amount: Amount, fee_rate: FeeRate,
locktime: Option<LockTime>, excluded_txids: &HashSet<Txid>,
algorithm: CoinSelectionAlgorithm, utxo_filter: impl Fn(&LocalOutput) -> bool,
) -> Result<Psbt, Error> {
let all_utxos: Vec<LocalOutput> = self
.list_unspent()
.into_iter()
.filter(|u| !excluded_txids.contains(&u.outpoint.txid))
.filter(&utxo_filter)
.collect();
if all_utxos.is_empty() {
return Err(Error::NoSpendableOutputs);
}
let drain_script = self
.wallet(build_key)
.ok_or(Error::WalletNotFound)?
.peek_address(KeychainKind::Internal, 0)
.address
.script_pubkey();
let selected = utxo::select_utxos_with_algorithm(
amount.to_sat(),
all_utxos,
fee_rate,
algorithm,
&drain_script,
&[],
&self.wallets,
)?;
let infos = self.prepare_outpoints_for_psbt(&selected)?;
if infos.is_empty() {
return Err(Error::InsufficientFunds);
}
let w = self.wallets.get_mut(build_key).ok_or(Error::WalletNotFound)?;
let mut b = w.build_tx();
b.add_recipient(output_script, amount).fee_rate(fee_rate);
if let Some(lt) = locktime {
b.nlocktime(lt);
}
utxo::add_utxos_to_tx_builder(&mut b, &infos)?;
// BDK must not add extra UTXOs — we already selected everything.
b.manually_selected_only();
b.finish().map_err(|e| {
log::error!("Failed to build tx with unified selection: {}", e);
Error::InsufficientFunds
})
}
/// Build a channel-funding transaction using unified coin selection
/// across all wallets. Only SegWit-compatible UTXOs are included
/// (Legacy/P2PKH excluded) as required by BOLT 2.
#[allow(deprecated)]
pub fn build_and_sign_funding_tx(
&mut self, output_script: ScriptBuf, amount: Amount, fee_rate: FeeRate, locktime: LockTime,
) -> Result<Transaction, Error> {
let psbt = self.build_tx_unified(
&self.primary.clone(),
output_script,
amount,
fee_rate,
Some(locktime),
&HashSet::new(),
CoinSelectionAlgorithm::BranchAndBound,
|u| {
u.txout.script_pubkey.witness_version().is_some() || u.txout.script_pubkey.is_p2sh()
},
)?;
let tx = self.sign_psbt_all(psbt)?;
self.persist_all()?;
Ok(tx)
}
/// Build a channel-funding transaction when the primary wallet is not
/// eligible (e.g. Legacy). Picks the highest-balance wallet from those
/// passing `filter` as the PSBT builder, then runs unified coin
/// selection across all eligible wallets.
#[allow(deprecated)]
pub fn build_and_sign_tx_with_best_wallet(
&mut self, output_script: ScriptBuf, amount: Amount, fee_rate: FeeRate, locktime: LockTime,
filter: impl Fn(&K) -> bool,
) -> Result<Transaction, Error> {
let mut matching_keys: Vec<K> =
self.wallets.keys().filter(|k| filter(k)).cloned().collect();
if matching_keys.is_empty() {
return Err(Error::InsufficientFunds);
}
matching_keys.sort_by(|a, b| {
let bal_a = self
.balance_for(a)
.map(|bal| bal.confirmed.to_sat() + bal.trusted_pending.to_sat())
.unwrap_or(0);
let bal_b = self
.balance_for(b)
.map(|bal| bal.confirmed.to_sat() + bal.trusted_pending.to_sat())
.unwrap_or(0);
bal_b.cmp(&bal_a)
});
let build_key = matching_keys[0];
let psbt = self.build_tx_unified(
&build_key,
output_script,
amount,
fee_rate,
Some(locktime),
&HashSet::new(),
CoinSelectionAlgorithm::BranchAndBound,
|u| {
u.txout.script_pubkey.witness_version().is_some() || u.txout.script_pubkey.is_p2sh()
},
)?;
let tx = self.sign_psbt_all(psbt)?;
self.persist_all()?;
Ok(tx)
}
/// Build a PSBT using unified coin selection across all wallets.
/// Returns the **unsigned** PSBT — the caller is responsible for
/// signing and persisting.
#[allow(deprecated)]