1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
use std::{
collections::BTreeMap,
path::PathBuf,
str::FromStr,
sync::{
atomic::{AtomicBool, Ordering},
mpsc, Arc, Mutex,
},
thread::{self, JoinHandle},
};
use bwk_backoff::Backoff;
use bwk_electrum::client::{CoinRequest, CoinResponse};
use miniscript::{
bitcoin::{self, absolute, EcdsaSighashType, OutPoint, ScriptBuf, TxOut},
psbt::PsbtExt,
};
use serde::{Deserialize, Serialize};
use crate::{
address_store::{AddressEntry, AddressTip},
coin::Coin,
coin_store::{CoinEntry, CoinStore},
config::{Config, Tip},
derivator::Derivator,
label_store::{LabelKey, LabelStore},
signing_manager::SigningManager,
tx_store::TxStore,
};
/// The factor that non-witness serialization data is multiplied by during weight calculation.
const WITNESS_SCALE_FACTOR: u64 = 4;
const DUST_AMOUNT: u64 = 5_000;
pub struct TransactionTemplate {
pub inputs: Vec<RustCoin>,
pub outputs: Vec<Output>,
pub fee_sats: u64,
fee_sats_vb: f64,
}
pub struct TransactionSimulation {
pub spendable: bool,
pub has_change: bool,
pub estimated_weight: u64,
pub error: String,
}
pub struct Output {
pub address: String,
pub amount: u64, // amount in sats
pub label: String,
pub max: bool, // if max == true, amount is not taken in account,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, PartialOrd, Ord)]
pub enum CoinStatus {
Unconfirmed,
Confirmed,
BeingSpend,
Spent,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, PartialOrd, Ord)]
pub enum AddrAccount {
Receive,
Change,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, PartialOrd, Ord)]
pub enum AddressStatus {
NotUsed,
Used,
Reused,
Unknown,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct CoinState {
pub coins: Vec<RustCoin>,
pub confirmed_coins: usize,
pub confirmed_balance: u64,
pub unconfirmed_coins: usize,
pub unconfirmed_balance: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct RustCoin {
pub value: u64,
pub height: u64,
pub confirmed: bool,
pub status: CoinStatus,
pub outpoint: String,
pub address: RustAddress,
pub label: String,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct RustAddress {
pub address: String,
pub status: AddressStatus,
pub account: AddrAccount,
pub index: u32,
}
impl From<AddrAccount> for u32 {
fn from(value: AddrAccount) -> Self {
match value {
AddrAccount::Receive => 0,
AddrAccount::Change => 2,
}
}
}
impl From<u32> for AddrAccount {
fn from(value: u32) -> Self {
match value {
0 => AddrAccount::Receive,
1 => AddrAccount::Change,
_ => unimplemented!(),
}
}
}
pub struct Transaction {
pub height: Option<u64>,
pub txid: String,
pub inputs: Vec<TxInput>,
pub outputs: Vec<TxOutput>,
pub fees: u64,
pub weight: u64,
}
pub struct TxInput {
pub vin: usize,
pub outpoint: String,
pub value: u64,
pub owned: bool,
}
pub struct TxOutput {
pub vout: usize,
pub spk: ScriptBuf,
pub value: u64,
pub owned: bool,
}
/// Represents different types of errors that can occur.
#[derive(Debug)]
pub enum Notification {
Electrum(TxListenerNotif),
AddressTipChanged,
CoinUpdate,
InvalidElectrumConfig,
InvalidLookAhead,
Stopped,
Error(Error),
}
impl From<TxListenerNotif> for Notification {
fn from(value: TxListenerNotif) -> Self {
Notification::Electrum(value)
}
}
impl From<Error> for Notification {
fn from(value: Error) -> Self {
Self::Error(value)
}
}
#[derive(Debug)]
pub enum Error {
CreatePool,
JoinPool,
InvalidOutPoint,
CoinMissing,
InvalidDenomination,
RelayMissing,
WrongElectrumConfig,
PoolMissing,
WrongKeyType,
Satisfaction,
}
/// Represents notifications related to transaction listeners.
#[derive(Debug, Clone)]
pub enum TxListenerNotif {
Started,
Error(String),
Stopped,
}
#[derive(Debug)]
pub struct Account {
coin_store: Arc<Mutex<CoinStore>>,
label_store: Arc<Mutex<LabelStore>>,
receiver: Option<mpsc::Receiver<Notification>>,
sender: mpsc::Sender<Notification>,
tx_listener: Option<JoinHandle<()>>,
config: Config,
electrum_stop: Option<Arc<AtomicBool>>,
signing_manager: SigningManager,
}
impl Drop for Account {
fn drop(&mut self) {
if let Some(stop) = self.electrum_stop.as_mut() {
stop.store(true, Ordering::Relaxed);
}
}
}
// Rust only interface
impl Account {
/// Creates a new `Account` instance with the given configuration.
///
/// # Arguments
///
/// * `config` - The configuration for the account.
///
/// # Returns
///
/// A new `Account` instance.
pub fn new(config: Config) -> Self {
assert!(!config.account.is_empty());
let (sender, receiver) = mpsc::channel();
let tx_data = if config.persist {
TxStore::store_from_file(config.transactions_path())
} else {
BTreeMap::new()
};
let tx_store =
TxStore::new(tx_data, Some(config.transactions_path())).enable_persist(config.persist);
let (receive, change) = if config.persist {
let Tip { receive, change } = config.tip_from_file();
(receive, change)
} else {
(0, 0)
};
let label_store = Arc::new(Mutex::new(
LabelStore::from_file(config.clone()).enable_persist(config.persist),
));
let coin_store = Arc::new(Mutex::new(CoinStore::new(
config.network,
config.descriptor.clone(),
sender.clone(),
receive,
change,
config.look_ahead,
tx_store,
label_store.clone(),
Some(config.clone()),
)));
coin_store.lock().expect("poisoned").generate();
let mut signing_manager =
SigningManager::new(PathBuf::new(), config.dir_name()).enable_persist(config.persist);
if let Some(mnemo) = config.mnemonic.clone() {
signing_manager.new_hot_signer_from_mnemonic(config.network(), mnemo);
}
let mut account = Account {
coin_store,
label_store,
tx_listener: None,
electrum_stop: None,
receiver: Some(receiver),
sender,
config,
signing_manager,
};
account.start_electrum();
account
}
/// Starts listening for transactions on the specified address and port.
///
/// # Arguments
///
/// * `addr` - The address to listen on.
/// * `port` - The port to listen on.
///
/// # Returns
///
/// A tuple containing a sender for address tips and a stop flag.
fn start_listen_txs(
&mut self,
addr: String,
port: u16,
config: Config,
) -> (mpsc::Sender<AddressTip>, Arc<AtomicBool>) {
log::debug!("Account::start_poll_txs()");
let (sender, address_tip) = mpsc::channel();
let coin_store = self.coin_store.clone();
let notification = self.sender.clone();
let derivator = self.derivator();
let stop = Arc::new(AtomicBool::new(false));
let stop_request = stop.clone();
let poller = thread::spawn(move || {
let client = match bwk_electrum::client::Client::new(&addr, port) {
Ok(c) => c,
Err(e) => {
log::error!("start_listen_txs(): fail to create electrum client {}", e);
let _ = notification.send(TxListenerNotif::Error(e.to_string()).into());
return;
}
};
let (request, response) = client.listen::<CoinRequest, CoinResponse>();
listen_txs(
coin_store,
derivator,
notification,
address_tip,
stop_request,
request,
response,
Some(config),
);
});
self.tx_listener = Some(poller);
(sender, stop)
}
pub fn receiver(&mut self) -> Option<mpsc::Receiver<Notification>> {
self.receiver.take()
}
/// Returns the derivator associated with the account.
///
/// # Returns
///
/// A `Derivator` instance.
pub fn derivator(&self) -> Derivator {
self.coin_store.lock().expect("poisoned").derivator()
}
/// Returns a map of coins associated with the account.
///
/// # Returns
///
/// A `BTreeMap` of `OutPoint` to `CoinEntry`.
pub fn coins(&self) -> BTreeMap<OutPoint, CoinEntry> {
self.coin_store.lock().expect("poisoned").coins()
}
/// Returns the receiving address at the specified index.
///
/// # Arguments
///
/// * `index` - The index of the receiving address.
///
/// # Returns
///
/// A `bitcoin::Address` instance.
pub fn recv_at(&self, index: u32) -> bitcoin::Address {
self.coin_store
.lock()
.expect("poisoned")
.derivator_ref()
.receive_at(index)
}
/// Returns the change address at the specified index.
///
/// # Arguments
///
/// * `index` - The index of the change address.
///
/// # Returns
///
/// A `bitcoin::Address` instance.
pub fn change_at(&self, index: u32) -> bitcoin::Address {
self.coin_store
.lock()
.expect("poisoned")
.derivator_ref()
.change_at(index)
}
/// Generates a new receiving address for the account.
///
/// # Returns
///
/// A `bitcoin::Address` instance.
pub fn new_recv_addr(&mut self) -> bitcoin::Address {
self.coin_store.lock().expect("poisoned").new_recv_addr()
}
/// Generates a new change address for the account.
///
/// # Returns
///
/// A `bitcoin::Address` instance.
pub fn new_change_addr(&mut self) -> bitcoin::Address {
self.coin_store.lock().expect("poisoned").new_change_addr()
}
/// Returns the current receiving watch tip index.
///
/// # Returns
///
/// The receiving watch tip index as a `u32`.
pub fn recv_watch_tip(&self) -> u32 {
self.coin_store.lock().expect("poisoned").recv_watch_tip()
}
/// Returns the current change watch tip index.
///
/// # Returns
///
/// The change watch tip index as a `u32`.
pub fn change_watch_tip(&self) -> u32 {
self.coin_store.lock().expect("poisoned").change_watch_tip()
}
/// Re-generate coin_store from tx_store
pub fn generate_coins(&mut self) {
self.coin_store.lock().expect("poisoned").generate();
}
/// Returns spendable coins for the account.
pub fn spendable_coins(&self) -> CoinState {
self.coin_store.lock().expect("poisoned").spendable_coins()
}
/// Returns a list of all historical transactions
pub fn tx_history(&self) -> Vec<Transaction> {
self.coin_store.lock().expect("poisoned").tx_history()
}
/// Calculates the satisfaction size for an input, returning the result
/// in weight units (WU).
///
/// This function estimates the size required to satisfy the inputs of a
/// transaction based on the
/// account's descriptor.
///
/// # Returns
///
/// A `Result<usize, Error>` where:
/// - `Ok(usize)` indicates the estimated satisfaction size in weight units (WU).
/// - `Err(Error)` indicates an error occurred during the calculation.
///
/// # Errors
///
/// This function can return an error in the following cases:
/// - If the descriptor is invalid or cannot be parsed, leading to an
/// inability to determine the satisfaction size for the inputs.
pub fn input_satisfaction_size(&self) -> Result<usize, Error> {
self.config
.descriptor
.clone()
.into_single_descriptors()
.expect("multikey")
.first()
.expect("multikey")
.clone()
.max_weight_to_satisfy()
.map_err(|_| Error::Satisfaction)
.map(|w| w.to_wu() as usize)
}
/// Estimates the maximum possible weight in weight units of an unsigned
/// transaction, `tx`, after satisfaction, assuming all inputs of `tx` are
/// from this descriptor.
///
/// # Arguments
///
/// * `tx` - A reference to the `bitcoin::Transaction` for which the weight
/// is to be estimated.
///
/// # Returns
///
/// A `Result<u64, Error>` containing:
/// - `Ok(u64)` - The estimated weight of the transaction in weight units (WU).
/// - `Err(Error)` - An error if the estimation fails.
///
/// # Errors
///
/// This function can return an error in the following cases:
/// - If the satisfaction size for the inputs cannot be calculated due to an
/// invalid descriptor.
/// - If the input satisfaction size exceeds the maximum allowable weight,
/// leading to an overflow.
/// - If the transaction contains no inputs, which would make weight estimation
/// impossible.
/// - If there is an issue with the underlying logic of the weight calculation,
/// such as unexpected behavior from the `miniscript` library.
///
/// # Note
///
/// The weight is calculated based on the number of inputs and their respective
/// satisfaction sizes.
/// The function takes into account the Segwit marker and flag, ensuring that
/// the weight is accurately represented according to Bitcoin's transaction weight rules.
/// This logic have been borrowed from Liana wallet.
pub fn tx_estimated_weight(&self, tx: &bitcoin::Transaction) -> Result<u64, Error> {
let num_inputs: u64 = tx.input.len().try_into().unwrap();
let max_sat_weight: u64 = self.input_satisfaction_size()?.try_into().unwrap();
// Add weights together before converting to vbytes to avoid rounding up multiple times.
let size = tx
.weight()
.to_wu()
.checked_add(max_sat_weight.checked_mul(num_inputs).unwrap())
.and_then(|weight| {
weight.checked_add(
// Make sure the Segwit marker and flag are included:
// https://docs.rs/bitcoin/0.31.0/src/bitcoin/blockdata/transaction.rs.html#752-753
// https://docs.rs/bitcoin/0.31.0/src/bitcoin/blockdata/transaction.rs.html#968-979
if num_inputs > 0 && tx.input.iter().all(|txin| txin.witness.is_empty()) {
2
} else {
0
},
)
})
.unwrap();
let size = size
.checked_add(WITNESS_SCALE_FACTOR.checked_sub(1).unwrap())
.unwrap()
.checked_div(WITNESS_SCALE_FACTOR)
.unwrap();
Ok(size)
}
/// Returns the coin matching the given outpoint if found, else None.
pub fn get_coin(&self, outpoint: &OutPoint) -> Option<Coin> {
self.coin_store
.lock()
.expect("poisoned")
.get(outpoint)
.map(|e| e.coin)
}
/// Generates a static dummy script public key (SPK) for change outputs.
///
/// This function always returns the same dummy spk,
/// It is useful for simulating change outputs in a non-final transaction
/// while allowing for easy replacement of this SPK later during the final
/// crafting of the transaction.
///
/// # Returns
///
/// A `ScriptBuf` representing the dummy script public key for the change address.
///
/// # Note
///
/// The SPK returned by this function is not intended for actual use in
/// transactions until it is replaced with a valid SPK at the time of final
/// transaction crafting.
pub fn dummy_spk(&self) -> ScriptBuf {
ScriptBuf::from_bytes(vec![0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
}
/// Assembles a Bitcoin transaction from the provided inputs and outputs.
///
/// This function creates a new `bitcoin::Transaction` by populating its
/// input and output fields based on the provided vectors of coin entries
/// and transaction outputs. The transaction is initialized with a version
/// and a lock time of zero.
///
/// # Arguments
///
/// * `inputs` - A reference to a vector of `CoinEntry` representing the
/// inputs for the transaction.
/// * `outputs` - A reference to a vector of tuples, where each tuple contains
/// a `TxOut` and an optional tuple with an `AddrAccount` and an index,
/// representing the outputs for the transaction.
///
/// # Returns
///
/// A `bitcoin::Transaction` instance that contains the assembled inputs and outputs.
fn assembly_tx(
inputs: &Vec<CoinEntry>,
outputs: &Vec<(TxOut, Option<(AddrAccount, u32)>)>,
) -> bitcoin::Transaction {
let mut tx = bitcoin::Transaction {
version: bitcoin::transaction::Version(2),
lock_time: absolute::LockTime::ZERO,
input: vec![],
output: vec![],
};
for i in inputs {
tx.input.push(i.txin());
}
for o in outputs {
tx.output.push(o.0.clone());
}
tx
}
/// Preprocesses a transaction based on the provided `TransactionTemplate`.
///
/// This function processes the transaction template to estimate whether the
/// transaction can be successfully executed, including whether it is spendable
/// and if it requires change.
///
/// # Arguments
///
/// * `tx_template` - A `TransactionTemplate` containing the details of the
/// transaction to be processed.
///
/// # Returns
///
/// A `Result` containing:
/// - A tuple with three elements:
/// - A `Vec<CoinEntry>` representing the inputs for the transaction.
/// - A `Vec<(TxOut, Option<(AddrAccount, u32)>)>` representing the outputs
/// for the transaction.
/// - A boolean indicating if the transaction contains a change output.
///
/// # Errors
///
/// This function can return an error in the following cases:
/// - If both `fee_sats` and `fee_sats_vb` are filled, which is not allowed.
/// - If neither `fee_sats` nor `fee_sats_vb` is filled, which is required.
/// - If `fee_sats_vb` is filled with a value less than 1.0, which is below
/// the minimum allowed fee rate.
/// - If the provided outpoints do not match any available coins in the coin
/// store. (external inputs are not allowed for now)
/// - If the total inputs amount is less than the total outputs amount, making
/// the transaction invalid.
/// - If the maximum output is selected but there are not enough reserves to fill it.
/// - If the estimated fees exceed the available reserves.
/// - If there is an issue while handling the transaction history or if the
/// transaction cannot be created for any other reason.
///
/// # Note
///
/// This function is intended for use in scenarios where users need to gather
/// information about the transaction before finalizing it, allowing for
/// adjustments based on the simulation results.
#[allow(clippy::type_complexity)]
pub fn process_transaction(
&self,
tx_template: &TransactionTemplate,
) -> Result<
(
Vec<CoinEntry>, /* inputs */
Vec<(TxOut, Option<(AddrAccount, u32)>)>, /* outputs */
bool, /* change */
),
String,
> {
// TODO: implement coin selection if no or not enough input provided
if (tx_template.fee_sats > 0) && (tx_template.fee_sats_vb > 0.0) {
return Err("Only one of fee_sats or fee_sats_vb must be filled!".to_string());
} else if (tx_template.fee_sats == 0) && (tx_template.fee_sats_vb == 0.0) {
return Err("One of fee_sats or fee_sats_vb must be filled!".to_string());
} else if (tx_template.fee_sats == 0) && (tx_template.fee_sats_vb < 1.0) {
return Err("Minimum allowed fee rate is 1 sat/vb!".to_string());
}
if tx_template.outputs.is_empty() {
return Err("No outputs!".to_string());
} else if tx_template.inputs.is_empty() {
return Err("No inputs!".to_string());
}
let mut inputs_total = 0;
let mut outputs_total = 0;
// count maxed outputs
let mut maxed_outputs = 0;
let mut maxed_output = None;
for o in &tx_template.outputs {
if o.max {
if maxed_outputs > 0 {
return Err("A single output can have the MAX field selected".to_string());
} else {
maxed_outputs += 1;
}
}
}
// parse outpoints
let mut outpoints = vec![];
for inp in &tx_template.inputs {
let parsed = OutPoint::from_str(&inp.outpoint);
match parsed {
Ok(op) => outpoints.push(op),
Err(_) => return Err("Fail to parse Outpoint".to_string()),
}
}
// craft outputs
let mut outputs = vec![];
{
for out in &tx_template.outputs {
if !out.max {
outputs_total += out.amount;
}
// parse address & sanitize address
let addr = match bitcoin::Address::from_str(&out.address) {
Ok(a) => a,
Err(_) => return Err("Fail to parse address".to_string()),
};
if !addr.is_valid_for_network(self.config.network) {
return Err("Provided address is not valid for the current network".to_string());
}
let addr = addr.assume_checked();
let amount = if out.max {
bitcoin::Amount::ZERO
} else {
bitcoin::Amount::from_sat(out.amount)
};
let txout = bitcoin::TxOut {
value: amount,
script_pubkey: addr.script_pubkey(),
};
if out.max {
maxed_output = Some(addr.script_pubkey());
}
outputs.push((txout, None));
}
}
// get informations about coins to spend
let inputs = {
let store = self.coin_store.lock().expect("poisoned");
let mut inputs = Vec::<CoinEntry>::new();
for op in outpoints {
match store.get(&op) {
Some(coin) => {
inputs_total += coin.amount_sat();
inputs.push(coin);
}
// TODO: maybe support external inputs?
None => {
return Err("Provided outpoint do not match an available coin".to_string())
}
}
}
inputs
}; // <- release coin_store lock
let fee_reserve = inputs_total - outputs_total;
if maxed_output.is_some() && fee_reserve < DUST_AMOUNT {
return Err("Not enough reserve to fill maxed output!".to_string());
}
if tx_template.fee_sats > fee_reserve {
return Err("Not enough reserve to pay fees!".to_string());
}
// estimate the fee value if change is not needed
let tx_without_change = Self::assembly_tx(&inputs, &outputs);
let estimated_weight_without_change = match self.tx_estimated_weight(&tx_without_change) {
Ok(w) => w,
Err(e) => return Err(format!("Failed to estimate tx weight: {e:?}")),
};
let fees_without_change = if tx_template.fee_sats_vb > 0.0 {
let estimated_fees_without_change =
(tx_template.fee_sats_vb * estimated_weight_without_change as f64).ceil() as u64;
if estimated_fees_without_change > fee_reserve {
return Err("Not enough reserve to pay fees!".to_string());
}
estimated_fees_without_change
} else {
tx_template.fee_sats
};
let mut change = maxed_output.is_none() && (fee_reserve > DUST_AMOUNT);
let fees = if change {
// if a change output is expected we add a dummy output
let dummy_spk = self.dummy_spk();
let txout = bitcoin::TxOut {
// NOTE: putting a dummy 0 amount, will be adjusted
// after processing fees
value: bitcoin::Amount::from_sat(0),
// NOTE: we use here the dummy spk in order to make it easy to
// find which output we need to substract fees from in a later step.
script_pubkey: dummy_spk,
};
outputs.push((txout, None));
// process tx weight w/ the added change
let tx_with_change = Self::assembly_tx(&inputs, &outputs);
let estimated_weight_with_change = match self.tx_estimated_weight(&tx_with_change) {
Ok(w) => w,
Err(e) => return Err(format!("Failed to estimate tx weight: {e:?}")),
};
let mut fees = if tx_template.fee_sats_vb > 0.0 {
// fee rate is given, we estimate the fee value
let estimated_fees_with_change =
(tx_template.fee_sats_vb * estimated_weight_with_change as f64).ceil() as u64;
if estimated_fees_with_change > fee_reserve {
// if the reserve not contain enough for pay fees, we drop the change output
outputs.pop();
change = false;
fees_without_change
} else {
estimated_fees_with_change
}
} else {
// fee amount have been selected
let min_fee = estimated_weight_with_change;
if fee_reserve < min_fee {
outputs.pop();
change = false;
}
tx_template.fee_sats
};
if change {
// if the resulting change amount < DUST amount
// we drop the change output
let change_amount = fee_reserve - fees;
if change_amount < DUST_AMOUNT {
outputs.pop();
change = false;
fees = fee_reserve;
}
}
fees
} else {
fees_without_change
};
if fees > fee_reserve {
return Err("Not enough reserve to pay fees!".to_string());
}
// fill amount for maxed or change output
let change_or_max = bitcoin::Amount::from_sat(fee_reserve - fees);
if change {
outputs.last_mut().expect("as a last output").0.value = change_or_max;
} else {
if change_or_max.to_sat() < DUST_AMOUNT {
return Err("Maxed output amount is lower than the dust limit".to_string());
}
let dummy_spk = self.dummy_spk();
for (txout, _) in &mut outputs {
if txout.script_pubkey == dummy_spk {
txout.value = change_or_max;
}
}
}
// populate addresses indexes
{
let store = self.coin_store.lock().expect("poisoned");
for out in &mut outputs {
let spk = &out.0.script_pubkey;
// get derivation index of this address
// NOTE: this is needed by the signer to know it's a change/send-to-self
out.1 = store.address_info(spk).map(|e| (e.account(), e.index()));
}
} // <- release coin_store lock here
Ok((inputs, outputs, change))
}
pub fn change_index(&self, tx: &bitcoin::Transaction) -> Option<usize> {
let dummy_spk = self.dummy_spk();
for (index, TxOut { script_pubkey, .. }) in tx.output.iter().enumerate() {
if *script_pubkey == dummy_spk {
return Some(index);
}
}
None
}
/// Simulates a transaction based on the provided `TransactionTemplate`
///
/// This function processes the transaction template to estimate whether the
/// transaction can be successfully executed, including whether it is spendable
/// and if it requires change. It also calculates the estimated weight of the
/// transaction in weight units (WU).
///
/// # Arguments
///
/// * `tx_template` - A `TransactionTemplate` containing the details of the
/// transaction to be simulated.
///
/// # Returns
///
/// A `Result` containing:
/// - A tuple with three elements:
/// - A boolean indicating if the transaction is spendable.
/// - A boolean indicating if the transaction has change.
/// - An estimated weight of the transaction in weight units (WU).
///
/// # Errors
///
/// This function can return an error in the following cases:
/// - If the transaction processing fails due to invalid outpoints in
/// `tx_template.inputs`.
/// - If the provided outpoints do not match any available coins in the coin store
/// - If the addresses in `tx_template.outputs` cannot be parsed into valid
/// `bitcoin::Address` instances.
/// - If the parsed addresses are not valid for the current network.
/// - If the total inputs amount is less than the total outputs amount, making
/// the transaction invalid.
/// - If there is an issue while handling the transaction history or if the
/// transaction cannot be created for any other reason.
///
/// # Note
///
/// This function is intended for use in scenarios where users need to gather
/// information about the transaction before finalizing it, allowing for
/// adjustments based on the simulation results.
pub fn simulate_transaction(&self, tx_template: TransactionTemplate) -> TransactionSimulation {
let (inputs, outputs, has_change) = match self.process_transaction(&tx_template) {
Ok(r) => r,
Err(e) => {
return TransactionSimulation {
spendable: false,
has_change: false,
estimated_weight: 0,
error: e,
}
}
};
let tx = Self::assembly_tx(&inputs, &outputs);
let estimated_weight = match self.tx_estimated_weight(&tx) {
Ok(ew) => ew,
Err(e) => {
return TransactionSimulation {
spendable: false,
has_change: false,
estimated_weight: 0,
error: format!("{e:?}"),
}
}
};
TransactionSimulation {
spendable: true,
has_change,
estimated_weight,
error: String::new(),
}
}
/// Prepares a PSBT from a given `TransactionTemplate`.
///
/// This function processes the provided transaction template to create a
/// PSBT that is ready for signing.
/// It gathers the necessary inputs and outputs based on the transaction
/// template and populates the PSBT
/// with the appropriate descriptors for each input and output.
///
/// # Arguments
///
/// * `tx_template` - A `TransactionTemplate` containing the details of
/// the transaction to be processed.
/// This includes inputs, outputs, and fee information.
///
/// # Returns
///
/// A `Box<PsbtResult>` containing the following:
/// - `Ok(psbt)` - A successfully created PSBT as a string.
/// - `Err(String)` - An error message if the PSBT could not be created.
///
/// # Errors
///
/// This function can return an error in the following cases:
/// - If the provided `TransactionTemplate` is invalid or does not contain
/// the necessary information.
/// - If the inputs specified in the transaction template do not match any
/// available coins in the coin store.
/// - If the outputs specified in the transaction template cannot be parsed
/// into valid Bitcoin addresses.
/// - If the total input amount is less than the total output amount, making
/// the transaction invalid.
/// - If the fee specified is greater than the available reserves, preventing
/// the transaction from being processed.
/// - If there is an issue while creating the PSBT from the unsigned transaction,
/// such as invalid input data.
/// - If the function encounters any unexpected errors during processing.
///
/// # Note
///
/// This function is intended for use in scenarios where users need to prepare
/// a transaction for signing, allowing for adjustments based on the provided
/// transaction template before finalizing the transaction.
pub fn prepare_transaction(
&mut self,
tx_template: TransactionTemplate,
) -> Result<String /* PSBT */, String /* error */> {
let (inputs, mut outputs, change) = self.process_transaction(&tx_template)?;
// if there is a change, we replace the dummy spk by a freshly generated spk
if change {
let dummy_spk = self.dummy_spk();
for (txout, _) in &mut outputs {
if txout.script_pubkey == dummy_spk {
txout.script_pubkey = self.new_change_addr().script_pubkey();
}
}
}
let tx = Self::assembly_tx(&inputs, &outputs);
let mut psbt = bitcoin::Psbt::from_unsigned_tx(tx)
.map_err(|_| "Fail to generate PSBT from unsigned transaction".to_string())?;
let descriptor = self.config.descriptor.clone();
let mut descriptors = descriptor
.into_single_descriptors()
.expect("have a multipath")
.into_iter();
let receive = descriptors.next().expect("have a multipath");
let change = descriptors.next().expect("have a multipath");
// Populate PSBT inputs
for (index, coin) in inputs.iter().enumerate() {
// NOTE: for now we consider all inputs to be owned by this descriptor
let (account, addr_index) = coin.deriv();
let descriptor = match account {
AddrAccount::Receive => &receive,
AddrAccount::Change => &change,
};
let definite = descriptor
.at_derivation_index(addr_index)
.expect("has a wildcard");
if let Err(e) = psbt.update_input_with_descriptor(index, &definite) {
log::error!("fail to update PSBT input w/ descriptor: {e}");
return Err("Fail to update PSBT input with descriptor".into());
}
let input = psbt.inputs.get_mut(index).expect("valid index");
// TODO: allow sighash to be passed in the TransactionTemplate
input.sighash_type = Some(EcdsaSighashType::All.into());
input.witness_utxo = Some(coin.txout());
}
// Populate PSBT outputs
for (index, (_, deriv)) in outputs.iter().enumerate() {
if let Some((account, addr_index)) = deriv {
let descriptor = match *account {
AddrAccount::Receive => &receive,
AddrAccount::Change => &change,
};
let definite = descriptor
.at_derivation_index(*addr_index)
.expect("has a wildcard");
if let Err(e) = psbt.update_output_with_descriptor(index, &definite) {
log::error!("fail to update PSBT output w/ descriptor: {e}");
return Err("Fail to update PSBT output with descriptor".into());
}
}
}
Ok(psbt.to_string())
}
/// Sets the Electrum server URL and port for the account.
///
/// # Arguments
///
/// * `url` - The URL of the Electrum server.
/// * `port` - The port of the Electrum server.
pub fn set_electrum(&mut self, url: String, port: String) {
if let Ok(port) = port.parse::<u16>() {
self.config.electrum_url = Some(url);
self.config.electrum_port = Some(port);
self.config.to_file();
} else {
self.sender
.send(Notification::InvalidElectrumConfig)
.expect("cannot fail");
}
}
/// Starts the Electrum listener for the account.
pub fn start_electrum(&mut self) {
if let (None, Some(addr), Some(port)) = (
&self.tx_listener,
self.config.electrum_url.clone(),
self.config.electrum_port,
) {
let (tx_listener, electrum_stop) =
self.start_listen_txs(addr, port, self.config.clone());
self.coin_store.lock().expect("poisoned").init(tx_listener);
self.electrum_stop = Some(electrum_stop);
}
}
/// Stops the Electrum listener for the account.
pub fn stop_electrum(&mut self) {
if let Some(stop) = self.electrum_stop.as_mut() {
stop.store(true, Ordering::Relaxed);
}
self.electrum_stop = None;
}
/// Sets the look-ahead value for the account.
///
/// # Arguments
///
/// * `look_ahead` - The look-ahead value to set.
pub fn set_look_ahead(&mut self, look_ahead: String) {
if let Ok(la) = look_ahead.parse::<u32>() {
self.config.look_ahead = la;
self.config.to_file();
} else {
self.sender
.send(Notification::InvalidLookAhead)
.expect("cannot fail");
}
}
/// Returns the configuration of the account.
///
/// # Returns
///
/// A boxed `Config` instance.
pub fn get_config(&self) -> Config {
self.config.clone()
}
/// Returns the receiving address at the specified index as a string.
///
/// # Arguments
///
/// * `index` - The index of the receiving address.
///
/// # Returns
///
/// The receiving address as a string.
pub fn recv_addr_at(&self, index: u32) -> String {
self.coin_store
.lock()
.expect("poisoned")
.derivator_ref()
.receive_at(index)
.to_string()
}
/// Returns the change address at the specified index as a string.
///
/// # Arguments
///
/// * `index` - The index of the change address.
///
/// # Returns
///
/// The change address as a string.
pub fn change_addr_at(&self, index: u32) -> String {
self.coin_store
.lock()
.expect("poisoned")
.derivator_ref()
.change_at(index)
.to_string()
}
/// Generates a new receiving address entry for the account.
///
/// # Returns
///
/// A boxed `AddressEntry` instance.
pub fn new_addr(&mut self) -> RustAddress {
let addr = self.new_recv_addr();
let index = self.coin_store.lock().expect("poisoned").recv_tip();
AddressEntry {
status: AddressStatus::NotUsed,
address: addr.as_unchecked().clone(),
account: AddrAccount::Receive,
index,
}
.into()
}
/// Edits the label of a coin identified by the given outpoint.
///
/// # Arguments
///
/// * `outpoint` - A string representation of the outpoint for the coin.
/// * `label` - The new label to set for the coin. If the label is empty, the label will be removed.
pub fn edit_coin_label(&self, outpoint: String, label: String) {
if let Ok(outpoint) = bitcoin::OutPoint::from_str(&outpoint) {
if !label.is_empty() {
self.label_store
.lock()
.expect("poisoned")
.edit(LabelKey::OutPoint(outpoint), Some(label));
} else {
self.label_store
.lock()
.expect("poisoned")
.remove(LabelKey::OutPoint(outpoint));
}
}
if let Ok(mut store) = self.coin_store.try_lock() {
store.generate();
}
}
pub fn sign(&self, psbt: String) {
self.signing_manager.sign(self.config.network(), psbt);
}
}
// /// Creates a new account with the specified account name.
// ///
// /// # Arguments
// ///
// /// * `account` - The name of the account.
// ///
// /// # Returns
// ///
// /// A boxed `Account` instance.
// pub fn new_account(account: String) -> Box<Account> {
// let config = Config::from_file(account);
//
// let account = Account::new(config);
// account.boxed()
// }
macro_rules! send_notif {
($notification:expr, $request:expr, $msg:expr) => {
let res = $notification.send($msg.into());
if res.is_err() {
// stop detached client
let _ = $request.send(CoinRequest::Stop);
return;
}
};
}
macro_rules! send_electrum {
($request:expr, $notification:expr, $msg:expr) => {
if $request.send($msg).is_err() {
send_notif!($notification, $request, TxListenerNotif::Stopped);
return;
}
};
}
/// Listens for transactions on the specified address and port.
///
/// # Arguments
///
/// * `addr` - The address to listen on.
/// * `port` - The port to listen on.
/// * `coin_store` - The coin store to update with transaction data.
/// * `signer` - The signer for the account.
/// * `notification` - The sender for notifications.
/// * `address_tip` - The receiver for address tips.
/// * `stop_request` - The stop flag for the listener.
#[allow(clippy::too_many_arguments)]
fn listen_txs<T: From<TxListenerNotif>>(
coin_store: Arc<Mutex<CoinStore>>,
derivator: Derivator,
notification: mpsc::Sender<T>,
address_tip: mpsc::Receiver<AddressTip>,
stop_request: Arc<AtomicBool>,
request: mpsc::Sender<CoinRequest>,
response: mpsc::Receiver<CoinResponse>,
config: Option<Config>,
) {
log::info!("listen_txs(): started");
send_notif!(notification, request, TxListenerNotif::Started);
let mut statuses = if let Some(config) = &config {
config.statuses_from_file()
} else {
BTreeMap::<ScriptBuf, (Option<String>, u32, u32)>::new()
};
if !statuses.is_empty() {
let sub: Vec<_> = statuses.keys().cloned().collect();
send_electrum!(request, notification, CoinRequest::Subscribe(sub));
}
fn persist_status(
config: &Option<Config>,
statuses: &BTreeMap<ScriptBuf, (Option<String>, u32, u32)>,
) {
if let Some(cfg) = config.as_ref() {
cfg.persist_statuses(statuses);
}
}
let mut backoff = Backoff::new_ms(20);
loop {
// stop request from consumer side
if stop_request.load(Ordering::Relaxed) {
send_notif!(notification, request, TxListenerNotif::Stopped);
let _ = request.send(CoinRequest::Stop);
return;
}
let mut received = false;
// listen for AddressTip update
match address_tip.try_recv() {
Ok(tip) => {
log::debug!("listen_txs() receive {tip:?}");
let AddressTip { recv, change } = tip;
received = true;
let mut sub = vec![];
let r_spk = derivator.receive_at(recv).script_pubkey();
if !statuses.contains_key(&r_spk) {
// FIXME: here we can be smart an not start at 0 but at `actual_tip`
for i in 0..recv {
let spk = derivator.receive_at(i).script_pubkey();
if !statuses.contains_key(&spk) {
statuses.insert(spk.clone(), (None, 0, i));
persist_status(&config, &statuses);
sub.push(spk);
}
}
}
let c_spk = derivator.change_at(recv).script_pubkey();
if !statuses.contains_key(&c_spk) {
// FIXME: here we can be smart an not start at 0 but at `actual_tip`
for i in 0..change {
let spk = derivator.change_at(i).script_pubkey();
if !statuses.contains_key(&spk) {
statuses.insert(spk.clone(), (None, 1, i));
persist_status(&config, &statuses);
sub.push(spk);
}
}
}
if !sub.is_empty() {
send_electrum!(request, notification, CoinRequest::Subscribe(sub));
}
}
Err(e) => match e {
mpsc::TryRecvError::Empty => {}
mpsc::TryRecvError::Disconnected => {
log::error!("listen_txs(): address store disconnected");
send_notif!(
notification,
request,
TxListenerNotif::Error("AddressStore disconnected".to_string())
);
// FIXME: what should we do there?
// it's AddressStore being dropped, but she should keep upating
// the actual spk set even if it cannot grow anymore
}
},
}
// listen for response
match response.try_recv() {
Ok(rsp) => {
log::debug!("listen_txs() receive {rsp:#?}");
received = true;
match rsp {
CoinResponse::Status(elct_status) => {
let mut history = vec![];
for (spk, status) in elct_status {
if let Some((s, _, _)) = statuses.get_mut(&spk) {
// status is registered
if *s != status {
// status changed
if status.is_some() {
// status is not empty so we ask for txs changes
history.push(spk);
} else {
// status change from Some(_) to None we directly update
// coin_store
let mut store = coin_store.lock().expect("poisoned");
let mut map = BTreeMap::new();
map.insert(spk.clone(), vec![]);
let _ = store.handle_history_response(map);
store.generate();
}
// record the local status change
*s = status;
}
} else if status.is_some() {
// status is not None & not registered
statuses.entry(spk.clone()).and_modify(|s| s.0 = status);
persist_status(&config, &statuses);
history.push(spk);
} else {
// status is None & not registered
// record local status
statuses.entry(spk.clone()).and_modify(|s| s.0 = status);
persist_status(&config, &statuses);
// update coin_store
let mut store = coin_store.lock().expect("poisoned");
let mut map = BTreeMap::new();
map.insert(spk.clone(), vec![]);
let _ = store.handle_history_response(map);
}
}
if !history.is_empty() {
let hist = CoinRequest::History(history);
log::debug!("listen_txs() send {:#?}", hist);
send_electrum!(request, notification, hist);
}
persist_status(&config, &statuses);
}
CoinResponse::History(map) => {
let mut store = coin_store.lock().expect("poisoned");
let (height_updated, missing_txs) = store.handle_history_response(map);
if !missing_txs.is_empty() {
send_electrum!(request, notification, CoinRequest::Txs(missing_txs));
}
if height_updated {
store.generate();
}
}
CoinResponse::Txs(txs) => {
let mut store = coin_store.lock().expect("poisoned");
store.handle_txs_response(txs);
}
CoinResponse::Stopped => {
send_notif!(notification, request, TxListenerNotif::Stopped);
let _ = request.send(CoinRequest::Stop);
return;
}
CoinResponse::Error(e) => {
send_notif!(notification, request, TxListenerNotif::Error(e));
}
}
}
Err(e) => match e {
mpsc::TryRecvError::Empty => {}
mpsc::TryRecvError::Disconnected => {
// NOTE: here the electrum client is dropped, we cannot continue
log::error!("listen_txs() electrum client stopped unexpectedly");
send_notif!(notification, request, TxListenerNotif::Stopped);
let _ = request.send(CoinRequest::Stop);
return;
}
},
}
if received {
continue;
}
backoff.snooze();
}
}
#[cfg(test)]
mod tests {
use std::{str::FromStr, sync::mpsc::TryRecvError, time::Duration};
use {bip39, miniscript::bitcoin::bip32::DerivationPath};
use crate::{
descriptor::wpkh,
signer::HotSigner,
test_utils::{funding_tx, setup_logger, spending_tx},
tx_store::TxStore,
};
use super::*;
struct CoinStoreMock {
pub store: Arc<Mutex<CoinStore>>,
pub notif: mpsc::Receiver<Notification>,
pub request: mpsc::Receiver<CoinRequest>,
pub response: mpsc::Sender<CoinResponse>,
pub listener: JoinHandle<()>,
pub stop: Arc<AtomicBool>,
pub derivator: Derivator,
}
impl Drop for CoinStoreMock {
fn drop(&mut self) {
self.stop.store(true, Ordering::Relaxed);
}
}
impl CoinStoreMock {
fn new(recv_tip: u32, change_tip: u32, look_ahead: u32) -> Self {
let (notif_sender, notif_recv) = mpsc::channel();
let (tip_sender, tip_receiver) = mpsc::channel();
let (req_sender, req_receiver) = mpsc::channel();
let (resp_sender, resp_receiver) = mpsc::channel();
let mnemonic = bip39::Mnemonic::generate(12).unwrap();
let stop = Arc::new(AtomicBool::new(false));
let signer =
HotSigner::new_from_mnemonics(bitcoin::Network::Regtest, &mnemonic.to_string())
.unwrap();
let xpub = signer.xpub(&DerivationPath::from_str("m/84'/0'/0'/1").unwrap());
let descriptor = wpkh(xpub);
let derivator = Derivator::new(descriptor.clone(), bitcoin::Network::Regtest).unwrap();
let tx_store = TxStore::new(Default::default(), None);
let label_store = Arc::new(Mutex::new(LabelStore::new()));
let coin_store = Arc::new(Mutex::new(CoinStore::new(
bitcoin::Network::Regtest,
descriptor.clone(),
notif_sender.clone(),
recv_tip,
change_tip,
look_ahead,
tx_store,
label_store,
None,
)));
coin_store.lock().expect("poisoned").init(tip_sender);
let store = coin_store.clone();
let cloned_stop = stop.clone();
let cloned_derivator = derivator.clone();
let listener_handle = thread::spawn(move || {
listen_txs(
coin_store,
cloned_derivator,
notif_sender,
tip_receiver,
stop,
req_sender,
resp_receiver,
None,
);
});
CoinStoreMock {
store,
notif: notif_recv,
request: req_receiver,
response: resp_sender,
listener: listener_handle,
stop: cloned_stop,
derivator,
}
}
fn coins(&mut self) -> BTreeMap<OutPoint, CoinEntry> {
self.store.lock().expect("poisoned").coins()
}
fn stop(&self) {
self.stop.store(true, Ordering::Relaxed);
}
}
#[test]
fn simple_start_stop() {
setup_logger();
let mock = CoinStoreMock::new(0, 0, 20);
thread::sleep(Duration::from_millis(10));
assert!(!mock.listener.is_finished());
assert!(matches!(
mock.notif.try_recv().unwrap(),
Notification::AddressTipChanged,
));
assert!(matches!(
mock.notif.try_recv().unwrap(),
Notification::Electrum(TxListenerNotif::Started)
));
mock.stop();
thread::sleep(Duration::from_secs(1));
assert!(mock.listener.is_finished());
}
fn simple_recv() -> (bitcoin::Transaction, CoinStoreMock) {
setup_logger();
let look_ahead = 5;
let mut mock = CoinStoreMock::new(0, 0, look_ahead);
thread::sleep(Duration::from_millis(500));
assert!(!mock.listener.is_finished());
assert!(matches!(
mock.notif.try_recv().unwrap(),
Notification::AddressTipChanged,
));
assert!(matches!(
mock.notif.try_recv().unwrap(),
Notification::Electrum(TxListenerNotif::Started)
));
let mut init_spks = vec![];
for i in 0..(look_ahead + 1) {
let spk = mock.derivator.receive_spk_at(i);
init_spks.push(spk);
}
for i in 0..(look_ahead + 1) {
let spk = mock.derivator.change_spk_at(i);
init_spks.push(spk);
}
// receive initial subscriptions
if let Ok(CoinRequest::Subscribe(v)) = mock.request.try_recv() {
// NOTE: we expect (tip + 1 + look_ahead )
assert_eq!(v.len(), 12);
for spk in &init_spks {
assert!(v.contains(spk));
}
} else {
panic!()
}
// electrum server send spks statuses (None)
let statuses: BTreeMap<_, _> = init_spks.clone().into_iter().map(|s| (s, None)).collect();
mock.response.send(CoinResponse::Status(statuses)).unwrap();
thread::sleep(Duration::from_millis(100));
assert!(mock.coins().is_empty());
let spk_recv_0 = mock.derivator.receive_spk_at(0);
// server send a status update at recv(0)
let mut statuses = BTreeMap::new();
statuses.insert(spk_recv_0.clone(), Some("1_tx_unco".to_string()));
mock.response.send(CoinResponse::Status(statuses)).unwrap();
thread::sleep(Duration::from_millis(100));
// server should receive an history request for this spk
if let Ok(CoinRequest::History(v)) = mock.request.try_recv() {
assert!(v == vec![spk_recv_0.clone()]);
} else {
panic!()
}
thread::sleep(Duration::from_millis(100));
let tx_0 = funding_tx(spk_recv_0.clone(), 0.1);
// server must send history response
let mut history = BTreeMap::new();
history.insert(spk_recv_0.clone(), vec![(tx_0.compute_txid(), None)]);
mock.response.send(CoinResponse::History(history)).unwrap();
thread::sleep(Duration::from_millis(100));
// server should receive a tx request
if let Ok(CoinRequest::Txs(v)) = mock.request.try_recv() {
assert!(v == vec![tx_0.compute_txid()]);
} else {
panic!()
}
thread::sleep(Duration::from_millis(100));
// server send the requested tx
mock.response
.send(CoinResponse::Txs(vec![tx_0.clone()]))
.unwrap();
thread::sleep(Duration::from_millis(100));
// now the store contain one coin
let mut coins = mock.coins();
assert_eq!(coins.len(), 1);
let coin = coins.pop_first().unwrap().1;
// the coin is unconfirmed
assert_eq!(coin.height(), None);
assert_eq!(coin.status(), CoinStatus::Unconfirmed);
// NOTE: the coin is now confirmed
// server send a status update at recv(0)
let mut statuses = BTreeMap::new();
statuses.insert(spk_recv_0.clone(), Some("1_tx_conf".to_string()));
mock.response.send(CoinResponse::Status(statuses)).unwrap();
thread::sleep(Duration::from_millis(100));
// server should receive an history request for this spk
if let Ok(CoinRequest::History(v)) = mock.request.try_recv() {
assert!(v == vec![spk_recv_0.clone()]);
} else {
panic!()
}
thread::sleep(Duration::from_millis(100));
// server must send history response
let mut history = BTreeMap::new();
// the coin have now 1 confirmation
history.insert(spk_recv_0.clone(), vec![(tx_0.compute_txid(), Some(1))]);
mock.response.send(CoinResponse::History(history)).unwrap();
thread::sleep(Duration::from_millis(100));
// NOTE: coin_store already have the tx it should not ask it
assert!(matches!(mock.request.try_recv(), Err(TryRecvError::Empty)));
// the coin is now confirmed
let mut coins = mock.coins();
assert_eq!(coins.len(), 1);
let coin = coins.pop_first().unwrap().1;
assert_eq!(coin.height(), Some(1));
assert_eq!(coin.status(), CoinStatus::Confirmed);
(tx_0, mock)
}
#[test]
fn recv_and_spend() {
// init & receive one coin
let (tx_0, mut mock) = simple_recv();
let spk_recv_0 = mock.derivator.receive_spk_at(0);
// spend this coin
let outpoint = mock.coins().pop_first().unwrap().0;
let tx_1 = spending_tx(outpoint);
// NOTE: the coin is now spent
// server send a status update at recv(0)
let mut statuses = BTreeMap::new();
statuses.insert(spk_recv_0.clone(), Some("1_tx_spent".to_string()));
mock.response.send(CoinResponse::Status(statuses)).unwrap();
thread::sleep(Duration::from_millis(100));
// server should receive an history request for this spk
if let Ok(CoinRequest::History(v)) = mock.request.try_recv() {
assert!(v == vec![spk_recv_0.clone()]);
} else {
panic!()
}
thread::sleep(Duration::from_millis(100));
// server must send history response
let mut history = BTreeMap::new();
// the coin have now 1 confirmation
history.insert(
spk_recv_0.clone(),
vec![(tx_0.compute_txid(), Some(1)), (tx_1.compute_txid(), None)],
);
mock.response.send(CoinResponse::History(history)).unwrap();
thread::sleep(Duration::from_millis(100));
// server should receive a tx request only for tx_1
if let Ok(CoinRequest::Txs(v)) = mock.request.try_recv() {
assert!(v == vec![tx_1.compute_txid()]);
} else {
panic!()
}
// server send the requested tx
mock.response
.send(CoinResponse::Txs(vec![tx_1.clone()]))
.unwrap();
thread::sleep(Duration::from_millis(100));
// now the store contain one spent coin
let mut coins = mock.coins();
assert_eq!(coins.len(), 1);
let coin = coins.pop_first().unwrap().1;
// the coin is unconfirmed
assert_eq!(coin.status(), CoinStatus::Spent);
}
#[test]
fn simple_reorg() {
// init & receive one coin
let (tx_0, mut mock) = simple_recv();
let spk_recv_0 = mock.derivator.receive_spk_at(0);
// NOTE: the coin is now spent we can reorg it
// server send a status update at recv(0)
let mut statuses = BTreeMap::new();
statuses.insert(spk_recv_0.clone(), Some("1_tx_reorg".to_string()));
mock.response.send(CoinResponse::Status(statuses)).unwrap();
thread::sleep(Duration::from_millis(100));
// server should receive an history request for this spk
if let Ok(CoinRequest::History(v)) = mock.request.try_recv() {
assert!(v == vec![spk_recv_0.clone()]);
} else {
panic!()
}
thread::sleep(Duration::from_millis(100));
// server must send history response
let mut history = BTreeMap::new();
// NOTE: confirmation height is changed to 2
history.insert(spk_recv_0.clone(), vec![(tx_0.compute_txid(), Some(2))]);
mock.response.send(CoinResponse::History(history)).unwrap();
thread::sleep(Duration::from_millis(100));
// server do not receive a tx request as the store already go the tx
assert!(matches!(mock.request.try_recv(), Err(TryRecvError::Empty)));
// the store still contain one spent coin
let mut coins = mock.coins();
assert_eq!(coins.len(), 1);
let coin = coins.pop_first().unwrap().1;
// the coin have a confirmation height of 2
assert_eq!(coin.height(), Some(2));
}
}