This repository was archived by the owner on Feb 3, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathfederation.rs
More file actions
2207 lines (1970 loc) · 80.8 KB
/
federation.rs
File metadata and controls
2207 lines (1970 loc) · 80.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::storage::get_invoice_by_hash;
use crate::utils::{
convert_from_fedimint_invoice, convert_to_fedimint_invoice, fetch_with_timeout, now, spawn,
};
use crate::TransactionDetails;
use crate::{
error::{MutinyError, MutinyStorageError},
event::PaymentInfo,
key::{create_root_child_key, ChildKey},
logging::MutinyLogger,
onchain::coin_type_from_network,
storage::{
delete_transaction_details, get_transaction_details, list_payment_info,
persist_payment_info, persist_transaction_details, MutinyStorage, VersionedValue,
},
utils::sleep,
HTLCStatus, MutinyInvoice, DEFAULT_PAYMENT_TIMEOUT,
};
use crate::{labels::LabelStorage, storage::TRANSACTION_DETAILS_PREFIX_KEY};
use async_lock::RwLock;
use async_trait::async_trait;
use bdk_chain::ConfirmationTime;
use bip39::Mnemonic;
use bitcoin::{
bip32::{ChildNumber, DerivationPath, ExtendedPrivKey},
hashes::Hash,
secp256k1::{Secp256k1, SecretKey, ThirtyTwoByteHash},
Address, Network, Txid,
};
use core::fmt;
use esplora_client::AsyncClient;
use fedimint_bip39::Bip39RootSecretStrategy;
use fedimint_client::{
derivable_secret::DerivableSecret,
oplog::{OperationLogEntry, UpdateStreamOrOutcome},
secret::{get_default_client_secret, RootSecretStrategy},
ClientHandleArc,
};
use fedimint_core::bitcoin_migration::bitcoin30_to_bitcoin29_address;
use fedimint_core::config::ClientConfig;
use fedimint_core::{
api::InviteCode,
config::FederationId,
core::OperationId,
module::CommonModuleInit,
task::{MaybeSend, MaybeSync},
Amount,
};
use fedimint_core::{
db::{
mem_impl::{MemDatabase, MemTransaction},
IDatabaseTransactionOps, IDatabaseTransactionOpsCore, IRawDatabase,
IRawDatabaseTransaction, PrefixStream,
},
BitcoinHash,
};
use fedimint_ln_client::{
InternalPayState, LightningClientInit, LightningClientModule, LightningOperationMeta,
LightningOperationMetaVariant, LnPayState, LnReceiveState,
};
use fedimint_ln_common::lightning_invoice::{Bolt11InvoiceDescription, Description, RoutingFees};
use fedimint_ln_common::{LightningCommonInit, LightningGateway, LightningGatewayAnnouncement};
use fedimint_mint_client::MintClientInit;
use fedimint_wallet_client::{
WalletClientInit, WalletClientModule, WalletCommonInit, WalletOperationMeta, WithdrawState,
};
use futures::{select, FutureExt};
use futures_util::{pin_mut, StreamExt};
use hex_conservative::{DisplayHex, FromHex};
use lightning::{log_debug, log_error, log_info, log_trace, log_warn, util::logger::Logger};
use lightning_invoice::Bolt11Invoice;
use reqwest::Method;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use std::time::Duration;
#[cfg(not(target_arch = "wasm32"))]
use std::time::Instant;
use std::{
collections::{HashMap, HashSet},
fmt::Debug,
sync::{atomic::AtomicBool, Arc},
};
use std::{
str::FromStr,
sync::atomic::{AtomicU32, Ordering},
};
#[cfg(target_arch = "wasm32")]
use web_time::Instant;
/// The maximum amount of operations we try to pull
/// from fedimint when we need to search through
/// their internal list.
const FEDIMINT_OPERATIONS_LIST_MAX: usize = 100;
/// On chain peg in timeout
const PEG_IN_TIMEOUT_YEAR: Duration = Duration::from_secs(86400 * 365);
/// For key value storage
pub const FEDIMINTS_PREFIX_KEY: &str = "fedimints/";
// Default signet/mainnet federation gateway info
// TODO: Remove these hardcoded gateways and use our improved gateway selection logic
const SIGNET_GATEWAY: &str = "0256f5ef1d986e9abf559651b7167de28bfd954683cd0f14703be12d1421aedc55";
const MAINNET_GATEWAY: &str = "025b9f090d3daab012346701f27d1c220d6d290f6b498255cddc492c255532a09d";
const SIGNET_FEDERATION: &str = "c8d423964c7ad944d30f57359b6e5b260e211dcfdb945140e28d4df51fd572d2";
const MAINNET_FEDERATION: &str = "c36038cce5a97e3467f03336fa8e7e3410960b81d1865cda2a609f70a8f51efb";
// Translate from Fedimint's internal status to our HTLCStatus
impl From<LnReceiveState> for HTLCStatus {
fn from(state: LnReceiveState) -> Self {
match state {
LnReceiveState::Created => HTLCStatus::Pending,
LnReceiveState::Claimed => HTLCStatus::Succeeded,
LnReceiveState::WaitingForPayment { .. } => HTLCStatus::Pending,
LnReceiveState::Canceled { .. } => HTLCStatus::Failed,
LnReceiveState::Funded => HTLCStatus::InFlight,
LnReceiveState::AwaitingFunds => HTLCStatus::InFlight,
}
}
}
impl From<InternalPayState> for HTLCStatus {
fn from(state: InternalPayState) -> Self {
match state {
InternalPayState::Funding => HTLCStatus::InFlight,
InternalPayState::Preimage(_) => HTLCStatus::Succeeded,
InternalPayState::RefundSuccess { .. } => HTLCStatus::Failed,
InternalPayState::RefundError { .. } => HTLCStatus::Failed,
InternalPayState::FundingFailed { .. } => HTLCStatus::Failed,
InternalPayState::UnexpectedError(_) => HTLCStatus::Failed,
}
}
}
impl From<LnPayState> for HTLCStatus {
fn from(state: LnPayState) -> Self {
match state {
LnPayState::Created => HTLCStatus::Pending,
LnPayState::Canceled => HTLCStatus::Failed,
LnPayState::Funded => HTLCStatus::InFlight,
LnPayState::WaitingForRefund { .. } => HTLCStatus::InFlight,
LnPayState::AwaitingChange => HTLCStatus::InFlight,
LnPayState::Success { .. } => HTLCStatus::Succeeded,
LnPayState::Refunded { .. } => HTLCStatus::Failed,
LnPayState::UnexpectedError { .. } => HTLCStatus::Failed,
}
}
}
/// FederationStorage object saved to the DB
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct FederationStorage {
pub federations: HashMap<String, FederationIndex>,
pub version: u32,
}
/// FederationIdentity that refers to a specific federation
/// Used for public facing identification. (What the frontend needs to display a federation to the user)
/// Constructed via FederationMetaConfig -> FederationMeta -> FederationIdentity
#[derive(Serialize, Deserialize, Clone, Eq, PartialEq)]
pub struct FederationIdentity {
pub uuid: String,
pub federation_id: FederationId,
pub invite_code: InviteCode,
/// https://github.com/fedimint/fedimint/tree/master/docs/meta_fields
pub federation_name: Option<String>,
pub federation_expiry_timestamp: Option<String>,
pub welcome_message: Option<String>,
/// undocumented parameters that fedi uses: https://meta.dev.fedibtc.com/meta.json
pub federation_icon_url: Option<String>,
pub meta_external_url: Option<String>,
pub preview_message: Option<String>,
pub popup_end_timestamp: Option<u32>,
pub popup_countdown_message: Option<String>,
}
/// Fedi's federation listing format
#[derive(Serialize, Deserialize, Debug)]
pub(crate) struct FederationMetaConfig {
#[serde(flatten)]
pub federations: std::collections::HashMap<String, FederationMeta>,
}
/// FederationUrlConfig that refer to a specific federation
/// Normal config information that might exist from their URL.
#[derive(Serialize, Deserialize, Clone, Eq, PartialEq, Debug)]
pub struct FederationMeta {
// https://github.com/fedimint/fedimint/tree/master/docs/meta_fields
pub federation_name: Option<String>,
pub federation_expiry_timestamp: Option<String>,
pub welcome_message: Option<String>,
pub gateway_fees: Option<GatewayFees>,
// undocumented parameters that fedi uses: https://meta.dev.fedibtc.com/meta.json
pub default_currency: Option<String>,
pub federation_icon_url: Option<String>,
pub max_balance_msats: Option<String>,
pub max_invoice_msats: Option<String>,
pub meta_external_url: Option<String>,
pub preview_message: Option<String>,
pub tos_url: Option<String>,
pub popup_end_timestamp: Option<String>,
pub popup_countdown_message: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone, Default)]
pub struct GatewayFees {
pub base_msat: u32,
pub proportional_millionths: u32,
}
impl From<RoutingFees> for GatewayFees {
fn from(val: RoutingFees) -> Self {
GatewayFees {
base_msat: val.base_msat,
proportional_millionths: val.proportional_millionths,
}
}
}
// This is the FederationIndex reference that is saved to the DB
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
pub struct FederationIndex {
pub federation_code: InviteCode,
}
pub struct FedimintBalance {
pub amount: u64,
}
// This is for the sake of test mocking
#[cfg_attr(test, mockall::automock)]
pub trait FedimintClient {
async fn claim_external_receive(
&self,
secret_key: &SecretKey,
tweaks: Vec<u64>,
) -> Result<(), MutinyError>;
}
/// FederationClient is Mutiny's main abstraction on top of the fedimint library
/// We use this object to pay invoices, get addresses, etc.
pub(crate) struct FederationClient<S: MutinyStorage> {
pub(crate) uuid: String,
pub(crate) fedimint_client: ClientHandleArc,
pub(crate) invite_code: InviteCode,
storage: S,
#[allow(dead_code)]
fedimint_storage: FedimintStorage<S>,
gateway: Arc<RwLock<Option<LightningGateway>>>,
esplora: Arc<AsyncClient>,
stop: Arc<AtomicBool>,
pub(crate) logger: Arc<MutinyLogger>,
}
impl<S: MutinyStorage> FederationClient<S> {
/// We call this when it's the first time we're joining a federation, and also
/// when we're starting up the wallet.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn new(
uuid: String,
federation_code: InviteCode,
xprivkey: ExtendedPrivKey,
storage: S,
esplora: Arc<AsyncClient>,
network: Network,
stop: Arc<AtomicBool>,
logger: Arc<MutinyLogger>,
) -> Result<Self, MutinyError> {
log_info!(logger, "initializing a new federation client: {uuid}");
let federation_id = federation_code.federation_id();
log_trace!(logger, "Building fedimint client db");
let fedimint_storage =
FedimintStorage::new(storage.clone(), federation_id.to_string(), logger.clone())
.await?;
let db = fedimint_storage.clone().into();
let is_initialized = fedimint_client::Client::is_initialized(&db).await;
let mut client_builder = fedimint_client::Client::builder(db);
client_builder.with_module(WalletClientInit(None));
client_builder.with_module(MintClientInit);
client_builder.with_module(LightningClientInit);
client_builder.with_primary_module(1);
log_trace!(logger, "Building fedimint client db");
let secret = create_federation_secret(xprivkey, network)?;
// Handle if we've joined the federation already
let fedimint_client = if is_initialized {
client_builder
.open(get_default_client_secret(&secret, &federation_id))
.await
.map_err(|e| {
log_error!(logger, "Could not open federation client: {e}");
MutinyError::FederationConnectionFailed
})?
} else {
let download = Instant::now();
let config = ClientConfig::download_from_invite_code(&federation_code)
.await
.map_err(|e| {
log_error!(logger, "Could not download federation info: {e}");
e
})?;
log_trace!(
logger,
"Downloaded federation info in: {}ms",
download.elapsed().as_millis()
);
client_builder
.join(get_default_client_secret(&secret, &federation_id), config)
.await
.map_err(|e| {
log_error!(logger, "Could not join federation: {e}");
MutinyError::FederationConnectionFailed
})?
};
// TODO: does this need to be an arc?
let fedimint_client = Arc::new(fedimint_client);
log_trace!(logger, "Retrieving fedimint wallet client module");
// check federation is on expected network
let wallet_client = fedimint_client.get_first_module::<WalletClientModule>();
// compare magic bytes because different versions of rust-bitcoin
if network.magic().to_bytes() != wallet_client.get_network().magic().to_le_bytes() {
log_error!(
logger,
"Fedimint on different network {}, expected: {network}",
wallet_client.get_network()
);
// try to delete the storage for this federation
if let Err(e) = fedimint_storage.delete_store().await {
log_error!(logger, "Could not delete fedimint storage: {e}");
}
return Err(MutinyError::NetworkMismatch);
}
let gateway = Arc::new(RwLock::new(None));
// Set active gateway preference in background
let client_clone = fedimint_client.clone();
let gateway_clone = gateway.clone();
let logger_clone = logger.clone();
// don't want to block wallet startup with these gateway updates
// so we spawn here
spawn(async move {
let start = Instant::now();
// get lock immediately to block other actions until gateway is set
let mut gateway_lock = gateway_clone.write().await;
let lightning_module = client_clone.get_first_module::<LightningClientModule>();
match lightning_module.update_gateway_cache(true).await {
Ok(_) => {
log_trace!(logger_clone, "Updated lightning gateway cache");
}
Err(e) => {
log_error!(
logger_clone,
"Could not update lightning gateway cache: {e}"
);
}
}
let gateways = lightning_module.list_gateways().await;
if let Some(a) = get_gateway_preference(gateways, federation_id) {
log_info!(
logger_clone,
"Setting active gateway for federation {federation_id}: {a}"
);
let gateway = lightning_module.select_gateway(&a).await;
*gateway_lock = gateway;
}
log_trace!(
logger_clone,
"Setting active gateway took: {}ms",
start.elapsed().as_millis()
);
});
log_debug!(logger, "Built fedimint client");
let federation_client = FederationClient {
uuid,
fedimint_client,
fedimint_storage,
storage,
logger,
invite_code: federation_code,
esplora,
stop,
gateway,
};
Ok(federation_client)
}
/// The fedimint database has its own representation of transactions, but we need to
/// track them in our own database. This checks for unprocessed transactions and
/// processes them.
pub(crate) async fn process_previous_operations(&self) -> Result<(), MutinyError> {
// look for our internal state pending transactions
let mut pending_invoices: HashSet<[u8; 32]> = HashSet::new();
pending_invoices.extend(
list_payment_info(&self.storage, true)?
.into_iter()
.filter(|(_h, i)| matches!(i.status, HTLCStatus::InFlight | HTLCStatus::Pending))
.map(|(h, _i)| h.0),
);
pending_invoices.extend(
list_payment_info(&self.storage, false)?
.into_iter()
.filter(|(_h, i)| matches!(i.status, HTLCStatus::InFlight | HTLCStatus::Pending))
.map(|(h, _i)| h.0),
);
// confirmed on chain operations
let confirmed_wallet_txids = self
.storage
.scan::<TransactionDetails>(TRANSACTION_DETAILS_PREFIX_KEY, None)?
.into_iter()
.filter(|(_k, v)| match v.confirmation_time {
ConfirmationTime::Unconfirmed { .. } => false, // skip unconfirmed transactions
ConfirmationTime::Confirmed { .. } => true, // return all confirmed transactions
})
.map(|(_h, i)| i.internal_id)
.collect::<HashSet<Txid>>();
// go through last 100 operations
let operations = self
.fedimint_client
.operation_log()
.list_operations(FEDIMINT_OPERATIONS_LIST_MAX, None)
.await;
// find all of the pending ones
for (key, entry) in operations {
let module_type = entry.operation_module_kind();
if module_type == LightningCommonInit::KIND.as_str() {
let lightning_meta: LightningOperationMeta = entry.meta();
match lightning_meta.variant {
LightningOperationMetaVariant::Pay(pay_meta) => {
let hash = pay_meta.invoice.payment_hash().into_inner();
if pending_invoices.contains(&hash) {
self.subscribe_operation(entry, key.operation_id);
}
}
LightningOperationMetaVariant::Receive { invoice, .. } => {
let hash = invoice.payment_hash().into_inner();
if pending_invoices.contains(&hash) {
self.subscribe_operation(entry, key.operation_id);
}
}
LightningOperationMetaVariant::Claim { .. } => {}
}
} else if module_type == WalletCommonInit::KIND.as_str() {
let internal_id = Txid::from_slice(&key.operation_id.0)
.map_err(|_| MutinyError::ChainAccessFailed)
.expect("should convert");
// if already confirmed, no reason to subscribe
if !confirmed_wallet_txids.contains(&internal_id) {
self.subscribe_operation(entry, key.operation_id);
}
} else {
log_warn!(self.logger, "Unknown module type: {module_type}")
}
}
Ok(())
}
/// Subscribe to status of actions like invoice creation, pay invoice, on-chain address creation, etc.
fn subscribe_operation(&self, entry: OperationLogEntry, operation_id: OperationId) {
subscribe_operation_ext(
entry,
operation_id,
self.fedimint_client.clone(),
self.esplora.clone(),
self.logger.clone(),
self.stop.clone(),
self.storage.clone(),
);
}
/// Get the current gateway fees
pub(crate) async fn gateway_fee(&self) -> Result<GatewayFees, MutinyError> {
let gateway = self.gateway.read().await;
Ok(gateway.as_ref().map(|x| x.fees.into()).unwrap_or_default())
}
/// Create a new lightning invoice
/// Important limitation: if the FedimintClient hasn't updated the lightning gateways yet, this will
/// create an invoice that can only be paid inside to the federation.
pub(crate) async fn get_invoice(
&self,
amount: u64,
labels: Vec<String>,
) -> Result<MutinyInvoice, MutinyError> {
log_trace!(self.logger, "calling federation.get_invoice");
let inbound = true;
let lightning_module = self
.fedimint_client
.get_first_module::<LightningClientModule>();
log_debug!(
self.logger,
"getting invoice from federation: {}",
self.fedimint_client.federation_id()
);
let desc = Description::new(String::new()).expect("empty string is valid");
let gateway = self.gateway.read().await;
let (id, invoice, preimage) = lightning_module
.create_bolt11_invoice(
Amount::from_sats(amount),
Bolt11InvoiceDescription::Direct(&desc),
None,
(),
gateway.clone(),
)
.await?;
let invoice = convert_from_fedimint_invoice(&invoice);
log_debug!(self.logger, "got invoice from federation: {invoice}");
// persist the invoice
let mut stored_payment: MutinyInvoice = invoice.clone().into();
stored_payment.inbound = inbound;
stored_payment.labels = labels;
stored_payment.preimage = Some(preimage.to_lower_hex_string());
log_trace!(self.logger, "Persisting payment");
let hash = stored_payment.payment_hash.into_32();
let payment_info = PaymentInfo::from(stored_payment);
persist_payment_info(&self.storage, &hash, &payment_info, inbound)?;
log_trace!(self.logger, "Persisted payment");
// subscribe to updates for it
let fedimint_client_clone = self.fedimint_client.clone();
let logger_clone = self.logger.clone();
let storage_clone = self.storage.clone();
let esplora_clone = self.esplora.clone();
let stop = self.stop.clone();
spawn(async move {
let operation = fedimint_client_clone
.operation_log()
.get_operation(id)
.await
.expect("just created it");
subscribe_operation_ext(
operation,
id,
fedimint_client_clone,
esplora_clone,
logger_clone,
stop,
storage_clone,
);
});
log_trace!(self.logger, "finished calling get_invoice");
Ok(invoice.into())
}
/// Get a new on-chain address
pub(crate) async fn get_new_address(
&self,
labels: Vec<String>,
) -> Result<Address, MutinyError> {
log_trace!(self.logger, "calling federation.get_new_address");
let wallet_module = self
.fedimint_client
.get_first_module::<WalletClientModule>();
log_debug!(
self.logger,
"getting new address from federation: {}",
self.fedimint_client.federation_id()
);
let (op_id, address) = wallet_module
.get_deposit_address(fedimint_core::time::now() + PEG_IN_TIMEOUT_YEAR, ())
.await?;
log_debug!(self.logger, "got new address from federation: {address}");
let address = Address::from_str(&address.to_string())
.expect("should convert")
.assume_checked();
// persist the labels
self.storage
.set_address_labels(address.clone(), labels.clone())?;
// subscribe
let operation = self
.fedimint_client
.operation_log()
.get_operation(op_id)
.await
.expect("just created it");
self.subscribe_operation(operation, op_id);
log_trace!(self.logger, "finished calling get_new_address");
Ok(address)
}
/// Get the balance of this federation client in sats
pub(crate) async fn get_balance(&self) -> Result<u64, MutinyError> {
Ok(self.fedimint_client.get_balance().await.msats / 1_000)
}
fn maybe_update_after_checking_fedimint(
&self,
updated_invoice: MutinyInvoice,
) -> Result<MutinyInvoice, MutinyError> {
maybe_update_after_checking_fedimint(
updated_invoice,
self.logger.clone(),
self.storage.clone(),
)
}
/// Pay a lightning invoice
/// Important limitation: same as get_invoice
pub(crate) async fn pay_invoice(
&self,
invoice: Bolt11Invoice,
labels: Vec<String>,
) -> Result<MutinyInvoice, MutinyError> {
let inbound = false;
let lightning_module = self
.fedimint_client
.get_first_module::<LightningClientModule>();
let fedimint_invoice = convert_to_fedimint_invoice(&invoice);
let gateway = self.gateway.read().await;
let outgoing_payment = lightning_module
.pay_bolt11_invoice(gateway.clone(), fedimint_invoice, ())
.await?;
// Save after payment was initiated successfully
let mut stored_payment: MutinyInvoice = invoice.clone().into();
stored_payment.inbound = inbound;
stored_payment.labels = labels;
stored_payment.status = HTLCStatus::InFlight;
let hash = stored_payment.payment_hash.into_32();
let payment_info = PaymentInfo::from(stored_payment.clone());
persist_payment_info(&self.storage, &hash, &payment_info, inbound)?;
// Subscribe and process outcome based on payment type
let (mut inv, id) = match outgoing_payment.payment_type {
fedimint_ln_client::PayType::Internal(pay_id) => {
match lightning_module.subscribe_internal_pay(pay_id).await {
Ok(o) => {
let o = process_ln_outcome(
o,
process_pay_state_internal,
stored_payment,
Some(DEFAULT_PAYMENT_TIMEOUT * 1_000),
self.stop.clone(),
Arc::clone(&self.logger),
)
.await;
(o, pay_id)
}
Err(_) => (invoice.clone().into(), pay_id),
}
}
fedimint_ln_client::PayType::Lightning(pay_id) => {
match lightning_module.subscribe_ln_pay(pay_id).await {
Ok(o) => {
let o = process_ln_outcome(
o,
process_pay_state_ln,
stored_payment,
Some(DEFAULT_PAYMENT_TIMEOUT * 1_000),
self.stop.clone(),
Arc::clone(&self.logger),
)
.await;
(o, pay_id)
}
Err(_) => (invoice.clone().into(), pay_id),
}
}
};
inv.fees_paid = Some(sats_round_up(&outgoing_payment.fee));
inv = self.maybe_update_after_checking_fedimint(inv)?;
match inv.status {
HTLCStatus::Succeeded => Ok(inv),
HTLCStatus::Failed => Err(MutinyError::RoutingFailed),
_ => {
// keep streaming after timeout happens
let fedimint_client_clone = self.fedimint_client.clone();
let logger_clone = self.logger.clone();
let storage_clone = self.storage.clone();
let esplora_clone = self.esplora.clone();
let stop = self.stop.clone();
spawn(async move {
let operation = fedimint_client_clone
.operation_log()
.get_operation(id)
.await
.expect("just created it");
subscribe_operation_ext(
operation,
id,
fedimint_client_clone,
esplora_clone,
logger_clone,
stop,
storage_clone,
);
});
Err(MutinyError::PaymentTimeout)
}
}
}
/// Send on chain transaction
pub(crate) async fn send_onchain(
&self,
send_to: bitcoin::Address,
amount: u64,
labels: Vec<String>,
) -> Result<Txid, MutinyError> {
let address = bitcoin30_to_bitcoin29_address(send_to.clone());
let btc_amount = fedimint_ln_common::bitcoin::Amount::from_sat(amount);
let wallet_module = self
.fedimint_client
.get_first_module::<WalletClientModule>();
let peg_out_fees = wallet_module
.get_withdraw_fees(address.clone(), btc_amount)
.await?;
let op_id = wallet_module
.withdraw(address, btc_amount, peg_out_fees, ())
.await?;
let internal_id = Txid::from_slice(&op_id.0).map_err(|_| MutinyError::ChainAccessFailed)?;
let pending_transaction_details = TransactionDetails {
transaction: None,
txid: None,
internal_id,
received: 0,
sent: amount,
fee: Some(peg_out_fees.amount().to_sat()),
confirmation_time: ConfirmationTime::Unconfirmed {
last_seen: now().as_secs(),
},
labels: labels.clone(),
};
persist_transaction_details(&self.storage, &pending_transaction_details)?;
// persist the labels
self.storage.set_address_labels(send_to, labels)?;
// subscribe
let operation = self
.fedimint_client
.operation_log()
.get_operation(op_id)
.await
.expect("just created it");
// Subscribe for a little bit, just to hopefully get transaction id
process_operation_until_timeout(
self.logger.clone(),
operation,
op_id,
self.fedimint_client.clone(),
self.storage.clone(),
self.esplora.clone(),
Some(DEFAULT_PAYMENT_TIMEOUT * 1_000),
self.stop.clone(),
)
.await;
// now check the status of the payment from storage
if let Some(t) = get_transaction_details(&self.storage, internal_id, &self.logger) {
if t.txid.is_some() {
return Ok(internal_id);
}
}
// keep subscribing if txid wasn't retrieved, but then return timeout
let operation = self
.fedimint_client
.operation_log()
.get_operation(op_id)
.await
.expect("just created it");
self.subscribe_operation(operation, op_id);
Err(MutinyError::PaymentTimeout)
}
/// Ask the federation for the on chain fee estimate
pub async fn estimate_tx_fee(
&self,
destination_address: bitcoin::Address,
amount: u64,
) -> Result<u64, MutinyError> {
let address = bitcoin30_to_bitcoin29_address(destination_address);
let btc_amount = fedimint_ln_common::bitcoin::Amount::from_sat(amount);
let wallet_module = self
.fedimint_client
.get_first_module::<WalletClientModule>();
let peg_out_fees = wallet_module
.get_withdraw_fees(address.clone(), btc_amount)
.await?;
Ok(peg_out_fees.amount().to_sat())
}
/// Someone received a payment on our behalf, we need to claim it
/// This is used for claiming Hermes lightning address payments
pub async fn claim_external_receive(
&self,
secret_key: &SecretKey,
tweaks: Vec<u64>,
) -> Result<(), MutinyError> {
let lightning_module = self
.fedimint_client
.get_first_module::<LightningClientModule>();
let key_pair = fedimint_ln_common::bitcoin::secp256k1::KeyPair::from_seckey_slice(
fedimint_ln_common::bitcoin::secp256k1::SECP256K1,
&secret_key.secret_bytes(),
)
.map_err(|_| MutinyError::InvalidArgumentsError)?;
let operation_ids = lightning_module
.scan_receive_for_user_tweaked(key_pair, tweaks, ())
.await;
if operation_ids.is_empty() {
log_warn!(
self.logger,
"External receive not found, maybe already claimed?"
);
return Err(MutinyError::NotFound);
}
for operation_id in operation_ids {
let mut updates = lightning_module
.subscribe_ln_claim(operation_id)
.await?
.into_stream();
while let Some(update) = updates.next().await {
match update {
LnReceiveState::Claimed => {
log_info!(self.logger, "External receive claimed!");
}
LnReceiveState::Canceled { reason } => {
log_error!(self.logger, "External receive canceled: {reason}");
return Err(MutinyError::InvalidArgumentsError); // todo better error
}
_ => {}
}
}
}
Ok(())
}
/// Get the federation info for displaying to the user
pub async fn get_mutiny_federation_identity(&self) -> FederationIdentity {
get_federation_identity(
self.uuid.clone(),
self.fedimint_client.clone(),
self.invite_code.clone(),
self.logger.clone(),
)
.await
}
/// WARNING delete_fedimint_storage is not suggested at the moment due to the lack of easy restores
#[allow(dead_code)]
pub async fn delete_fedimint_storage(&self) -> Result<(), MutinyError> {
self.fedimint_storage.delete_store().await
}
}
pub(crate) async fn get_federation_identity(
uuid: String,
fedimint_client: ClientHandleArc,
invite_code: InviteCode,
logger: Arc<MutinyLogger>,
) -> FederationIdentity {
let federation_id = fedimint_client.federation_id();
let meta_external_url = fedimint_client.get_meta("meta_external_url");
let config = if let Some(ref url) = meta_external_url {
log_info!(
logger,
"Getting config for {federation_id} from meta_external_url: {url}"
);
let http_client = reqwest::Client::new();
let request = http_client.request(Method::GET, url);
match fetch_with_timeout(&http_client, request.build().expect("should build req")).await {
Ok(r) => match r.json::<FederationMetaConfig>().await {
Ok(c) =>
{
#[allow(clippy::map_clone)]
c.federations
.get(&federation_id.to_string())
.map(|f| f.clone())
}
Err(e) => {
log_error!(logger, "Error parsing meta config: {e}");
None
}
},
Err(e) => {
log_error!(logger, "Error fetching meta config: {e}");
None
}
}
} else {
None
};
FederationIdentity {
uuid: uuid.clone(),
federation_id,
invite_code: invite_code.clone(),
federation_name: merge_values(
fedimint_client.get_meta("federation_name").clone(),
config.as_ref().and_then(|c| c.federation_name.clone()),
),
federation_expiry_timestamp: merge_values(
fedimint_client.get_meta("federation_expiry_timestamp"),
config
.as_ref()
.and_then(|c| c.federation_expiry_timestamp.clone()),
),
welcome_message: merge_values(
fedimint_client.get_meta("welcome_message"),
config.as_ref().and_then(|c| c.welcome_message.clone()),
),
federation_icon_url: merge_values(
fedimint_client.get_meta("federation_icon_url"),
config.as_ref().and_then(|c| c.federation_icon_url.clone()),
),
meta_external_url, // Already set...
preview_message: merge_values(
fedimint_client.get_meta("preview_message"),
config.as_ref().and_then(|c| c.preview_message.clone()),
),
popup_end_timestamp: merge_values(
fedimint_client
.get_meta("popup_end_timestamp")
.map(|v| v.parse().unwrap_or(0)),
config.as_ref().and_then(|c| {
c.popup_end_timestamp
.clone()
.map(|v| v.parse().unwrap_or(0))
}),
),
popup_countdown_message: merge_values(
fedimint_client
.get_meta("popup_countdown_message")
.map(|v| v.to_string()),
config
.as_ref()
.and_then(|c| c.popup_countdown_message.clone()),
),
}
}
fn merge_values<T>(a: Option<T>, b: Option<T>) -> Option<T> {
match (a, b) {