1pub mod ldk;
2pub mod lnd;
3pub mod metrics;
4
5use std::fmt::Debug;
6use std::str::FromStr;
7use std::sync::Arc;
8
9use async_trait::async_trait;
10use bitcoin::Network;
11use bitcoin::hashes::sha256;
12use fedimint_core::Amount;
13use fedimint_core::encoding::{Decodable, Encodable};
14use fedimint_core::envs::{FM_IN_DEVIMINT_ENV, is_env_var_set};
15use fedimint_core::secp256k1::PublicKey;
16use fedimint_core::task::TaskGroup;
17use fedimint_core::time::now;
18use fedimint_core::util::{FmtCompact as _, FmtCompactResult as _, backoff_util, retry};
19use fedimint_gateway_common::{
20 ChannelInfo, CloseChannelsWithPeerRequest, CloseChannelsWithPeerResponse, ConnectPeerRequest,
21 GetInvoiceRequest, GetInvoiceResponse, LightningInfo, ListTransactionsResponse,
22 OpenChannelRequest, SendOnchainRequest, SetChannelFeesRequest,
23};
24use fedimint_ln_common::PrunedInvoice;
25pub use fedimint_ln_common::contracts::Preimage;
26use fedimint_ln_common::route_hints::RouteHint;
27use fedimint_logging::LOG_LIGHTNING;
28use fedimint_metrics::HistogramExt as _;
29use futures::future::BoxFuture;
30use futures::stream::BoxStream;
31use lightning_invoice::Bolt11Invoice;
32use serde::{Deserialize, Serialize};
33use thiserror::Error;
34use tracing::{info, trace, warn};
35
36pub const MAX_LIGHTNING_RETRIES: u32 = 10;
37
38pub type RouteHtlcStream<'a> = BoxStream<'a, InterceptPaymentRequest>;
39
40pub type Lnv2HoldInvoiceFilter =
46 Arc<dyn Fn(sha256::Hash) -> BoxFuture<'static, bool> + Send + Sync + 'static>;
47
48#[derive(
49 Error, Debug, Serialize, Deserialize, Encodable, Decodable, Clone, Eq, PartialEq, Hash,
50)]
51pub enum LightningRpcError {
52 #[error("Failed to connect to Lightning node")]
53 FailedToConnect,
54 #[error("Failed to retrieve node info: {failure_reason}")]
55 FailedToGetNodeInfo { failure_reason: String },
56 #[error("Failed to retrieve route hints: {failure_reason}")]
57 FailedToGetRouteHints { failure_reason: String },
58 #[error("Payment failed: {failure_reason}")]
59 FailedPayment { failure_reason: String },
60 #[error("Failed to route HTLCs: {failure_reason}")]
61 FailedToRouteHtlcs { failure_reason: String },
62 #[error("Failed to complete HTLC: {failure_reason}")]
63 FailedToCompleteHtlc { failure_reason: String },
64 #[error("Failed to open channel: {failure_reason}")]
65 FailedToOpenChannel { failure_reason: String },
66 #[error("Failed to close channel: {failure_reason}")]
67 FailedToCloseChannelsWithPeer { failure_reason: String },
68 #[error("Failed to set channel fees: {failure_reason}")]
69 FailedToSetChannelFees { failure_reason: String },
70 #[error("Failed to get Invoice: {failure_reason}")]
71 FailedToGetInvoice { failure_reason: String },
72 #[error("Failed to list transactions: {failure_reason}")]
73 FailedToListTransactions { failure_reason: String },
74 #[error("Failed to get funding address: {failure_reason}")]
75 FailedToGetLnOnchainAddress { failure_reason: String },
76 #[error("Failed to withdraw funds on-chain: {failure_reason}")]
77 FailedToWithdrawOnchain { failure_reason: String },
78 #[error("Failed to connect to peer: {failure_reason}")]
79 FailedToConnectToPeer { failure_reason: String },
80 #[error("Failed to list active channels: {failure_reason}")]
81 FailedToListChannels { failure_reason: String },
82 #[error("Failed to get balances: {failure_reason}")]
83 FailedToGetBalances { failure_reason: String },
84 #[error("Failed to sync to chain: {failure_reason}")]
85 FailedToSyncToChain { failure_reason: String },
86 #[error("Invalid metadata: {failure_reason}")]
87 InvalidMetadata { failure_reason: String },
88 #[error("Bolt12 Error: {failure_reason}")]
89 Bolt12Error { failure_reason: String },
90 #[error("HTLC completion cannot reach the requested outcome: {failure_reason}")]
93 HtlcCompletionRejected { failure_reason: String },
94}
95
96#[derive(Clone, Debug)]
98pub struct LightningContext {
99 pub lnrpc: Arc<dyn ILnRpcClient>,
100 pub lightning_public_key: PublicKey,
101 pub lightning_alias: String,
102 pub lightning_network: Network,
103}
104
105#[async_trait]
109pub trait ILnRpcClient: Debug + Send + Sync {
110 async fn info(&self) -> Result<GetNodeInfoResponse, LightningRpcError>;
112
113 async fn routehints(
118 &self,
119 num_route_hints: usize,
120 ) -> Result<GetRouteHintsResponse, LightningRpcError>;
121
122 async fn pay(
144 &self,
145 invoice: Bolt11Invoice,
146 max_delay: u64,
147 max_fee: Amount,
148 ) -> Result<PayInvoiceResponse, LightningRpcError> {
149 self.pay_private(
150 PrunedInvoice::try_from(invoice).map_err(|_| LightningRpcError::FailedPayment {
151 failure_reason: "Invoice has no amount".to_string(),
152 })?,
153 max_delay,
154 max_fee,
155 )
156 .await
157 }
158
159 async fn pay_private(
166 &self,
167 _invoice: PrunedInvoice,
168 _max_delay: u64,
169 _max_fee: Amount,
170 ) -> Result<PayInvoiceResponse, LightningRpcError> {
171 Err(LightningRpcError::FailedPayment {
172 failure_reason: "Private payments not supported".to_string(),
173 })
174 }
175
176 fn supports_private_payments(&self) -> bool {
180 false
181 }
182
183 async fn outbound_payment_exists(
194 &self,
195 payment_hash: sha256::Hash,
196 ) -> Result<bool, LightningRpcError>;
197
198 async fn route_htlcs<'a>(
209 self: Box<Self>,
210 task_group: &TaskGroup,
211 ) -> Result<(RouteHtlcStream<'a>, Arc<dyn ILnRpcClient>), LightningRpcError>;
212
213 async fn complete_htlc(&self, htlc: InterceptPaymentResponse) -> Result<(), LightningRpcError>;
223
224 async fn create_invoice(
229 &self,
230 create_invoice_request: CreateInvoiceRequest,
231 ) -> Result<CreateInvoiceResponse, LightningRpcError>;
232
233 async fn get_ln_onchain_address(
236 &self,
237 ) -> Result<GetLnOnchainAddressResponse, LightningRpcError>;
238
239 async fn send_onchain(
242 &self,
243 payload: SendOnchainRequest,
244 ) -> Result<SendOnchainResponse, LightningRpcError>;
245
246 async fn open_channel(
248 &self,
249 payload: OpenChannelRequest,
250 ) -> Result<OpenChannelResponse, LightningRpcError>;
251
252 async fn connect_peer(&self, payload: ConnectPeerRequest) -> Result<(), LightningRpcError>;
254
255 async fn close_channels_with_peer(
257 &self,
258 payload: CloseChannelsWithPeerRequest,
259 ) -> Result<CloseChannelsWithPeerResponse, LightningRpcError>;
260
261 async fn list_channels(&self) -> Result<ListChannelsResponse, LightningRpcError>;
263
264 async fn set_channel_fees(
268 &self,
269 payload: SetChannelFeesRequest,
270 ) -> Result<(), LightningRpcError>;
271
272 async fn get_balances(&self) -> Result<GetBalancesResponse, LightningRpcError>;
275
276 async fn get_invoice(
277 &self,
278 get_invoice_request: GetInvoiceRequest,
279 ) -> Result<Option<GetInvoiceResponse>, LightningRpcError>;
280
281 async fn list_transactions(
282 &self,
283 start_secs: u64,
284 end_secs: u64,
285 ) -> Result<ListTransactionsResponse, LightningRpcError>;
286
287 fn create_offer(
288 &self,
289 amount: Option<Amount>,
290 description: Option<String>,
291 expiry_secs: Option<u32>,
292 quantity: Option<u64>,
293 ) -> Result<String, LightningRpcError>;
294
295 async fn pay_offer(
296 &self,
297 offer: String,
298 quantity: Option<u64>,
299 amount: Option<Amount>,
300 payer_note: Option<String>,
301 ) -> Result<Preimage, LightningRpcError>;
302
303 fn sync_wallet(&self) -> Result<(), LightningRpcError>;
304}
305
306impl dyn ILnRpcClient {
307 pub async fn parsed_route_hints(&self, num_route_hints: u32) -> Vec<RouteHint> {
311 if num_route_hints == 0 {
312 return vec![];
313 }
314
315 let route_hints =
316 self.routehints(num_route_hints as usize)
317 .await
318 .unwrap_or(GetRouteHintsResponse {
319 route_hints: Vec::new(),
320 });
321 route_hints.route_hints
322 }
323
324 pub async fn parsed_node_info(&self) -> LightningInfo {
327 if let Ok(info) = self.info().await
328 && let Ok(network) =
329 Network::from_str(&info.network).map_err(|e| LightningRpcError::InvalidMetadata {
330 failure_reason: format!("Invalid network {}: {e}", info.network),
331 })
332 {
333 return LightningInfo::Connected {
334 public_key: info.pub_key,
335 alias: info.alias,
336 network,
337 block_height: info.block_height as u64,
338 synced_to_chain: info.synced_to_chain,
339 };
340 }
341
342 LightningInfo::NotConnected
343 }
344
345 pub async fn wait_for_chain_sync(&self) -> std::result::Result<(), LightningRpcError> {
347 if is_env_var_set(FM_IN_DEVIMINT_ENV) {
351 self.sync_wallet()?;
352 }
353
354 retry(
356 "Wait for chain sync",
357 backoff_util::background_backoff(),
358 || async {
359 let info = self.info().await?;
360 let block_height = info.block_height;
361 if info.synced_to_chain {
362 Ok(())
363 } else {
364 warn!(target: LOG_LIGHTNING, block_height = %block_height, "Lightning node is not synced yet");
365 Err(ChainSyncAttemptError::NotSynced)
366 }
367 },
368 )
369 .await
370 .map_err(|e| LightningRpcError::FailedToSyncToChain {
371 failure_reason: format!("Failed to sync to chain: {}", e.fmt_compact()),
372 })?;
373
374 info!(target: LOG_LIGHTNING, "Gateway successfully synced with the chain");
375 Ok(())
376 }
377}
378
379#[derive(Debug, Serialize, Deserialize, Clone)]
380pub struct GetNodeInfoResponse {
381 pub pub_key: PublicKey,
382 pub alias: String,
383 pub network: String,
384 pub block_height: u32,
385 pub synced_to_chain: bool,
386}
387
388pub const NO_INCOMING_CIRCUIT: (u64, u64) = (0, 0);
399
400#[derive(Debug, Serialize, Deserialize, Clone)]
401pub struct InterceptPaymentRequest {
402 pub payment_hash: sha256::Hash,
403 pub amount_msat: u64,
408 pub incoming_amount_msat: u64,
411 pub expiry: u32,
417 pub incoming_chan_id: u64,
418 pub short_channel_id: Option<u64>,
419 pub htlc_id: u64,
420}
421
422impl InterceptPaymentRequest {
423 pub fn incoming_circuit(&self) -> Option<(u64, u64)> {
426 let circuit = (self.incoming_chan_id, self.htlc_id);
427 (circuit != NO_INCOMING_CIRCUIT).then_some(circuit)
428 }
429
430 pub fn lnv2_blocks_to_claim_deadline(&self, current_block_height: Option<u32>) -> u32 {
439 if self.incoming_circuit().is_some() {
440 return 0;
441 }
442
443 current_block_height.map_or(0, |height| self.expiry.saturating_sub(height))
444 }
445}
446
447#[derive(Debug, Serialize, Deserialize, Clone)]
448pub struct InterceptPaymentResponse {
449 pub incoming_chan_id: u64,
450 pub htlc_id: u64,
451 pub payment_hash: sha256::Hash,
452 pub action: PaymentAction,
453}
454
455impl InterceptPaymentResponse {
456 pub fn incoming_circuit(&self) -> Option<(u64, u64)> {
465 let circuit = (self.incoming_chan_id, self.htlc_id);
466 (circuit != NO_INCOMING_CIRCUIT).then_some(circuit)
467 }
468}
469
470#[derive(Debug, Serialize, Deserialize, Clone)]
471pub enum PaymentAction {
472 Settle(Preimage),
473 Cancel,
474 Forward,
475}
476
477#[derive(Debug, Serialize, Deserialize, Clone)]
478pub struct GetRouteHintsResponse {
479 pub route_hints: Vec<RouteHint>,
480}
481
482#[derive(Debug, Serialize, Deserialize, Clone)]
483pub struct PayInvoiceResponse {
484 pub preimage: Preimage,
485}
486
487#[derive(Debug, Serialize, Deserialize, Clone)]
488pub struct CreateInvoiceRequest {
489 pub payment_hash: Option<sha256::Hash>,
490 pub amount_msat: u64,
491 pub expiry_secs: u32,
492 pub description: Option<InvoiceDescription>,
493}
494
495#[derive(Debug, Serialize, Deserialize, Clone)]
496pub enum InvoiceDescription {
497 Direct(String),
498 Hash(sha256::Hash),
499}
500
501#[derive(Debug, Serialize, Deserialize, Clone)]
502pub struct CreateInvoiceResponse {
503 pub invoice: String,
504}
505
506#[derive(Debug, Serialize, Deserialize, Clone)]
507pub struct GetLnOnchainAddressResponse {
508 pub address: String,
509}
510
511#[derive(Debug, Serialize, Deserialize, Clone)]
512pub struct SendOnchainResponse {
513 pub txid: String,
514}
515
516#[derive(Debug, Serialize, Deserialize, Clone)]
517pub struct OpenChannelResponse {
518 pub funding_txid: String,
519}
520
521#[derive(Debug, Serialize, Deserialize, Clone)]
522pub struct ListChannelsResponse {
523 pub channels: Vec<ChannelInfo>,
524}
525
526#[derive(Debug, Serialize, Deserialize, Clone)]
527pub struct GetBalancesResponse {
528 pub onchain_balance_sats: u64,
529 pub spendable_onchain_balance_sats: u64,
533 pub lightning_balance_msats: u64,
534 pub inbound_lightning_liquidity_msats: u64,
535}
536
537pub struct LnRpcTracked {
549 inner: Arc<dyn ILnRpcClient>,
550 name: &'static str,
551}
552
553impl std::fmt::Debug for LnRpcTracked {
554 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
555 f.debug_struct("LnRpcTracked")
556 .field("name", &self.name)
557 .field("inner", &self.inner)
558 .finish()
559 }
560}
561
562impl LnRpcTracked {
563 #[allow(clippy::new_ret_no_self)]
568 pub fn new(inner: Arc<dyn ILnRpcClient>, name: &'static str) -> Arc<dyn ILnRpcClient> {
569 Arc::new(Self { inner, name })
570 }
571
572 fn record_call<T, E>(&self, method: &str, result: &Result<T, E>) {
573 let result_label = if result.is_ok() { "success" } else { "error" };
574 metrics::LN_RPC_REQUESTS_TOTAL
575 .with_label_values(&[method, self.name, result_label])
576 .inc();
577 }
578}
579
580macro_rules! tracked_call {
581 ($self:ident, $method:expr, $call:expr) => {{
582 trace!(
583 target: LOG_LIGHTNING,
584 method = $method,
585 name = $self.name,
586 "starting lightning rpc"
587 );
588 let start = now();
589 let timer = metrics::LN_RPC_DURATION_SECONDS
590 .with_label_values(&[$method, $self.name])
591 .start_timer_ext();
592 let result = $call;
593 timer.observe_duration();
594 $self.record_call($method, &result);
595 let duration_ms = now()
596 .duration_since(start)
597 .unwrap_or_default()
598 .as_secs_f64()
599 * 1000.0;
600 trace!(
601 target: LOG_LIGHTNING,
602 method = $method,
603 name = $self.name,
604 duration_ms,
605 error = %result.fmt_compact_result(),
606 "completed lightning rpc"
607 );
608 result
609 }};
610}
611
612#[async_trait]
613impl ILnRpcClient for LnRpcTracked {
614 async fn info(&self) -> Result<GetNodeInfoResponse, LightningRpcError> {
615 tracked_call!(self, "info", self.inner.info().await)
616 }
617
618 async fn routehints(
619 &self,
620 num_route_hints: usize,
621 ) -> Result<GetRouteHintsResponse, LightningRpcError> {
622 tracked_call!(
623 self,
624 "routehints",
625 self.inner.routehints(num_route_hints).await
626 )
627 }
628
629 async fn pay(
630 &self,
631 invoice: Bolt11Invoice,
632 max_delay: u64,
633 max_fee: Amount,
634 ) -> Result<PayInvoiceResponse, LightningRpcError> {
635 tracked_call!(
636 self,
637 "pay",
638 self.inner.pay(invoice, max_delay, max_fee).await
639 )
640 }
641
642 async fn pay_private(
643 &self,
644 invoice: PrunedInvoice,
645 max_delay: u64,
646 max_fee: Amount,
647 ) -> Result<PayInvoiceResponse, LightningRpcError> {
648 tracked_call!(
649 self,
650 "pay_private",
651 self.inner.pay_private(invoice, max_delay, max_fee).await
652 )
653 }
654
655 fn supports_private_payments(&self) -> bool {
656 self.inner.supports_private_payments()
657 }
658
659 async fn outbound_payment_exists(
660 &self,
661 payment_hash: sha256::Hash,
662 ) -> Result<bool, LightningRpcError> {
663 tracked_call!(
664 self,
665 "outbound_payment_exists",
666 self.inner.outbound_payment_exists(payment_hash).await
667 )
668 }
669
670 async fn route_htlcs<'a>(
671 self: Box<Self>,
672 _task_group: &TaskGroup,
673 ) -> Result<(RouteHtlcStream<'a>, Arc<dyn ILnRpcClient>), LightningRpcError> {
674 panic!(
678 "route_htlcs should not be called on LnRpcTracked. \
679 Wrap the Arc returned from route_htlcs instead."
680 );
681 }
682
683 async fn complete_htlc(&self, htlc: InterceptPaymentResponse) -> Result<(), LightningRpcError> {
684 tracked_call!(self, "complete_htlc", self.inner.complete_htlc(htlc).await)
685 }
686
687 async fn create_invoice(
688 &self,
689 create_invoice_request: CreateInvoiceRequest,
690 ) -> Result<CreateInvoiceResponse, LightningRpcError> {
691 tracked_call!(
692 self,
693 "create_invoice",
694 self.inner.create_invoice(create_invoice_request).await
695 )
696 }
697
698 async fn get_ln_onchain_address(
699 &self,
700 ) -> Result<GetLnOnchainAddressResponse, LightningRpcError> {
701 tracked_call!(
702 self,
703 "get_ln_onchain_address",
704 self.inner.get_ln_onchain_address().await
705 )
706 }
707
708 async fn send_onchain(
709 &self,
710 payload: SendOnchainRequest,
711 ) -> Result<SendOnchainResponse, LightningRpcError> {
712 tracked_call!(self, "send_onchain", self.inner.send_onchain(payload).await)
713 }
714
715 async fn open_channel(
716 &self,
717 payload: OpenChannelRequest,
718 ) -> Result<OpenChannelResponse, LightningRpcError> {
719 tracked_call!(self, "open_channel", self.inner.open_channel(payload).await)
720 }
721
722 async fn connect_peer(&self, payload: ConnectPeerRequest) -> Result<(), LightningRpcError> {
723 tracked_call!(self, "connect_peer", self.inner.connect_peer(payload).await)
724 }
725
726 async fn close_channels_with_peer(
727 &self,
728 payload: CloseChannelsWithPeerRequest,
729 ) -> Result<CloseChannelsWithPeerResponse, LightningRpcError> {
730 tracked_call!(
731 self,
732 "close_channels_with_peer",
733 self.inner.close_channels_with_peer(payload).await
734 )
735 }
736
737 async fn list_channels(&self) -> Result<ListChannelsResponse, LightningRpcError> {
738 tracked_call!(self, "list_channels", self.inner.list_channels().await)
739 }
740
741 async fn set_channel_fees(
742 &self,
743 payload: SetChannelFeesRequest,
744 ) -> Result<(), LightningRpcError> {
745 tracked_call!(
746 self,
747 "set_channel_fees",
748 self.inner.set_channel_fees(payload).await
749 )
750 }
751
752 async fn get_balances(&self) -> Result<GetBalancesResponse, LightningRpcError> {
753 tracked_call!(self, "get_balances", self.inner.get_balances().await)
754 }
755
756 async fn get_invoice(
757 &self,
758 get_invoice_request: GetInvoiceRequest,
759 ) -> Result<Option<GetInvoiceResponse>, LightningRpcError> {
760 tracked_call!(
761 self,
762 "get_invoice",
763 self.inner.get_invoice(get_invoice_request).await
764 )
765 }
766
767 async fn list_transactions(
768 &self,
769 start_secs: u64,
770 end_secs: u64,
771 ) -> Result<ListTransactionsResponse, LightningRpcError> {
772 tracked_call!(
773 self,
774 "list_transactions",
775 self.inner.list_transactions(start_secs, end_secs).await
776 )
777 }
778
779 fn create_offer(
780 &self,
781 amount: Option<Amount>,
782 description: Option<String>,
783 expiry_secs: Option<u32>,
784 quantity: Option<u64>,
785 ) -> Result<String, LightningRpcError> {
786 tracked_call!(
787 self,
788 "create_offer",
789 self.inner
790 .create_offer(amount, description, expiry_secs, quantity)
791 )
792 }
793
794 async fn pay_offer(
795 &self,
796 offer: String,
797 quantity: Option<u64>,
798 amount: Option<Amount>,
799 payer_note: Option<String>,
800 ) -> Result<Preimage, LightningRpcError> {
801 tracked_call!(
802 self,
803 "pay_offer",
804 self.inner
805 .pay_offer(offer, quantity, amount, payer_note)
806 .await
807 )
808 }
809
810 fn sync_wallet(&self) -> Result<(), LightningRpcError> {
811 tracked_call!(self, "sync_wallet", self.inner.sync_wallet())
812 }
813}
814
815#[derive(Debug, Error)]
817enum ChainSyncAttemptError {
818 #[error(transparent)]
820 Info(#[from] LightningRpcError),
821
822 #[error("Not synced yet")]
824 NotSynced,
825}
826
827#[cfg(test)]
828mod tests;