-
Notifications
You must be signed in to change notification settings - Fork 45
/
breez_services.rs
3451 lines (3130 loc) · 133 KB
/
breez_services.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 std::fs::OpenOptions;
use std::io::Write;
use std::str::FromStr;
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use anyhow::{anyhow, Result};
use bip39::*;
use bitcoin::hashes::hex::ToHex;
use bitcoin::hashes::{sha256, Hash};
use bitcoin::util::bip32::ChildNumber;
use chrono::Local;
use futures::TryFutureExt;
use gl_client::pb::incoming_payment;
use log::{LevelFilter, Metadata, Record};
use reqwest::{header::CONTENT_TYPE, Body};
use sdk_common::grpc;
use sdk_common::prelude::*;
use serde::Serialize;
use serde_json::{json, Value};
use strum_macros::EnumString;
use tokio::sync::{mpsc, watch, Mutex};
use tokio::time::{sleep, MissedTickBehavior};
use crate::backup::{BackupRequest, BackupTransport, BackupWatcher};
use crate::buy::{BuyBitcoinApi, BuyBitcoinService};
use crate::chain::{
ChainService, Outspend, RecommendedFees, RedundantChainService, RedundantChainServiceTrait,
DEFAULT_MEMPOOL_SPACE_URL,
};
use crate::error::{
ConnectError, ReceiveOnchainError, ReceiveOnchainResult, ReceivePaymentError,
RedeemOnchainResult, SdkError, SdkResult, SendOnchainError, SendPaymentError,
};
use crate::greenlight::{GLBackupTransport, Greenlight};
use crate::lnurl::auth::SdkLnurlAuthSigner;
use crate::lnurl::pay::*;
use crate::lsp::LspInformation;
use crate::models::{
sanitize::*, ChannelState, ClosedChannelPaymentDetails, Config, EnvironmentType, LspAPI,
NodeState, Payment, PaymentDetails, PaymentType, ReverseSwapPairInfo, ReverseSwapServiceAPI,
SwapInfo, SwapperAPI, INVOICE_PAYMENT_FEE_EXPIRY_SECONDS,
};
use crate::node_api::{CreateInvoiceRequest, NodeAPI};
use crate::persist::db::SqliteStorage;
use crate::swap_in::swap::BTCReceiveSwap;
use crate::swap_out::boltzswap::BoltzApi;
use crate::swap_out::reverseswap::BTCSendSwap;
use crate::*;
const DETECT_HIBERNATE_SLEEP_DURATION: Duration = Duration::from_secs(1);
const DETECT_HIBERNATE_MAX_OFFSET: Duration = Duration::from_secs(2);
pub type BreezServicesResult<T, E = ConnectError> = Result<T, E>;
/// Trait that can be used to react to various [BreezEvent]s emitted by the SDK.
pub trait EventListener: Send + Sync {
fn on_event(&self, e: BreezEvent);
}
/// Event emitted by the SDK. To listen for and react to these events, use an [EventListener] when
/// initializing the [BreezServices].
#[derive(Clone, Debug, PartialEq)]
#[allow(clippy::large_enum_variant)]
pub enum BreezEvent {
/// Indicates that a new block has just been found
NewBlock { block: u32 },
/// Indicates that a new invoice has just been paid
InvoicePaid { details: InvoicePaidDetails },
/// Indicates that the local SDK state has just been sync-ed with the remote components
Synced,
/// Indicates that an outgoing payment has been completed successfully
PaymentSucceed { details: Payment },
/// Indicates that an outgoing payment has been failed to complete
PaymentFailed { details: PaymentFailedData },
/// Indicates that the backup process has just started
BackupStarted,
/// Indicates that the backup process has just finished successfully
BackupSucceeded,
/// Indicates that the backup process has just failed
BackupFailed { details: BackupFailedData },
/// Indicates that a reverse swap has been updated which may also
/// include a status change
ReverseSwapUpdated { details: ReverseSwapInfo },
/// Indicates that a swap has been updated which may also
/// include a status change
SwapUpdated { details: SwapInfo },
}
#[derive(Clone, Debug, PartialEq)]
pub struct BackupFailedData {
pub error: String,
}
#[derive(Clone, Debug, PartialEq)]
pub struct PaymentFailedData {
pub error: String,
pub node_id: String,
pub invoice: Option<LNInvoice>,
pub label: Option<String>,
}
/// Details of an invoice that has been paid, included as payload in an emitted [BreezEvent]
#[derive(Clone, Debug, PartialEq)]
pub struct InvoicePaidDetails {
pub payment_hash: String,
pub bolt11: String,
pub payment: Option<Payment>,
}
pub trait LogStream: Send + Sync {
fn log(&self, l: LogEntry);
}
/// Request to sign a message with the node's private key.
#[derive(Clone, Debug, PartialEq)]
pub struct SignMessageRequest {
/// The message to be signed by the node's private key.
pub message: String,
}
/// Response to a [SignMessageRequest].
#[derive(Clone, Debug, PartialEq)]
pub struct SignMessageResponse {
/// The signature that covers the message of SignMessageRequest. Zbase
/// encoded.
pub signature: String,
}
/// Request to check a message was signed by a specific node id.
#[derive(Clone, Debug, PartialEq)]
pub struct CheckMessageRequest {
/// The message that was signed.
pub message: String,
/// The public key of the node that signed the message.
pub pubkey: String,
/// The zbase encoded signature to verify.
pub signature: String,
}
/// Response to a [CheckMessageRequest]
#[derive(Clone, Debug, PartialEq)]
pub struct CheckMessageResponse {
/// Boolean value indicating whether the signature covers the message and
/// was signed by the given pubkey.
pub is_valid: bool,
}
#[derive(Clone, PartialEq, EnumString, Serialize)]
enum DevCommand {
/// Generates diagnostic data report.
#[strum(serialize = "generatediagnosticdata")]
GenerateDiagnosticData,
}
/// BreezServices is a facade and the single entry point for the SDK.
pub struct BreezServices {
config: Config,
started: Mutex<bool>,
node_api: Arc<dyn NodeAPI>,
lsp_api: Arc<dyn LspAPI>,
fiat_api: Arc<dyn FiatAPI>,
buy_bitcoin_api: Arc<dyn BuyBitcoinApi>,
support_api: Arc<dyn SupportAPI>,
chain_service: Arc<dyn ChainService>,
persister: Arc<SqliteStorage>,
payment_receiver: Arc<PaymentReceiver>,
btc_receive_swapper: Arc<BTCReceiveSwap>,
btc_send_swapper: Arc<BTCSendSwap>,
event_listener: Option<Box<dyn EventListener>>,
backup_watcher: Arc<BackupWatcher>,
shutdown_sender: watch::Sender<()>,
shutdown_receiver: watch::Receiver<()>,
hibernation_sender: watch::Sender<()>,
hibernation_receiver: watch::Receiver<()>,
}
impl BreezServices {
/// `connect` initializes the SDK services, schedules the node to run in the cloud and
/// runs the signer. This must be called in order to start communicating with the node.
///
/// # Arguments
///
/// * `req` - The connect request containing the `config` SDK configuration and `seed` node
/// private key, typically derived from the mnemonic. When using a new `invite_code`,
/// the seed should be derived from a new random mnemonic. When re-using an `invite_code`,
/// the same mnemonic should be used as when the `invite_code` was first used.
/// * `event_listener` - Listener to SDK events
///
pub async fn connect(
req: ConnectRequest,
event_listener: Box<dyn EventListener>,
) -> BreezServicesResult<Arc<BreezServices>> {
let (sdk_version, sdk_git_hash) = Self::get_sdk_version();
info!("SDK v{sdk_version} ({sdk_git_hash})");
let start = Instant::now();
let services = BreezServicesBuilder::new(req.config)
.seed(req.seed)
.build(req.restore_only, Some(event_listener))
.await?;
services.start().await?;
let connect_duration = start.elapsed();
info!("SDK connected in: {connect_duration:?}");
Ok(services)
}
fn get_sdk_version() -> (&'static str, &'static str) {
let sdk_version = option_env!("CARGO_PKG_VERSION").unwrap_or_default();
let sdk_git_hash = option_env!("SDK_GIT_HASH").unwrap_or_default();
(sdk_version, sdk_git_hash)
}
/// Internal utility method that starts the BreezServices background tasks for this instance.
///
/// It should be called once right after creating [BreezServices], since it is essential for the
/// communicating with the node.
///
/// It should be called only once when the app is started, regardless whether the app is sent to
/// background and back.
async fn start(self: &Arc<BreezServices>) -> BreezServicesResult<()> {
let mut started = self.started.lock().await;
ensure_sdk!(
!*started,
ConnectError::Generic {
err: "BreezServices already started".into()
}
);
let start = Instant::now();
self.start_background_tasks().await?;
let start_duration = start.elapsed();
info!("SDK initialized in: {start_duration:?}");
*started = true;
Ok(())
}
/// Trigger the stopping of BreezServices background threads for this instance.
pub async fn disconnect(&self) -> SdkResult<()> {
let mut started = self.started.lock().await;
ensure_sdk!(
*started,
SdkError::Generic {
err: "BreezServices is not running".into(),
}
);
self.shutdown_sender
.send(())
.map_err(|e| SdkError::Generic {
err: format!("Shutdown failed: {e}"),
})?;
*started = false;
Ok(())
}
/// Configure the node
///
/// This calls [NodeAPI::configure_node] to make changes to the active node's configuration.
/// Configuring the [ConfigureNodeRequest::close_to_address] only needs to be done one time
/// when registering the node or when the close to address need to be changed. Otherwise it is
/// stored by the node and used when neccessary.
pub async fn configure_node(&self, req: ConfigureNodeRequest) -> SdkResult<()> {
Ok(self.node_api.configure_node(req.close_to_address).await?)
}
/// Pay a bolt11 invoice
///
/// Calling `send_payment` ensures that the payment is not already completed, if so it will result in an error.
/// If the invoice doesn't specify an amount, the amount is taken from the `amount_msat` arg.
pub async fn send_payment(
&self,
req: SendPaymentRequest,
) -> Result<SendPaymentResponse, SendPaymentError> {
let parsed_invoice = parse_invoice(req.bolt11.as_str())?;
let invoice_expiration = parsed_invoice.timestamp + parsed_invoice.expiry;
let current_time = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
if invoice_expiration < current_time {
return Err(SendPaymentError::InvoiceExpired {
err: format!("Invoice expired at {}", invoice_expiration),
});
}
let invoice_amount_msat = parsed_invoice.amount_msat.unwrap_or_default();
let provided_amount_msat = req.amount_msat.unwrap_or_default();
// Valid the invoice network against the config network
validate_network(parsed_invoice.clone(), self.config.network)?;
let amount_msat = match (provided_amount_msat, invoice_amount_msat) {
(0, 0) => {
return Err(SendPaymentError::InvalidAmount {
err: "Amount must be provided when paying a zero invoice".into(),
})
}
(0, amount_msat) => amount_msat,
(amount_msat, 0) => amount_msat,
(_amount_1, _amount_2) => {
return Err(SendPaymentError::InvalidAmount {
err: "Amount should not be provided when paying a non zero invoice".into(),
})
}
};
if self
.persister
.get_completed_payment_by_hash(&parsed_invoice.payment_hash)?
.is_some()
{
return Err(SendPaymentError::AlreadyPaid);
}
// If there is an lsp, the invoice route hint does not contain the
// lsp in the hint, and trampoline payments are requested, attempt a
// trampoline payment.
let maybe_trampoline_id = self.get_trampoline_id(&req, &parsed_invoice)?;
self.persist_pending_payment(&parsed_invoice, amount_msat, req.label.clone())?;
// If trampoline is an option, try trampoline first.
let trampoline_result = if let Some(trampoline_id) = maybe_trampoline_id {
debug!("attempting trampoline payment");
match self
.node_api
.send_trampoline_payment(
parsed_invoice.bolt11.clone(),
amount_msat,
req.label.clone(),
trampoline_id,
)
.await
{
Ok(res) => Some(res),
Err(e) => {
warn!("trampoline payment failed: {:?}", e);
None
}
}
} else {
debug!("not attempting trampoline payment");
None
};
// If trampoline failed or didn't happen, fall back to regular payment.
let payment_res = match trampoline_result {
Some(res) => Ok(res),
None => {
debug!("attempting normal payment");
self.node_api
.send_payment(
parsed_invoice.bolt11.clone(),
req.amount_msat,
req.label.clone(),
)
.map_err(Into::into)
.await
}
};
debug!("payment returned {:?}", payment_res);
let payment = self
.on_payment_completed(
parsed_invoice.payee_pubkey.clone(),
Some(parsed_invoice),
req.label,
payment_res,
)
.await?;
Ok(SendPaymentResponse { payment })
}
fn get_trampoline_id(
&self,
req: &SendPaymentRequest,
invoice: &LNInvoice,
) -> Result<Option<Vec<u8>>, SendPaymentError> {
// If trampoline is turned off, return immediately
if !req.use_trampoline {
return Ok(None);
}
// Get the persisted LSP id. If no LSP, return early.
let lsp_pubkey = match self.persister.get_lsp_pubkey()? {
Some(lsp_pubkey) => lsp_pubkey,
None => return Ok(None),
};
// If the LSP is in the routing hint, don't use trampoline, but rather
// pay directly to the destination.
if invoice.routing_hints.iter().any(|hint| {
hint.hops
.last()
.map(|hop| hop.src_node_id == lsp_pubkey)
.unwrap_or(false)
}) {
return Ok(None);
}
// If ended up here, this payment will attempt trampoline.
Ok(Some(hex::decode(lsp_pubkey).map_err(|_| {
SendPaymentError::Generic {
err: "failed to decode lsp pubkey".to_string(),
}
})?))
}
/// Pay directly to a node id using keysend
pub async fn send_spontaneous_payment(
&self,
req: SendSpontaneousPaymentRequest,
) -> Result<SendPaymentResponse, SendPaymentError> {
let payment_res = self
.node_api
.send_spontaneous_payment(
req.node_id.clone(),
req.amount_msat,
req.extra_tlvs,
req.label.clone(),
)
.map_err(Into::into)
.await;
let payment = self
.on_payment_completed(req.node_id, None, req.label, payment_res)
.await?;
Ok(SendPaymentResponse { payment })
}
/// Second step of LNURL-pay. The first step is `parse()`, which also validates the LNURL destination
/// and generates the `LnUrlPayRequest` payload needed here.
///
/// This call will validate the `amount_msat` and `comment` parameters of `req` against the parameters
/// of the LNURL endpoint (`req_data`). If they match the endpoint requirements, the LNURL payment
/// is made.
///
/// This method will return an [anyhow::Error] when any validation check fails.
pub async fn lnurl_pay(&self, req: LnUrlPayRequest) -> Result<LnUrlPayResult, LnUrlPayError> {
match validate_lnurl_pay(
req.amount_msat,
&req.comment,
&req.data,
self.config.network,
req.validate_success_action_url,
)
.await?
{
ValidatedCallbackResponse::EndpointError { data: e } => {
Ok(LnUrlPayResult::EndpointError { data: e })
}
ValidatedCallbackResponse::EndpointSuccess { data: cb } => {
let pay_req = SendPaymentRequest {
bolt11: cb.pr.clone(),
amount_msat: None,
use_trampoline: req.use_trampoline,
label: req.payment_label,
};
let invoice = parse_invoice(cb.pr.as_str())?;
let payment = match self.send_payment(pay_req).await {
Ok(p) => Ok(p),
e @ Err(
SendPaymentError::InvalidInvoice { .. }
| SendPaymentError::ServiceConnectivity { .. },
) => e,
Err(e) => {
return Ok(LnUrlPayResult::PayError {
data: LnUrlPayErrorData {
payment_hash: invoice.payment_hash,
reason: e.to_string(),
},
})
}
}?
.payment;
let details = match &payment.details {
PaymentDetails::ClosedChannel { .. } => {
return Err(LnUrlPayError::Generic {
err: "Payment lookup found unexpected payment type".into(),
});
}
PaymentDetails::Ln { data } => data,
};
let maybe_sa_processed: Option<SuccessActionProcessed> = match cb.success_action {
Some(sa) => {
let processed_sa = match sa {
// For AES, we decrypt the contents on the fly
SuccessAction::Aes { data } => {
let preimage = sha256::Hash::from_str(&details.payment_preimage)?;
let preimage_arr: [u8; 32] = preimage.into_inner();
let result = match (data, &preimage_arr).try_into() {
Ok(data) => AesSuccessActionDataResult::Decrypted { data },
Err(e) => AesSuccessActionDataResult::ErrorStatus {
reason: e.to_string(),
},
};
SuccessActionProcessed::Aes { result }
}
SuccessAction::Message { data } => {
SuccessActionProcessed::Message { data }
}
SuccessAction::Url { data } => SuccessActionProcessed::Url { data },
};
Some(processed_sa)
}
None => None,
};
let lnurl_pay_domain = match req.data.ln_address {
Some(_) => None,
None => Some(req.data.domain),
};
// Store SA (if available) + LN Address in separate table, associated to payment_hash
self.persister.insert_payment_external_info(
&details.payment_hash,
PaymentExternalInfo {
lnurl_pay_success_action: maybe_sa_processed.clone(),
lnurl_pay_domain,
lnurl_pay_comment: req.comment,
lnurl_metadata: Some(req.data.metadata_str),
ln_address: req.data.ln_address,
lnurl_withdraw_endpoint: None,
attempted_amount_msat: invoice.amount_msat,
attempted_error: None,
},
)?;
Ok(LnUrlPayResult::EndpointSuccess {
data: lnurl::pay::LnUrlPaySuccessData {
payment,
success_action: maybe_sa_processed,
},
})
}
}
}
/// Second step of LNURL-withdraw. The first step is `parse()`, which also validates the LNURL destination
/// and generates the `LnUrlWithdrawRequest` payload needed here.
///
/// This call will validate the given `amount_msat` against the parameters
/// of the LNURL endpoint (`data`). If they match the endpoint requirements, the LNURL withdraw
/// request is made. A successful result here means the endpoint started the payment.
pub async fn lnurl_withdraw(
&self,
req: LnUrlWithdrawRequest,
) -> Result<LnUrlWithdrawResult, LnUrlWithdrawError> {
let invoice = self
.receive_payment(ReceivePaymentRequest {
amount_msat: req.amount_msat,
description: req.description.unwrap_or_default(),
use_description_hash: Some(false),
..Default::default()
})
.await?
.ln_invoice;
let lnurl_w_endpoint = req.data.callback.clone();
let res = validate_lnurl_withdraw(req.data, invoice).await?;
if let LnUrlWithdrawResult::Ok { ref data } = res {
// If endpoint was successfully called, store the LNURL-withdraw endpoint URL as metadata linked to the invoice
self.persister.insert_payment_external_info(
&data.invoice.payment_hash,
PaymentExternalInfo {
lnurl_pay_success_action: None,
lnurl_pay_domain: None,
lnurl_pay_comment: None,
lnurl_metadata: None,
ln_address: None,
lnurl_withdraw_endpoint: Some(lnurl_w_endpoint),
attempted_amount_msat: None,
attempted_error: None,
},
)?;
}
Ok(res)
}
/// Third and last step of LNURL-auth. The first step is `parse()`, which also validates the LNURL destination
/// and generates the `LnUrlAuthRequestData` payload needed here. The second step is user approval of auth action.
///
/// This call will sign `k1` of the LNURL endpoint (`req_data`) on `secp256k1` using `linkingPrivKey` and DER-encodes the signature.
/// If they match the endpoint requirements, the LNURL auth request is made. A successful result here means the client signature is verified.
pub async fn lnurl_auth(
&self,
req_data: LnUrlAuthRequestData,
) -> Result<LnUrlCallbackStatus, LnUrlAuthError> {
Ok(perform_lnurl_auth(&req_data, &SdkLnurlAuthSigner::new(self.node_api.clone())).await?)
}
/// Creates an bolt11 payment request.
/// This also works when the node doesn't have any channels and need inbound liquidity.
/// In such case when the invoice is paid a new zero-conf channel will be open by the LSP,
/// providing inbound liquidity and the payment will be routed via this new channel.
pub async fn receive_payment(
&self,
req: ReceivePaymentRequest,
) -> Result<ReceivePaymentResponse, ReceivePaymentError> {
self.payment_receiver.receive_payment(req).await
}
/// Report an issue.
///
/// Calling `report_issue` with a [ReportIssueRequest] enum param sends an issue report using the Support API.
/// - [ReportIssueRequest::PaymentFailure] sends a payment failure report to the Support API
/// using the provided `payment_hash` to lookup the failed payment and the current [NodeState].
pub async fn report_issue(&self, req: ReportIssueRequest) -> SdkResult<()> {
match self.persister.get_node_state()? {
Some(node_state) => match req {
ReportIssueRequest::PaymentFailure { data } => {
let payment = self
.persister
.get_payment_by_hash(&data.payment_hash)?
.ok_or(SdkError::Generic {
err: "Payment not found".into(),
})?;
let lsp_id = self.persister.get_lsp_id()?;
self.support_api
.report_payment_failure(node_state, payment, lsp_id, data.comment)
.await
}
},
None => Err(SdkError::Generic {
err: "Node state not found".into(),
}),
}
}
/// Retrieve the decrypted credentials from the node.
pub async fn node_credentials(&self) -> SdkResult<Option<NodeCredentials>> {
Ok(self.node_api.node_credentials().await?)
}
/// Retrieve the node state from the persistent storage.
///
/// Fail if it could not be retrieved or if `None` was found.
pub fn node_info(&self) -> SdkResult<NodeState> {
self.persister.get_node_state()?.ok_or(SdkError::Generic {
err: "Node info not found".into(),
})
}
/// Sign given message with the private key of the node id. Returns a zbase
/// encoded signature.
pub async fn sign_message(&self, req: SignMessageRequest) -> SdkResult<SignMessageResponse> {
let signature = self.node_api.sign_message(&req.message).await?;
Ok(SignMessageResponse { signature })
}
/// Check whether given message was signed by the private key or the given
/// pubkey and the signature (zbase encoded) is valid.
pub async fn check_message(&self, req: CheckMessageRequest) -> SdkResult<CheckMessageResponse> {
let is_valid = self
.node_api
.check_message(&req.message, &req.pubkey, &req.signature)
.await?;
Ok(CheckMessageResponse { is_valid })
}
/// Retrieve the node up to date BackupStatus
pub fn backup_status(&self) -> SdkResult<BackupStatus> {
let backup_time = self.persister.get_last_backup_time()?;
let sync_request = self.persister.get_last_sync_request()?;
Ok(BackupStatus {
last_backup_time: backup_time,
backed_up: sync_request.is_none(),
})
}
/// Force running backup
pub async fn backup(&self) -> SdkResult<()> {
let (on_complete, mut on_complete_receiver) = mpsc::channel::<Result<()>>(1);
let req = BackupRequest::with(on_complete, true);
self.backup_watcher.request_backup(req).await?;
match on_complete_receiver.recv().await {
Some(res) => res.map_err(|e| SdkError::Generic {
err: format!("Backup failed: {e}"),
}),
None => Err(SdkError::Generic {
err: "Backup process failed to complete".into(),
}),
}
}
/// List payments matching the given filters, as retrieved from persistent storage
pub async fn list_payments(&self, req: ListPaymentsRequest) -> SdkResult<Vec<Payment>> {
Ok(self.persister.list_payments(req)?)
}
/// Fetch a specific payment by its hash.
pub async fn payment_by_hash(&self, hash: String) -> SdkResult<Option<Payment>> {
Ok(self.persister.get_payment_by_hash(&hash)?)
}
/// Set the external metadata of a payment as a valid JSON string
pub async fn set_payment_metadata(&self, hash: String, metadata: String) -> SdkResult<()> {
Ok(self
.persister
.set_payment_external_metadata(hash, metadata)?)
}
/// Redeem on-chain funds from closed channels to the specified on-chain address, with the given feerate
pub async fn redeem_onchain_funds(
&self,
req: RedeemOnchainFundsRequest,
) -> RedeemOnchainResult<RedeemOnchainFundsResponse> {
let txid = self
.node_api
.redeem_onchain_funds(req.to_address, req.sat_per_vbyte)
.await?;
self.sync().await?;
Ok(RedeemOnchainFundsResponse { txid })
}
pub async fn prepare_redeem_onchain_funds(
&self,
req: PrepareRedeemOnchainFundsRequest,
) -> RedeemOnchainResult<PrepareRedeemOnchainFundsResponse> {
let response = self.node_api.prepare_redeem_onchain_funds(req).await?;
Ok(response)
}
/// Fetch live rates of fiat currencies, sorted by name
pub async fn fetch_fiat_rates(&self) -> SdkResult<Vec<Rate>> {
self.fiat_api.fetch_fiat_rates().await.map_err(Into::into)
}
/// List all supported fiat currencies for which there is a known exchange rate.
/// List is sorted by the canonical name of the currency
pub async fn list_fiat_currencies(&self) -> SdkResult<Vec<FiatCurrency>> {
self.fiat_api
.list_fiat_currencies()
.await
.map_err(Into::into)
}
/// List available LSPs that can be selected by the user
pub async fn list_lsps(&self) -> SdkResult<Vec<LspInformation>> {
self.lsp_api.list_lsps(self.node_info()?.id).await
}
/// Select the LSP to be used and provide inbound liquidity
pub async fn connect_lsp(&self, lsp_id: String) -> SdkResult<()> {
let lsp_pubkey = match self.list_lsps().await?.iter().find(|lsp| lsp.id == lsp_id) {
Some(lsp) => lsp.pubkey.clone(),
None => {
return Err(SdkError::Generic {
err: format!("Unknown LSP: {lsp_id}"),
})
}
};
self.persister.set_lsp(lsp_id, Some(lsp_pubkey))?;
self.sync().await?;
if let Some(webhook_url) = self.persister.get_webhook_url()? {
self.register_payment_notifications(webhook_url).await?
}
Ok(())
}
/// Get the current LSP's ID
pub async fn lsp_id(&self) -> SdkResult<Option<String>> {
Ok(self.persister.get_lsp_id()?)
}
/// Convenience method to look up [LspInformation] for a given LSP ID
pub async fn fetch_lsp_info(&self, id: String) -> SdkResult<Option<LspInformation>> {
get_lsp_by_id(self.persister.clone(), self.lsp_api.clone(), id.as_str()).await
}
/// Gets the fees required to open a channel for a given amount.
/// If no channel is needed, returns 0. If a channel is needed, returns the required opening fees.
pub async fn open_channel_fee(
&self,
req: OpenChannelFeeRequest,
) -> SdkResult<OpenChannelFeeResponse> {
let lsp_info = self.lsp_info().await?;
let fee_params = lsp_info
.cheapest_open_channel_fee(req.expiry.unwrap_or(INVOICE_PAYMENT_FEE_EXPIRY_SECONDS))?
.clone();
let node_state = self.node_info()?;
let fee_msat = req.amount_msat.map(|req_amount_msat| {
match node_state.max_receivable_single_payment_amount_msat >= req_amount_msat {
// In case we have enough inbound liquidity we return zero fee.
true => 0,
// Otherwise we need to calculate the fee for opening a new channel.
false => fee_params.get_channel_fees_msat_for(req_amount_msat),
}
});
Ok(OpenChannelFeeResponse {
fee_msat,
fee_params,
})
}
/// Close all channels with the current LSP.
///
/// Should be called when the user wants to close all the channels.
pub async fn close_lsp_channels(&self) -> SdkResult<Vec<String>> {
let lsp = self.lsp_info().await?;
let tx_ids = self.node_api.close_peer_channels(lsp.pubkey).await?;
self.sync().await?;
Ok(tx_ids)
}
/// Onchain receive swap API
///
/// Create and start a new swap. A user-selected [OpeningFeeParams] can be optionally set in the argument.
/// If set, and the operation requires a new channel, the SDK will use the given fee params.
/// The provided [OpeningFeeParams] need to be valid at the time of swap redeeming.
///
/// Since we only allow one in-progress swap this method will return error if there is currently
/// a swap waiting for confirmation to be redeemed and by that complete the swap.
/// In such case the [BreezServices::in_progress_swap] can be used to query the live swap status.
///
/// The returned [SwapInfo] contains the created swap details. The channel opening fees are
/// available at [SwapInfo::channel_opening_fees].
pub async fn receive_onchain(
&self,
req: ReceiveOnchainRequest,
) -> ReceiveOnchainResult<SwapInfo> {
if let Some(in_progress) = self.in_progress_swap().await? {
return Err(ReceiveOnchainError::SwapInProgress{ err:format!(
"A swap was detected for address {}. Use in_progress_swap method to get the current swap state",
in_progress.bitcoin_address
)});
}
let channel_opening_fees = req.opening_fee_params.unwrap_or(
self.lsp_info()
.await?
.cheapest_open_channel_fee(SWAP_PAYMENT_FEE_EXPIRY_SECONDS)?
.clone(),
);
let swap_info = self
.btc_receive_swapper
.create_swap_address(channel_opening_fees)
.await?;
if let Some(webhook_url) = self.persister.get_webhook_url()? {
let address = &swap_info.bitcoin_address;
info!("Registering for onchain tx notification for address {address}");
self.register_onchain_tx_notification(address, &webhook_url)
.await?;
}
Ok(swap_info)
}
/// Returns an optional in-progress [SwapInfo].
/// A [SwapInfo] is in-progress if it is waiting for confirmation to be redeemed and complete the swap.
pub async fn in_progress_swap(&self) -> SdkResult<Option<SwapInfo>> {
let tip = self.chain_service.current_tip().await?;
self.btc_receive_swapper.rescan_monitored_swaps(tip).await?;
let in_progress = self.btc_receive_swapper.list_in_progress()?;
if !in_progress.is_empty() {
return Ok(Some(in_progress[0].clone()));
}
Ok(None)
}
/// Iterate all historical swap addresses and fetch their current status from the blockchain.
/// The status is then updated in the persistent storage.
pub async fn rescan_swaps(&self) -> SdkResult<()> {
let tip = self.chain_service.current_tip().await?;
self.btc_receive_swapper.rescan_swaps(tip).await?;
Ok(())
}
/// Redeems an individual swap.
///
/// To be used only in the context of mobile notifications, where the notification triggers
/// an individual redeem.
///
/// This is taken care of automatically in the context of typical SDK usage.
pub async fn redeem_swap(&self, swap_address: String) -> SdkResult<()> {
let tip = self.chain_service.current_tip().await?;
self.btc_receive_swapper
.refresh_swap_on_chain_status(swap_address.clone(), tip)
.await?;
self.btc_receive_swapper.redeem_swap(swap_address).await?;
Ok(())
}
/// Lists current and historical swaps.
///
/// Swaps can be filtered based on creation time and status.
pub async fn list_swaps(&self, req: ListSwapsRequest) -> SdkResult<Vec<SwapInfo>> {
Ok(self.persister.list_swaps(req)?)
}
/// Claims an individual reverse swap.
///
/// To be used only in the context of mobile notifications, where the notification triggers
/// an individual reverse swap to be claimed.
///
/// This is taken care of automatically in the context of typical SDK usage.
pub async fn claim_reverse_swap(&self, lockup_address: String) -> SdkResult<()> {
Ok(self
.btc_send_swapper
.claim_reverse_swap(lockup_address)
.await?)
}
/// Lookup the reverse swap fees (see [ReverseSwapServiceAPI::fetch_reverse_swap_fees]).
///
/// If the request has the `send_amount_sat` set, the returned [ReverseSwapPairInfo] will have
/// the total estimated fees for the reverse swap in its `total_estimated_fees`.
///
/// If, in addition to that, the request has the `claim_tx_feerate` set as well, then
/// - `fees_claim` will have the actual claim transaction fees, instead of an estimate, and
/// - `total_estimated_fees` will have the actual total fees for the given parameters
///
/// ### Errors
///
/// If a `send_amount_sat` is specified in the `req`, but is outside the `min` and `max`,
/// this will result in an error. If you are not sure what are the `min` and `max`, please call
/// this with `send_amount_sat` as `None` first, then repeat the call with the desired amount.
pub async fn fetch_reverse_swap_fees(
&self,
req: ReverseSwapFeesRequest,
) -> SdkResult<ReverseSwapPairInfo> {
let mut res = self.btc_send_swapper.fetch_reverse_swap_fees().await?;
if let Some(amt) = req.send_amount_sat {
ensure_sdk!(amt <= res.max, SdkError::generic("Send amount is too high"));
ensure_sdk!(amt >= res.min, SdkError::generic("Send amount is too low"));
if let Some(claim_tx_feerate) = req.claim_tx_feerate {
res.fees_claim = BTCSendSwap::calculate_claim_tx_fee(claim_tx_feerate)?;
}
let service_fee_sat = swap_out::get_service_fee_sat(amt, res.fees_percentage);
res.total_fees = Some(service_fee_sat + res.fees_lockup + res.fees_claim);
}
Ok(res)
}
/// Returns the max amount that can be sent on-chain using the send_onchain method.
/// The returned amount is the sum of the max amount that can be sent on each channel
/// minus the expected fees.
/// This is possible since the route to the swapper node is known in advance and is expected
/// to consist of maximum 3 hops.
async fn max_reverse_swap_amount(&self) -> SdkResult<u64> {
// fetch the last hop hints from the swapper
let last_hop = self.btc_send_swapper.last_hop_for_payment().await?;
info!("max_reverse_swap_amount last_hop={:?}", last_hop);
// calculate the largest payment we can send over this route using maximum 3 hops
// as follows:
// User Node -> LSP Node -> Routing Node -> Swapper Node
let max_to_pay = self
.node_api
.max_sendable_amount(
Some(
hex::decode(&last_hop.src_node_id).map_err(|e| SdkError::Generic {
err: format!("Failed to decode hex node_id: {e}"),
})?,
),
swap_out::reverseswap::MAX_PAYMENT_PATH_HOPS,
Some(&last_hop),
)
.await?;
// Sum the max amount per channel and return the result
let total_msat: u64 = max_to_pay.into_iter().map(|m| m.amount_msat).sum();
let total_sat = total_msat / 1000;
Ok(total_sat)
}
/// list non-completed expired swaps that should be refunded by calling [BreezServices::refund]
pub async fn list_refundables(&self) -> SdkResult<Vec<SwapInfo>> {
Ok(self.btc_receive_swapper.list_refundables()?)
}
/// Prepares a refund transaction for a failed/expired swap.
///
/// Can optionally be used before [BreezServices::refund] to know how much fees will be paid
/// to perform the refund.
pub async fn prepare_refund(
&self,
req: PrepareRefundRequest,
) -> SdkResult<PrepareRefundResponse> {
Ok(self.btc_receive_swapper.prepare_refund_swap(req).await?)
}
/// Construct and broadcast a refund transaction for a failed/expired swap
///
/// Returns the txid of the refund transaction.
pub async fn refund(&self, req: RefundRequest) -> SdkResult<RefundResponse> {
Ok(self.btc_receive_swapper.refund_swap(req).await?)
}
pub async fn onchain_payment_limits(&self) -> SdkResult<OnchainPaymentLimitsResponse> {
let fee_info = self.btc_send_swapper.fetch_reverse_swap_fees().await?;
debug!("Reverse swap pair info: {fee_info:?}");
let max_amt_current_channels = self.max_reverse_swap_amount().await?;
debug!("Max send amount possible with current channels: {max_amt_current_channels:?}");
Ok(OnchainPaymentLimitsResponse {
min_sat: fee_info.min,
max_sat: fee_info.max,