-
Notifications
You must be signed in to change notification settings - Fork 37
/
nodemanager.rs
2791 lines (2474 loc) · 94.8 KB
/
nodemanager.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use anyhow::anyhow;
use lightning::sign::{NodeSigner, Recipient};
use std::sync::atomic::{AtomicBool, Ordering};
use std::{collections::HashMap, ops::Deref, sync::Arc};
use crate::logging::LOGGING_KEY;
use crate::redshift::{RedshiftManager, RedshiftStatus, RedshiftStorage};
use crate::scb::{
EncryptedSCB, StaticChannelBackup, StaticChannelBackupStorage,
SCB_ENCRYPTION_KEY_DERIVATION_PATH,
};
use crate::storage::{MutinyStorage, KEYCHAIN_STORE_KEY};
use crate::utils::sleep;
use crate::{auth::MutinyAuthClient, gossip::*};
use crate::{
chain::MutinyChain,
error::MutinyError,
esplora::EsploraSyncClient,
fees::MutinyFeeEstimator,
gossip, keymanager,
logging::MutinyLogger,
lspclient::LspClient,
node::{Node, ProbScorer, PubkeyConnectionInfo, RapidGossipSync},
onchain::get_esplora_url,
onchain::OnChainWallet,
utils,
};
use crate::{
event::{HTLCStatus, PaymentInfo},
lnurlauth::make_lnurl_auth_connection,
};
use crate::{labels::LabelStorage, subscription::MutinySubscriptionClient};
use crate::{
lnurlauth::{AuthManager, AuthProfile},
MutinyWalletConfig,
};
use bdk::chain::{BlockId, ConfirmationTime};
use bdk::{wallet::AddressIndex, LocalUtxo};
use bdk_esplora::esplora_client::AsyncClient;
use bip39::Mnemonic;
use bitcoin::blockdata::script;
use bitcoin::hashes::hex::ToHex;
use bitcoin::hashes::{sha256, Hash};
use bitcoin::secp256k1::{rand, PublicKey, Secp256k1, SecretKey};
use bitcoin::util::bip32::{DerivationPath, ExtendedPrivKey};
use bitcoin::{Address, Network, OutPoint, Transaction, Txid};
use core::time::Duration;
use futures::{future::join_all, lock::Mutex};
use lightning::chain::chaininterface::{ConfirmationTarget, FeeEstimator};
use lightning::chain::Confirm;
use lightning::events::ClosureReason;
use lightning::io::Read;
use lightning::ln::channelmanager::{ChannelDetails, PhantomRouteHints};
use lightning::ln::msgs::DecodeError;
use lightning::ln::PaymentHash;
use lightning::routing::gossip::NodeId;
use lightning::util::logger::*;
use lightning::util::ser::{Readable, Writeable, Writer};
use lightning::{log_debug, log_error, log_info, log_warn};
use lightning_invoice::{Invoice, InvoiceDescription};
use lnurl::lnurl::LnUrl;
use lnurl::{AsyncClient as LnUrlClient, LnUrlResponse, Response};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::str::FromStr;
use uuid::Uuid;
const BITCOIN_PRICE_CACHE_SEC: u64 = 300;
// This is the NodeStorage object saved to the DB
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct NodeStorage {
pub nodes: HashMap<String, NodeIndex>,
}
// This is the NodeIndex reference that is saved to the DB
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
pub struct NodeIndex {
pub child_index: u32,
pub lsp: Option<String>,
pub archived: Option<bool>,
}
impl NodeIndex {
pub fn is_archived(&self) -> bool {
self.archived.unwrap_or(false)
}
}
impl Writeable for NodeIndex {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), lightning::io::Error> {
// Write the archived flag, 1 if archived, 0 if not
if self.archived.unwrap_or(false) {
writer.write_all(&[1])?;
} else {
writer.write_all(&[0])?;
}
// Write the child index
writer.write_all(&self.child_index.to_be_bytes())?;
// Write the lsp
match self.lsp {
Some(ref lsp) => {
let bytes = lsp.as_bytes();
let len = bytes.len() as u32;
writer.write_all(&len.to_be_bytes())?;
writer.write_all(bytes)?;
}
None => {
let len: u32 = 0;
writer.write_all(&len.to_be_bytes())?;
}
}
Ok(())
}
}
impl Readable for NodeIndex {
fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
// Read the archived flag
let mut archived = [0; 1];
reader.read_exact(&mut archived)?;
let archived = archived[0] == 1;
// Read the child index
let child_index: u32 = Readable::read(reader)?;
// Read the lsp
let lsp_len: u32 = Readable::read(reader)?;
let lsp = if lsp_len > 0 {
let mut lsp = Vec::with_capacity(lsp_len as usize);
reader.take(lsp_len as u64).read_to_end(&mut lsp)?;
Some(String::from_utf8(lsp).unwrap())
} else {
None
};
Ok(NodeIndex {
child_index,
lsp,
archived: Some(archived),
})
}
}
// This is the NodeIdentity that refer to a specific node
// Used for public facing identification.
pub struct NodeIdentity {
pub uuid: String,
pub pubkey: PublicKey,
}
#[derive(Serialize, Deserialize, Clone, Eq, PartialEq)]
pub struct MutinyBip21RawMaterials {
pub address: Address,
pub invoice: Invoice,
pub btc_amount: Option<String>,
pub labels: Vec<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)]
pub struct MutinyInvoice {
pub bolt11: Option<Invoice>,
pub description: Option<String>,
pub payment_hash: sha256::Hash,
pub preimage: Option<String>,
pub payee_pubkey: Option<PublicKey>,
pub amount_sats: Option<u64>,
pub expire: u64,
pub paid: bool,
pub fees_paid: Option<u64>,
pub inbound: bool,
pub labels: Vec<String>,
pub last_updated: u64,
}
impl From<Invoice> for MutinyInvoice {
fn from(value: Invoice) -> Self {
let description = match value.description() {
InvoiceDescription::Direct(a) => {
if a.is_empty() {
None
} else {
Some(a.to_string())
}
}
InvoiceDescription::Hash(_) => None,
};
let timestamp = value.duration_since_epoch().as_secs();
let expiry = timestamp + value.expiry_time().as_secs();
let payment_hash = value.payment_hash().to_owned();
let payee_pubkey = value.payee_pub_key().map(|p| p.to_owned());
let amount_sats = value.amount_milli_satoshis().map(|m| m / 1000);
MutinyInvoice {
bolt11: Some(value),
description,
payment_hash,
preimage: None,
payee_pubkey,
amount_sats,
expire: expiry,
paid: false,
fees_paid: None,
inbound: true,
labels: vec![],
last_updated: timestamp,
}
}
}
impl MutinyInvoice {
pub(crate) fn from(
i: PaymentInfo,
payment_hash: PaymentHash,
inbound: bool,
labels: Vec<String>,
) -> Result<Self, MutinyError> {
match i.bolt11 {
Some(invoice) => {
// Construct an invoice from a bolt11, easy
let amount_sats = if let Some(inv_amt) = invoice.amount_milli_satoshis() {
if inv_amt == 0 {
i.amt_msat.0.map(|a| a / 1_000)
} else {
Some(inv_amt / 1_000)
}
} else {
i.amt_msat.0.map(|a| a / 1_000)
};
Ok(MutinyInvoice {
inbound,
last_updated: i.last_update,
paid: i.status == HTLCStatus::Succeeded,
labels,
amount_sats,
payee_pubkey: i.payee_pubkey,
preimage: i.preimage.map(|p| p.to_hex()),
fees_paid: i.fee_paid_msat.map(|f| f / 1_000),
..invoice.into()
})
}
None => {
let paid = i.status == HTLCStatus::Succeeded;
let amount_sats: Option<u64> = i.amt_msat.0.map(|s| s / 1_000);
let fees_paid = i.fee_paid_msat.map(|f| f / 1_000);
let preimage = i.preimage.map(|p| p.to_hex());
let payment_hash = sha256::Hash::from_inner(payment_hash.0);
let invoice = MutinyInvoice {
bolt11: None,
description: None,
payment_hash,
preimage,
payee_pubkey: i.payee_pubkey,
amount_sats,
expire: i.last_update,
paid,
fees_paid,
inbound,
labels,
last_updated: i.last_update,
};
Ok(invoice)
}
}
}
}
#[derive(Serialize, Deserialize, Clone, Eq, PartialEq)]
pub struct MutinyPeer {
pub pubkey: PublicKey,
pub connection_string: Option<String>,
pub alias: Option<String>,
pub color: Option<String>,
pub label: Option<String>,
pub is_connected: bool,
}
impl PartialOrd for MutinyPeer {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for MutinyPeer {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.is_connected
.cmp(&other.is_connected)
.then_with(|| self.alias.cmp(&other.alias))
.then_with(|| self.pubkey.cmp(&other.pubkey))
.then_with(|| self.connection_string.cmp(&other.connection_string))
}
}
#[derive(Serialize, Deserialize, Clone, Eq, PartialEq)]
pub struct MutinyChannel {
pub user_chan_id: String,
pub balance: u64,
pub size: u64,
pub reserve: u64,
pub outpoint: Option<OutPoint>,
pub peer: PublicKey,
pub confirmations_required: Option<u32>,
pub confirmations: u32,
}
impl From<&ChannelDetails> for MutinyChannel {
fn from(c: &ChannelDetails) -> Self {
MutinyChannel {
user_chan_id: c.user_channel_id.to_hex(),
balance: c.outbound_capacity_msat / 1_000,
size: c.channel_value_satoshis,
reserve: c.unspendable_punishment_reserve.unwrap_or(0),
outpoint: c.funding_txo.map(|f| f.into_bitcoin_outpoint()),
peer: c.counterparty.node_id,
confirmations_required: c.confirmations_required,
confirmations: c.confirmations.unwrap_or(0),
}
}
}
/// A wallet transaction
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct TransactionDetails {
/// Optional transaction
pub transaction: Option<Transaction>,
/// Transaction id
pub txid: Txid,
/// Received value (sats)
/// Sum of owned outputs of this transaction.
pub received: u64,
/// Sent value (sats)
/// Sum of owned inputs of this transaction.
pub sent: u64,
/// Fee value in sats if it was available.
pub fee: Option<u64>,
/// If the transaction is confirmed, contains height and Unix timestamp of the block containing the
/// transaction, unconfirmed transaction contains `None`.
pub confirmation_time: ConfirmationTime,
/// Labels associated with this transaction
pub labels: Vec<String>,
}
impl PartialOrd for TransactionDetails {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for TransactionDetails {
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
self.confirmation_time
.cmp(&other.confirmation_time)
.then_with(|| self.txid.cmp(&other.txid))
}
}
impl From<bdk::TransactionDetails> for TransactionDetails {
fn from(t: bdk::TransactionDetails) -> Self {
TransactionDetails {
transaction: t.transaction,
txid: t.txid,
received: t.received,
sent: t.sent,
fee: t.fee,
confirmation_time: t.confirmation_time,
labels: vec![],
}
}
}
/// Information about a channel that was closed.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)]
pub struct ChannelClosure {
pub user_channel_id: Option<[u8; 16]>,
pub channel_id: Option<[u8; 32]>,
pub node_id: Option<PublicKey>,
pub reason: String,
pub timestamp: u64,
}
impl ChannelClosure {
pub fn new(
user_channel_id: u128,
channel_id: [u8; 32],
node_id: Option<PublicKey>,
reason: ClosureReason,
) -> Self {
Self {
user_channel_id: Some(user_channel_id.to_be_bytes()),
channel_id: Some(channel_id),
node_id,
reason: reason.to_string(),
timestamp: utils::now().as_secs(),
}
}
}
impl PartialOrd for ChannelClosure {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for ChannelClosure {
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
self.timestamp.cmp(&other.timestamp)
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub enum ActivityItem {
OnChain(TransactionDetails),
Lightning(Box<MutinyInvoice>),
ChannelClosed(ChannelClosure),
}
impl ActivityItem {
pub fn last_updated(&self) -> Option<u64> {
match self {
ActivityItem::OnChain(t) => match t.confirmation_time {
ConfirmationTime::Confirmed { time, .. } => Some(time),
ConfirmationTime::Unconfirmed { last_seen } => Some(last_seen),
},
ActivityItem::Lightning(i) => Some(i.last_updated),
ActivityItem::ChannelClosed(c) => Some(c.timestamp),
}
}
pub fn labels(&self) -> Vec<String> {
match self {
ActivityItem::OnChain(t) => t.labels.clone(),
ActivityItem::Lightning(i) => i.labels.clone(),
ActivityItem::ChannelClosed(_) => vec![],
}
}
pub fn is_channel_open(&self) -> bool {
match self {
ActivityItem::OnChain(onchain) => {
onchain.labels.iter().any(|l| l.contains("LN Channel:"))
}
ActivityItem::Lightning(_) => false,
ActivityItem::ChannelClosed(_) => false,
}
}
}
impl PartialOrd for ActivityItem {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for ActivityItem {
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
// We want None to be greater than Some because those are pending transactions
// so those should be at the top of the list
match (self.last_updated(), other.last_updated()) {
(Some(self_time), Some(other_time)) => self_time.cmp(&other_time),
(Some(_), None) => core::cmp::Ordering::Less,
(None, Some(_)) => core::cmp::Ordering::Greater,
(None, None) => core::cmp::Ordering::Equal,
}
}
}
pub struct MutinyBalance {
pub confirmed: u64,
pub unconfirmed: u64,
pub lightning: u64,
pub force_close: u64,
}
pub struct LnUrlParams {
pub max: u64,
pub min: u64,
pub tag: String,
}
/// Plan is a subscription plan for Mutiny+
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Plan {
/// The ID of the internal plan.
/// Used for subscribing to specific one.
pub id: u8,
/// The amount in sats for the plan.
pub amount_sat: u64,
}
/// The [NodeManager] is the main entry point for interacting with the Mutiny Wallet.
/// It is responsible for managing the on-chain wallet and the lightning nodes.
///
/// It can be used to create a new wallet, or to load an existing wallet.
///
/// It can be configured to use all different custom backend services, or to use the default
/// services provided by Mutiny.
pub struct NodeManager<S: MutinyStorage> {
pub(crate) stop: Arc<AtomicBool>,
mnemonic: Mnemonic,
network: Network,
#[cfg(target_arch = "wasm32")]
websocket_proxy_addr: String,
esplora: Arc<AsyncClient>,
wallet: Arc<OnChainWallet<S>>,
gossip_sync: Arc<RapidGossipSync>,
scorer: Arc<utils::Mutex<ProbScorer>>,
chain: Arc<MutinyChain<S>>,
fee_estimator: Arc<MutinyFeeEstimator<S>>,
pub(crate) storage: S,
pub(crate) node_storage: Mutex<NodeStorage>,
pub(crate) nodes: Arc<Mutex<HashMap<PublicKey, Arc<Node<S>>>>>,
auth: AuthManager<S>,
lnurl_client: Arc<LnUrlClient>,
pub(crate) lsp_clients: Vec<LspClient>,
pub(crate) subscription_client: Option<Arc<MutinySubscriptionClient<S>>>,
pub(crate) logger: Arc<MutinyLogger>,
bitcoin_price_cache: Arc<Mutex<Option<(f32, Duration)>>>,
do_not_connect_peers: bool,
}
impl<S: MutinyStorage> NodeManager<S> {
/// Returns if there is a saved wallet in storage.
/// This is checked by seeing if a mnemonic seed exists in storage.
pub fn has_node_manager(storage: S) -> bool {
storage.get_mnemonic().is_ok()
}
/// Creates a new [NodeManager] with the given parameters.
/// The mnemonic seed is read from storage, unless one is provided.
/// If no mnemonic is provided, a new one is generated and stored.
pub async fn new(c: MutinyWalletConfig, storage: S) -> Result<NodeManager<S>, MutinyError> {
let stop = Arc::new(AtomicBool::new(false));
#[cfg(target_arch = "wasm32")]
let websocket_proxy_addr = c
.websocket_proxy_addr
.unwrap_or_else(|| String::from("wss://p.mutinywallet.com"));
let network: Network = c.network.unwrap_or(Network::Bitcoin);
let mnemonic = match c.mnemonic {
Some(seed) => storage.insert_mnemonic(seed)?,
None => match storage.get_mnemonic() {
Ok(mnemonic) => mnemonic,
Err(_) => {
let seed = keymanager::generate_seed(12)?;
storage.insert_mnemonic(seed)?
}
},
};
let logger = Arc::new(MutinyLogger::with_writer(stop.clone(), storage.clone()));
let esplora_server_url = get_esplora_url(network, c.user_esplora_url);
let tx_sync = Arc::new(EsploraSyncClient::new(esplora_server_url, logger.clone()));
let esplora = Arc::new(tx_sync.client().clone());
let fee_estimator = Arc::new(MutinyFeeEstimator::new(
storage.clone(),
esplora.clone(),
logger.clone(),
));
let wallet = Arc::new(OnChainWallet::new(
&mnemonic,
storage.clone(),
network,
esplora.clone(),
fee_estimator.clone(),
stop.clone(),
logger.clone(),
)?);
let chain = Arc::new(MutinyChain::new(tx_sync, wallet.clone(), logger.clone()));
let (gossip_sync, scorer) =
gossip::get_gossip_sync(&storage, c.user_rgs_url, network, logger.clone()).await?;
let scorer = Arc::new(utils::Mutex::new(scorer));
let gossip_sync = Arc::new(gossip_sync);
// load lsp clients, if any
let lsp_clients: Vec<LspClient> = match c.lsp_url.clone() {
// check if string is some and not an empty string
Some(lsp_urls) if !lsp_urls.is_empty() => {
let urls: Vec<&str> = lsp_urls.split(',').collect();
let futs = urls.into_iter().map(|url| LspClient::new(url.trim()));
let results = futures::future::join_all(futs).await;
results
.into_iter()
.flat_map(|res| match res {
Ok(client) => Some(client),
Err(e) => {
log_warn!(logger, "Error starting up lsp client: {e}");
None
}
})
.collect()
}
_ => Vec::new(),
};
let node_storage = storage.get_nodes()?;
// Remove the archived nodes, we don't need to start them up.
let unarchived_nodes = node_storage
.clone()
.nodes
.into_iter()
.filter(|(_, n)| !n.is_archived());
let mut nodes_map = HashMap::new();
for node_item in unarchived_nodes {
let node = Node::new(
node_item.0,
&node_item.1,
&mnemonic,
storage.clone(),
gossip_sync.clone(),
scorer.clone(),
chain.clone(),
fee_estimator.clone(),
wallet.clone(),
network,
esplora.clone(),
&lsp_clients,
logger.clone(),
c.do_not_connect_peers,
false,
#[cfg(target_arch = "wasm32")]
websocket_proxy_addr.clone(),
)
.await?;
let id = node
.keys_manager
.get_node_id(Recipient::Node)
.expect("Failed to get node id");
nodes_map.insert(id, Arc::new(node));
}
// when we create the nodes we set the LSP if one is missing
// we need to save it to local storage after startup in case
// a LSP was set.
let updated_nodes: HashMap<String, NodeIndex> = nodes_map
.values()
.map(|n| (n._uuid.clone(), n.node_index()))
.collect();
log_info!(logger, "inserting updated nodes");
storage.insert_nodes(NodeStorage {
nodes: updated_nodes,
})?;
log_info!(logger, "inserted updated nodes");
let nodes = Arc::new(Mutex::new(nodes_map));
let seed = mnemonic.to_seed("");
let xprivkey = ExtendedPrivKey::new_master(network, &seed)?;
let auth = AuthManager::new(xprivkey, storage.clone())?;
// Create default profile if it doesn't exist
auth.create_init()?;
let lnurl_client = Arc::new(
lnurl::Builder::default()
.build_async()
.expect("failed to make lnurl client"),
);
let auth_client = if let Some(auth_url) = c.auth_url {
let a = Arc::new(MutinyAuthClient::new(
auth.clone(),
lnurl_client.clone(),
logger.clone(),
auth_url,
));
Some(a)
} else {
None
};
let subscription_client = if let Some(auth_client) = auth_client {
if let Some(subscription_url) = c.subscription_url {
let s = Arc::new(MutinySubscriptionClient::new(
auth_client,
subscription_url,
logger.clone(),
));
Some(s)
} else {
None
}
} else {
None
};
let nm = NodeManager {
stop,
mnemonic,
network,
wallet,
gossip_sync,
scorer,
chain,
fee_estimator,
storage,
node_storage: Mutex::new(node_storage),
nodes,
#[cfg(target_arch = "wasm32")]
websocket_proxy_addr,
esplora,
auth,
lnurl_client,
lsp_clients,
subscription_client,
logger,
bitcoin_price_cache: Arc::new(Mutex::new(None)),
do_not_connect_peers: c.do_not_connect_peers,
};
Ok(nm)
}
/// Returns the node with the given pubkey
pub(crate) async fn get_node(&self, pk: &PublicKey) -> Result<Arc<Node<S>>, MutinyError> {
let nodes = self.nodes.lock().await;
let node = nodes.get(pk).ok_or(MutinyError::NotFound)?;
Ok(node.clone())
}
/// Stops all of the nodes and background processes.
/// Returns after node has been stopped.
pub async fn stop(&self) -> Result<(), MutinyError> {
self.stop.swap(true, Ordering::Relaxed);
let mut nodes = self.nodes.lock().await;
let node_futures = nodes.iter().map(|(_, n)| async {
match n.stop().await {
Ok(_) => {
log_debug!(self.logger, "stopped node: {}", n.pubkey.to_hex())
}
Err(e) => {
log_error!(
self.logger,
"failed to stop node {}: {e}",
n.pubkey.to_hex()
)
}
}
});
log_debug!(self.logger, "stopping all nodes");
join_all(node_futures).await;
nodes.clear();
log_debug!(self.logger, "stopped all nodes");
// stop the indexeddb object to close db connection
if self.storage.connected().unwrap_or(false) {
log_debug!(self.logger, "stopping storage");
self.storage.stop();
log_debug!(self.logger, "stopped storage");
}
Ok(())
}
/// Starts a background tasks to poll redshifts until they are ready and then start attempting payments.
///
/// This function will first find redshifts that are in the [RedshiftStatus::AttemptingPayments] state and start attempting payments
/// and redshifts that are in the [RedshiftStatus::ClosingChannels] state and finish closing channels.
/// This is done in case the node manager was shutdown while attempting payments or closing channels.
pub(crate) fn start_redshifts(nm: Arc<NodeManager<S>>) {
// find AttemptingPayments redshifts and restart attempting payments
// find ClosingChannels redshifts and restart closing channels
// use unwrap_or_default() to handle errors
let all = nm.storage.get_redshifts().unwrap_or_default();
for redshift in all {
match redshift.status {
RedshiftStatus::AttemptingPayments => {
// start attempting payments
let nm_clone = nm.clone();
utils::spawn(async move {
if let Err(e) = nm_clone.attempt_payments(redshift).await {
log_error!(nm_clone.logger, "Error attempting redshift payments: {e}");
}
});
}
RedshiftStatus::ClosingChannels => {
// finish closing channels
let nm_clone = nm.clone();
utils::spawn(async move {
if let Err(e) = nm_clone.close_channels(redshift).await {
log_error!(nm_clone.logger, "Error closing redshift channels: {e}");
}
});
}
_ => {} // ignore other statuses
}
}
utils::spawn(async move {
loop {
if nm.stop.load(Ordering::Relaxed) {
break;
}
// find redshifts with channels ready
// use unwrap_or_default() to handle errors
let all = nm.storage.get_redshifts().unwrap_or_default();
for mut redshift in all {
if redshift.status == RedshiftStatus::ChannelOpened {
// update status
redshift.status = RedshiftStatus::AttemptingPayments;
if let Err(e) = nm.storage.persist_redshift(redshift.clone()) {
log_error!(nm.logger, "Error persisting redshift status update: {e}");
}
// start attempting payments
let payment_nm = nm.clone();
utils::spawn(async move {
if let Err(e) = payment_nm.attempt_payments(redshift).await {
log_error!(
payment_nm.logger,
"Error attempting redshift payments: {e}"
);
}
});
}
}
// sleep 10 seconds
sleep(10_000).await;
}
});
}
/// Creates a background process that will sync the wallet with the blockchain.
/// This will also update the fee estimates every 10 minutes.
pub fn start_sync(nm: Arc<NodeManager<S>>) {
// If we are stopped, don't sync
if nm.stop.load(Ordering::Relaxed) {
return;
}
utils::spawn(async move {
let mut synced = false;
loop {
// If we are stopped, don't sync
if nm.stop.load(Ordering::Relaxed) {
return;
}
// we don't need to re-sync fees every time
// just do it every 10 minutes
if let Err(e) = nm.fee_estimator.update_fee_estimates_if_necessary().await {
log_error!(nm.logger, "Failed to update fee estimates: {e}");
} else {
log_info!(nm.logger, "Updated fee estimates!");
}
if let Err(e) = nm.sync().await {
log_error!(nm.logger, "Failed to sync: {e}");
} else if !synced {
// if this is the first sync, set the done_first_sync flag
let _ = nm.storage.set_done_first_sync();
synced = true;
}
// sleep for 1 minute, checking graceful shutdown check each 1s.
for _ in 0..60 {
if nm.stop.load(Ordering::Relaxed) {
return;
}
sleep(1_000).await;
}
}
});
}
/// Broadcast a transaction to the network.
/// The transaction is broadcast through the configured esplora server.
pub async fn broadcast_transaction(&self, tx: Transaction) -> Result<(), MutinyError> {
self.wallet.broadcast_transaction(tx).await
}
/// Returns the mnemonic seed phrase for the wallet.
pub fn show_seed(&self) -> Mnemonic {
self.mnemonic.clone()
}
/// Returns the network of the wallet.
pub fn get_network(&self) -> Network {
self.network
}
/// Gets a new bitcoin address from the wallet.
/// Will generate a new address on every call.
///
/// It is recommended to create a new address for every transaction.
pub fn get_new_address(&self, labels: Vec<String>) -> Result<Address, MutinyError> {
if let Ok(mut wallet) = self.wallet.wallet.try_write() {
let address = wallet.get_address(AddressIndex::New).address;
self.set_address_labels(address.clone(), labels)?;
return Ok(address);
}
log_error!(self.logger, "Could not get wallet lock to get new address");
Err(MutinyError::WalletOperationFailed)
}
/// Gets the current balance of the on-chain wallet.
pub fn get_wallet_balance(&self) -> Result<u64, MutinyError> {
if let Ok(wallet) = self.wallet.wallet.try_read() {
return Ok(wallet.get_balance().total());
}
log_error!(
self.logger,
"Could not get wallet lock to get wallet balance"
);
Err(MutinyError::WalletOperationFailed)
}
/// Creates a BIP 21 invoice. This creates a new address and a lightning invoice.
/// The lightning invoice may return errors related to the LSP. Check the error and
/// fallback to `get_new_address` and warn the user that Lightning is not available.
///
/// Errors that might be returned include:
///
/// - [`MutinyError::LspGenericError`]: This is returned for various reasons, including if a
/// request to the LSP server fails for any reason, or if the server returns
/// a status other than 500 that can't be parsed into a `ProposalResponse`.
///
/// - [`MutinyError::LspFundingError`]: Returned if the LSP server returns an error with
/// a status of 500, indicating an "Internal Server Error", and a message
/// stating "Cannot fund new channel at this time". This means that the LSP cannot support
/// a new channel at this time.
///
/// - [`MutinyError::LspConnectionError`]: Returned if the LSP server returns an error with
/// a status of 500, indicating an "Internal Server Error", and a message that starts with
/// "Failed to connect to peer". This means that the LSP is not connected to our node.
///
/// If the server returns a status of 500 with a different error message,
/// a [`MutinyError::LspGenericError`] is returned.
pub async fn create_bip21(
&self,
amount: Option<u64>,
labels: Vec<String>,
) -> Result<MutinyBip21RawMaterials, MutinyError> {
let invoice = self.create_invoice(amount, labels.clone()).await?;
let Ok(address) = self.get_new_address(labels.clone()) else {
return Err(MutinyError::WalletOperationFailed);
};
let Some(bolt11) = invoice.bolt11 else {
return Err(MutinyError::WalletOperationFailed);
};
Ok(MutinyBip21RawMaterials {
address,
invoice: bolt11,
btc_amount: amount.map(|amount| bitcoin::Amount::from_sat(amount).to_btc().to_string()),
labels,
})
}
/// Sends an on-chain transaction to the given address.
/// The amount is in satoshis and the fee rate is in sat/vbyte.
///
/// If a fee rate is not provided, one will be used from the fee estimator.
pub async fn send_to_address(
&self,
send_to: Address,
amount: u64,
labels: Vec<String>,
fee_rate: Option<f32>,
) -> Result<Txid, MutinyError> {
if !send_to.is_valid_for_network(self.network) {
return Err(MutinyError::IncorrectNetwork(send_to.network));
}
self.wallet.send(send_to, amount, labels, fee_rate).await
}
/// Sweeps all the funds from the wallet to the given address.
/// The fee rate is in sat/vbyte.
///