1use std::collections::{BTreeMap, HashMap};
2use std::path::Path;
3use std::str::FromStr;
4use std::sync::Arc;
5use std::time::{Duration, UNIX_EPOCH};
6
7use async_trait::async_trait;
8use bitcoin::hashes::{Hash, sha256};
9use bitcoin::{FeeRate, Network, OutPoint};
10use fedimint_bip39::Mnemonic;
11use fedimint_core::envs::is_running_in_test_env;
12use fedimint_core::task::{TaskGroup, TaskHandle, block_in_place};
13use fedimint_core::util::{FmtCompact, SafeUrl};
14use fedimint_core::{Amount, BitcoinAmountOrAll, crit};
15use fedimint_gateway_common::{
16 ChainSource, ConnectPeerRequest, GetInvoiceRequest, GetInvoiceResponse,
17 ListTransactionsResponse, NodeAddress, SetChannelFeesRequest,
18};
19use fedimint_ln_common::contracts::Preimage;
20use fedimint_logging::{LOG_LIGHTNING, LOG_LIGHTNING_LDK};
21use ldk_node::config::ChannelConfig;
22use ldk_node::lightning::ln::msgs::SocketAddress;
23use ldk_node::lightning::routing::gossip::{NodeAlias, NodeId};
24use ldk_node::logger::{LogLevel, LogRecord, LogWriter};
25use ldk_node::payment::{PaymentDetails, PaymentDirection, PaymentKind, PaymentStatus};
26use lightning::ln::channelmanager::PaymentId;
27use lightning::offers::offer::{Offer, OfferId};
28use lightning::routing::router::RouteParametersConfig;
29use lightning::types::payment::{PaymentHash, PaymentPreimage};
30use lightning_invoice::{Bolt11Invoice, Bolt11InvoiceDescription, Description};
31use thiserror::Error;
32use tokio::sync::mpsc::Sender;
33use tokio::sync::{RwLock, oneshot};
34use tokio_stream::wrappers::ReceiverStream;
35use tracing::{debug, error, info, trace, warn};
36
37use super::{ChannelInfo, ILnRpcClient, LightningRpcError, ListChannelsResponse, RouteHtlcStream};
38use crate::{
39 CloseChannelsWithPeerRequest, CloseChannelsWithPeerResponse, CreateInvoiceRequest,
40 CreateInvoiceResponse, GetBalancesResponse, GetLnOnchainAddressResponse, GetNodeInfoResponse,
41 GetRouteHintsResponse, InterceptPaymentRequest, InterceptPaymentResponse, InvoiceDescription,
42 NO_INCOMING_CIRCUIT, OpenChannelRequest, OpenChannelResponse, PayInvoiceResponse,
43 PaymentAction, SendOnchainRequest, SendOnchainResponse,
44};
45
46struct LdkTracingLogger {
54 in_test_env: bool,
58}
59
60impl LdkTracingLogger {
61 fn downgraded_level(&self, record: &LogRecord<'_>) -> LogLevel {
71 if self.in_test_env
72 && record.level == LogLevel::Error
73 && record.module_path == "ldk_node::chain"
74 && format!("{}", record.args).contains("Failed to retrieve fee rate estimates")
75 {
76 LogLevel::Debug
77 } else {
78 record.level
79 }
80 }
81}
82
83impl LogWriter for LdkTracingLogger {
84 fn log(&self, record: LogRecord<'_>) {
85 match self.downgraded_level(&record) {
87 LogLevel::Gossip | LogLevel::Trace => trace!(
88 target: LOG_LIGHTNING_LDK,
89 ldk_module = record.module_path, line = record.line, "{}", record.args,
90 ),
91 LogLevel::Debug => debug!(
92 target: LOG_LIGHTNING_LDK,
93 ldk_module = record.module_path, line = record.line, "{}", record.args,
94 ),
95 LogLevel::Info => info!(
96 target: LOG_LIGHTNING_LDK,
97 ldk_module = record.module_path, line = record.line, "{}", record.args,
98 ),
99 LogLevel::Warn => warn!(
100 target: LOG_LIGHTNING_LDK,
101 ldk_module = record.module_path, line = record.line, "{}", record.args,
102 ),
103 LogLevel::Error => error!(
104 target: LOG_LIGHTNING_LDK,
105 ldk_module = record.module_path, line = record.line, "{}", record.args,
106 ),
107 }
108 }
109}
110
111pub struct GatewayLdkClient {
112 node: Arc<ldk_node::Node>,
114
115 task_group: TaskGroup,
116
117 htlc_stream_receiver_or: Option<tokio::sync::mpsc::Receiver<InterceptPaymentRequest>>,
120
121 outbound_lightning_payment_lock_pool: lockable::LockPool<PaymentId>,
125
126 outbound_offer_lock_pool: lockable::LockPool<LdkOfferId>,
131
132 pending_channels: Arc<RwLock<BTreeMap<UserChannelId, PendingChannelSender>>>,
137
138 pending_payments: Arc<RwLock<HashMap<PaymentId, oneshot::Sender<()>>>>,
144}
145
146type PendingChannelSender = oneshot::Sender<Result<OutPoint, String>>;
149
150impl std::fmt::Debug for GatewayLdkClient {
151 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
152 f.debug_struct("GatewayLdkClient").finish_non_exhaustive()
153 }
154}
155
156#[derive(Debug, Clone, Copy, PartialEq, Eq)]
158pub enum MnemonicSource {
159 Generated,
162 Existing,
168}
169
170impl GatewayLdkClient {
171 #[allow(clippy::too_many_arguments)]
183 pub fn new(
184 data_dir: &Path,
185 chain_source: ChainSource,
186 network: Network,
187 lightning_port: u16,
188 alias: String,
189 mnemonic: Mnemonic,
190 mnemonic_source: MnemonicSource,
191 runtime: Arc<tokio::runtime::Runtime>,
192 ) -> Result<Self, LdkClientInitError> {
193 let mut bytes = [0u8; 32];
194 let alias = if alias.is_empty() {
195 "LDK Gateway".to_string()
196 } else {
197 alias
198 };
199 let alias_bytes = alias.as_bytes();
200 let truncated = &alias_bytes[..alias_bytes.len().min(32)];
201 bytes[..truncated.len()].copy_from_slice(truncated);
202 let node_alias = Some(NodeAlias(bytes));
203
204 let mut node_builder = ldk_node::Builder::from_config(ldk_node::config::Config {
205 network,
206 listening_addresses: Some(vec![SocketAddress::TcpIpV4 {
207 addr: [0, 0, 0, 0],
208 port: lightning_port,
209 }]),
210 node_alias,
211 ..Default::default()
212 });
213
214 node_builder.set_custom_logger(Arc::new(LdkTracingLogger {
218 in_test_env: is_running_in_test_env(),
219 }));
220
221 node_builder.set_entropy_bip39_mnemonic(mnemonic, None);
222
223 match chain_source.clone() {
224 ChainSource::Bitcoind {
225 username,
226 password,
227 server_url,
228 } => {
229 node_builder.set_chain_source_bitcoind_rpc(
230 server_url
231 .host_str()
232 .expect("Could not retrieve host from bitcoind RPC url")
233 .to_string(),
234 server_url
235 .port()
236 .expect("Could not retrieve port from bitcoind RPC url"),
237 username,
238 password,
239 );
240 }
241 ChainSource::Esplora { server_url } => {
242 node_builder.set_chain_source_esplora(get_esplora_url(server_url)?, None);
243 }
244 };
245 let Some(data_dir_str) = data_dir.to_str() else {
246 return Err(LdkClientInitError::InvalidDataDir);
247 };
248 node_builder.set_storage_dir_path(data_dir_str.to_string());
249 node_builder.set_runtime(runtime.handle().clone());
250 if mnemonic_source == MnemonicSource::Existing {
251 info!(
252 target: LOG_LIGHTNING,
253 "Mnemonic was not generated by this process, recovering onchain wallet from genesis if it does not exist yet"
254 );
255 node_builder.set_wallet_recovery_mode();
256 }
257
258 info!(chain_source = %chain_source, data_dir = %data_dir_str, alias = %alias, "Starting LDK Node...");
259 let node = Arc::new(node_builder.build().map_err(LdkClientInitError::Build)?);
260 node.start().map_err(|err| {
261 crit!(target: LOG_LIGHTNING, err = %err.fmt_compact(), "Failed to start LDK Node");
262 LdkClientInitError::Start(err)
263 })?;
264
265 let (htlc_stream_sender, htlc_stream_receiver) = tokio::sync::mpsc::channel(1024);
266 let task_group = TaskGroup::new();
267
268 let node_clone = node.clone();
269 let pending_channels = Arc::new(RwLock::new(BTreeMap::new()));
270 let pending_channels_clone = pending_channels.clone();
271 let pending_payments = Arc::new(RwLock::new(HashMap::new()));
272 let pending_payments_clone = pending_payments.clone();
273 task_group.spawn("ldk lightning node event handler", |handle| async move {
274 loop {
275 Self::handle_next_event(
276 &node_clone,
277 &htlc_stream_sender,
278 &handle,
279 pending_channels_clone.clone(),
280 pending_payments_clone.clone(),
281 )
282 .await;
283 }
284 });
285
286 info!("Successfully started LDK Gateway");
287 Ok(GatewayLdkClient {
288 node,
289 task_group,
290 htlc_stream_receiver_or: Some(htlc_stream_receiver),
291 outbound_lightning_payment_lock_pool: lockable::LockPool::new(),
292 outbound_offer_lock_pool: lockable::LockPool::new(),
293 pending_channels,
294 pending_payments,
295 })
296 }
297
298 async fn handle_next_event(
299 node: &ldk_node::Node,
300 htlc_stream_sender: &Sender<InterceptPaymentRequest>,
301 handle: &TaskHandle,
302 pending_channels: Arc<RwLock<BTreeMap<UserChannelId, PendingChannelSender>>>,
303 pending_payments: Arc<RwLock<HashMap<PaymentId, oneshot::Sender<()>>>>,
304 ) {
305 let event = tokio::select! {
309 event = node.next_event_async() => {
310 event
311 }
312 () = handle.make_shutdown_rx() => {
313 return;
314 }
315 };
316
317 match event {
318 ldk_node::Event::PaymentClaimable {
319 payment_id: _,
320 payment_hash,
321 claimable_amount_msat,
322 claim_deadline,
323 custom_records: _,
324 } => {
325 if let Err(err) = htlc_stream_sender
326 .send(InterceptPaymentRequest {
327 payment_hash: Hash::from_slice(&payment_hash.0)
328 .expect("Failed to create Hash"),
329 amount_msat: claimable_amount_msat,
332 incoming_amount_msat: claimable_amount_msat,
333 expiry: claim_deadline.unwrap_or_default(),
334 short_channel_id: None,
335 incoming_chan_id: NO_INCOMING_CIRCUIT.0,
338 htlc_id: NO_INCOMING_CIRCUIT.1,
339 })
340 .await
341 {
342 warn!(target: LOG_LIGHTNING, err = %err.fmt_compact(), "Failed send InterceptHtlcRequest to stream");
343 }
344 }
345 ldk_node::Event::ChannelPending {
346 channel_id,
347 user_channel_id,
348 former_temporary_channel_id: _,
349 counterparty_node_id: _,
350 funding_txo,
351 } => {
352 info!(target: LOG_LIGHTNING, %channel_id, "LDK Channel is pending");
353 let mut channels = pending_channels.write().await;
354 if let Some(sender) = channels.remove(&UserChannelId(user_channel_id)) {
355 let _ = sender.send(Ok(funding_txo));
356 } else {
357 debug!(
358 ?user_channel_id,
359 "No channel pending channel open for user channel id"
360 );
361 }
362 }
363 ldk_node::Event::ChannelClosed {
364 channel_id,
365 user_channel_id,
366 counterparty_node_id: _,
367 reason,
368 } => {
369 info!(target: LOG_LIGHTNING, %channel_id, "LDK Channel is closed");
370 let mut channels = pending_channels.write().await;
371 if let Some(sender) = channels.remove(&UserChannelId(user_channel_id)) {
372 let reason = if let Some(reason) = reason {
373 reason.to_string()
374 } else {
375 "Channel has been closed".to_string()
376 };
377 let _ = sender.send(Err(reason));
378 } else {
379 debug!(
380 ?user_channel_id,
381 "No channel pending channel open for user channel id"
382 );
383 }
384 }
385 ldk_node::Event::PaymentSuccessful {
386 payment_id: Some(payment_id),
387 ..
388 }
389 | ldk_node::Event::PaymentFailed {
390 payment_id: Some(payment_id),
391 ..
392 } => {
393 Self::wake_pending_payment(&pending_payments, payment_id).await;
394 }
395 _ => {}
396 }
397
398 if let Err(err) = node.event_handled() {
403 warn!(err = %err.fmt_compact(), "LDK could not mark event handled");
404 }
405 }
406
407 async fn wake_pending_payment(
411 pending_payments: &Arc<RwLock<HashMap<PaymentId, oneshot::Sender<()>>>>,
412 payment_id: PaymentId,
413 ) -> PendingPaymentWakeup {
414 let Some(sender) = pending_payments.write().await.remove(&payment_id) else {
415 return PendingPaymentWakeup::NoWaiter;
416 };
417
418 if sender.send(()).is_ok() {
419 PendingPaymentWakeup::Woken
420 } else {
421 PendingPaymentWakeup::ReceiverDropped
422 }
423 }
424
425 fn outbound_payment(&self, payment_id: PaymentId) -> Option<PaymentDetails> {
435 self.node
436 .payment(&payment_id)
437 .filter(|details| details.direction == PaymentDirection::Outbound)
438 }
439
440 fn ldk_payment_result(
445 &self,
446 payment_id: PaymentId,
447 ) -> Option<Result<PayInvoiceResponse, LightningRpcError>> {
448 let payment_details = self.outbound_payment(payment_id)?;
449 match payment_details.status {
450 PaymentStatus::Pending => None,
451 PaymentStatus::Succeeded => {
452 if let PaymentKind::Bolt11 {
453 preimage: Some(preimage),
454 ..
455 } = payment_details.kind
456 {
457 Some(Ok(PayInvoiceResponse {
458 preimage: Preimage(preimage.0),
459 }))
460 } else {
461 Some(Err(LightningRpcError::FailedPayment {
462 failure_reason: "LDK payment succeeded without preimage".to_string(),
463 }))
464 }
465 }
466 PaymentStatus::Failed => Some(Err(LightningRpcError::FailedPayment {
467 failure_reason: "LDK payment failed".to_string(),
468 })),
469 }
470 }
471}
472
473#[derive(Debug, Error)]
478#[non_exhaustive]
479pub enum LdkClientInitError {
480 #[error("Missing esplora host")]
482 MissingEsploraHost,
483
484 #[error("Invalid data dir path")]
487 InvalidDataDir,
488
489 #[error("The LDK node could not be built")]
492 Build(#[source] ldk_node::BuildError),
493
494 #[error("The LDK node could not be started")]
496 Start(#[source] ldk_node::NodeError),
497}
498
499#[derive(Debug, Clone, Copy, PartialEq, Eq)]
501enum InboundRegistrationRefusal {
502 OutboundInFlight,
505 OutboundRecorded,
507}
508
509impl std::fmt::Display for InboundRegistrationRefusal {
510 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
511 match self {
512 Self::OutboundInFlight => {
513 write!(f, "an outbound payment for this hash is in flight")
514 }
515 Self::OutboundRecorded => {
516 write!(f, "the node holds an outbound payment for this hash")
517 }
518 }
519 }
520}
521
522fn check_inbound_registration(
539 outbound_lock_acquired: bool,
540 existing_direction: Option<PaymentDirection>,
541) -> Result<(), InboundRegistrationRefusal> {
542 if !outbound_lock_acquired {
543 return Err(InboundRegistrationRefusal::OutboundInFlight);
544 }
545
546 match existing_direction {
547 Some(PaymentDirection::Outbound) => Err(InboundRegistrationRefusal::OutboundRecorded),
548 Some(PaymentDirection::Inbound) | None => Ok(()),
549 }
550}
551
552fn htlc_completion_error(err: &ldk_node::NodeError, payment_hash: &str) -> LightningRpcError {
564 match err {
565 ldk_node::NodeError::InvalidPaymentHash
566 | ldk_node::NodeError::InvalidPaymentPreimage
567 | ldk_node::NodeError::InvalidAmount => LightningRpcError::HtlcCompletionRejected {
568 failure_reason: format!(
569 "LDK rejected completion of payment with hash {payment_hash}: {err}"
570 ),
571 },
572 _ => LightningRpcError::FailedToCompleteHtlc {
573 failure_reason: format!(
574 "Failed to complete LDK payment with hash {payment_hash}: {err}"
575 ),
576 },
577 }
578}
579
580impl Drop for GatewayLdkClient {
581 fn drop(&mut self) {
582 self.task_group.shutdown();
583
584 info!(target: LOG_LIGHTNING, "Stopping LDK Node...");
585 match self.node.stop() {
586 Err(err) => {
587 warn!(target: LOG_LIGHTNING, err = %err.fmt_compact(), "Failed to stop LDK Node");
588 }
589 _ => {
590 info!(target: LOG_LIGHTNING, "LDK Node stopped.");
591 }
592 }
593 }
594}
595
596#[async_trait]
597impl ILnRpcClient for GatewayLdkClient {
598 async fn info(&self) -> Result<GetNodeInfoResponse, LightningRpcError> {
599 let node_status = self.node.status();
600 let ldk_block_height = node_status.current_best_block.height;
601 let onchain_sync = node_status.latest_onchain_wallet_sync_timestamp;
602 let lightning_sync = node_status.latest_lightning_wallet_sync_timestamp;
603 let is_running = node_status.is_running;
604 debug!(target: LOG_LIGHTNING, ?onchain_sync, ?lightning_sync, ?is_running, "LDK Sync Status");
605
606 Ok(GetNodeInfoResponse {
607 pub_key: self.node.node_id(),
608 alias: match self.node.node_alias() {
609 Some(alias) => alias.to_string(),
610 None => format!("LDK Fedimint Gateway Node {}", self.node.node_id()),
611 },
612 network: self.node.config().network.to_string(),
613 block_height: ldk_block_height,
614 synced_to_chain: lightning_sync.is_some(),
617 })
618 }
619
620 async fn routehints(
621 &self,
622 _num_route_hints: usize,
623 ) -> Result<GetRouteHintsResponse, LightningRpcError> {
624 Ok(GetRouteHintsResponse {
630 route_hints: vec![],
631 })
632 }
633
634 async fn pay(
635 &self,
636 invoice: Bolt11Invoice,
637 max_delay: u64,
638 max_fee: Amount,
639 ) -> Result<PayInvoiceResponse, LightningRpcError> {
640 let payment_id = PaymentId(*invoice.payment_hash().as_byte_array());
641
642 let _payment_lock_guard = self
648 .outbound_lightning_payment_lock_pool
649 .async_lock(payment_id)
650 .await;
651
652 let (payment_sender, payment_receiver) = oneshot::channel();
656 self.pending_payments
657 .write()
658 .await
659 .insert(payment_id, payment_sender);
660
661 if self.outbound_payment(payment_id).is_none() {
672 let sent_payment_id = match self.node.bolt11_payment().send(
673 &invoice,
674 Some(
675 RouteParametersConfig::default()
676 .with_max_total_routing_fee_msat(max_fee.msats)
677 .with_max_total_cltv_expiry_delta(max_delay as u32),
678 ),
679 ) {
680 Ok(sent_payment_id) => sent_payment_id,
681 Err(err) => {
682 self.pending_payments.write().await.remove(&payment_id);
683 return Err(LightningRpcError::FailedPayment {
686 failure_reason: format!("LDK payment failed to initialize: {err:?}"),
687 });
688 }
689 };
690 assert_eq!(sent_payment_id, payment_id);
691 }
692
693 if let Some(result) = self.ldk_payment_result(payment_id) {
697 self.pending_payments.write().await.remove(&payment_id);
698 return result;
699 }
700
701 let _ = payment_receiver.await;
706
707 self.pending_payments.write().await.remove(&payment_id);
708 self.ldk_payment_result(payment_id).unwrap_or_else(|| {
709 Err(LightningRpcError::FailedPayment {
710 failure_reason: "LDK payment event fired without terminal payment status"
711 .to_string(),
712 })
713 })
714 }
715
716 async fn outbound_payment_exists(
717 &self,
718 payment_hash: sha256::Hash,
719 ) -> Result<bool, LightningRpcError> {
720 Ok(self
721 .outbound_payment(PaymentId(payment_hash.to_byte_array()))
722 .is_some())
723 }
724
725 async fn route_htlcs<'a>(
726 mut self: Box<Self>,
727 _task_group: &TaskGroup,
728 ) -> Result<(RouteHtlcStream<'a>, Arc<dyn ILnRpcClient>), LightningRpcError> {
729 let route_htlc_stream = match self.htlc_stream_receiver_or.take() {
730 Some(stream) => Ok(Box::pin(ReceiverStream::new(stream))),
731 None => Err(LightningRpcError::FailedToRouteHtlcs {
732 failure_reason:
733 "Stream does not exist. Likely was already taken by calling `route_htlcs()`."
734 .to_string(),
735 }),
736 }?;
737
738 Ok((route_htlc_stream, Arc::new(*self)))
739 }
740
741 async fn complete_htlc(&self, htlc: InterceptPaymentResponse) -> Result<(), LightningRpcError> {
742 let InterceptPaymentResponse {
743 action,
744 payment_hash,
745 incoming_chan_id: _,
746 htlc_id: _,
747 } = htlc;
748
749 let ph = PaymentHash(*payment_hash.clone().as_byte_array());
750
751 let claimable_amount_msat = 999_999_999_999_999;
757
758 let ph_hex_str = hex::encode(payment_hash);
759
760 if let PaymentAction::Settle(preimage) = action {
761 self.node
762 .bolt11_payment()
763 .claim_for_hash(ph, claimable_amount_msat, PaymentPreimage(preimage.0))
764 .map_err(|err| htlc_completion_error(&err, &ph_hex_str))?;
765 } else {
766 warn!(target: LOG_LIGHTNING, payment_hash = %ph_hex_str, "Unwinding payment because the action was not `Settle`");
767 self.node
768 .bolt11_payment()
769 .fail_for_hash(ph)
770 .map_err(|err| htlc_completion_error(&err, &ph_hex_str))?;
771 }
772
773 return Ok(());
774 }
775
776 async fn create_invoice(
777 &self,
778 create_invoice_request: CreateInvoiceRequest,
779 ) -> Result<CreateInvoiceResponse, LightningRpcError> {
780 let payment_hash_or = if let Some(payment_hash) = create_invoice_request.payment_hash {
781 let ph = PaymentHash(*payment_hash.as_byte_array());
782 Some(ph)
783 } else {
784 None
785 };
786
787 let description = match create_invoice_request.description {
788 Some(InvoiceDescription::Direct(desc)) => {
789 Bolt11InvoiceDescription::Direct(Description::new(desc).map_err(|_| {
790 LightningRpcError::FailedToGetInvoice {
791 failure_reason: "Invalid description".to_string(),
792 }
793 })?)
794 }
795 Some(InvoiceDescription::Hash(hash)) => {
796 Bolt11InvoiceDescription::Hash(lightning_invoice::Sha256(hash))
797 }
798 None => Bolt11InvoiceDescription::Direct(Description::empty()),
799 };
800
801 let invoice = match payment_hash_or {
802 Some(payment_hash) => {
803 let payment_id = PaymentId(payment_hash.0);
810 let outbound_lock_guard = self
811 .outbound_lightning_payment_lock_pool
812 .try_lock(payment_id);
813 let existing_direction = self
814 .node
815 .payment(&payment_id)
816 .map(|details| details.direction);
817 if let Err(refusal) =
818 check_inbound_registration(outbound_lock_guard.is_some(), existing_direction)
819 {
820 warn!(
821 target: LOG_LIGHTNING,
822 payment_hash = %hex::encode(payment_hash.0),
823 %refusal,
824 "Refusing to register an invoice for a payment hash we pay outbound"
825 );
826 return Err(LightningRpcError::FailedToGetInvoice {
827 failure_reason: format!(
828 "Payment hash cannot be registered for an invoice: {refusal}"
829 ),
830 });
831 }
832
833 self.node.bolt11_payment().receive_for_hash(
834 create_invoice_request.amount_msat,
835 &description,
836 create_invoice_request.expiry_secs,
837 payment_hash,
838 )
839 }
840 None => self.node.bolt11_payment().receive(
841 create_invoice_request.amount_msat,
842 &description,
843 create_invoice_request.expiry_secs,
844 ),
845 }
846 .map_err(|e| LightningRpcError::FailedToGetInvoice {
847 failure_reason: e.to_string(),
848 })?;
849
850 Ok(CreateInvoiceResponse {
851 invoice: invoice.to_string(),
852 })
853 }
854
855 async fn get_ln_onchain_address(
856 &self,
857 ) -> Result<GetLnOnchainAddressResponse, LightningRpcError> {
858 self.node
859 .onchain_payment()
860 .new_address()
861 .map(|address| GetLnOnchainAddressResponse {
862 address: address.to_string(),
863 })
864 .map_err(|e| LightningRpcError::FailedToGetLnOnchainAddress {
865 failure_reason: e.to_string(),
866 })
867 }
868
869 async fn send_onchain(
870 &self,
871 SendOnchainRequest {
872 address,
873 amount,
874 fee_rate_sats_per_vbyte,
875 }: SendOnchainRequest,
876 ) -> Result<SendOnchainResponse, LightningRpcError> {
877 let onchain = self.node.onchain_payment();
878
879 let retain_reserves = false;
880 let txid = match amount {
881 BitcoinAmountOrAll::All => onchain.send_all_to_address(
882 &address.assume_checked(),
883 retain_reserves,
884 FeeRate::from_sat_per_vb(fee_rate_sats_per_vbyte),
885 ),
886 BitcoinAmountOrAll::Amount(amount_sats) => onchain.send_to_address(
887 &address.assume_checked(),
888 amount_sats.to_sat(),
889 FeeRate::from_sat_per_vb(fee_rate_sats_per_vbyte),
890 ),
891 }
892 .map_err(|e| LightningRpcError::FailedToWithdrawOnchain {
893 failure_reason: e.to_string(),
894 })?;
895
896 Ok(SendOnchainResponse {
897 txid: txid.to_string(),
898 })
899 }
900
901 async fn open_channel(
902 &self,
903 OpenChannelRequest {
904 pubkey,
905 host,
906 channel_size_sats,
907 push_amount_sats,
908 fee_rate_sats_per_vbyte,
909 base_fee_msat,
910 parts_per_million,
911 }: OpenChannelRequest,
912 ) -> Result<OpenChannelResponse, LightningRpcError> {
913 let push_amount_msats_or = channel_push_amount_msats(push_amount_sats)?;
914
915 if fee_rate_sats_per_vbyte.is_some() {
916 warn!(
919 target: LOG_LIGHTNING,
920 "Ignoring fee_rate_sats_per_vbyte on LDK channel open; LDK uses its built-in fee estimator"
921 );
922 }
923
924 let channel_config = match (base_fee_msat, parts_per_million) {
925 (None, None) => None,
926 (base, ppm) => {
927 let mut config = ChannelConfig::default();
928 if let Some(base) = base {
929 config.forwarding_fee_base_msat = u32::try_from(base).map_err(|_| {
930 LightningRpcError::FailedToOpenChannel {
931 failure_reason: format!(
932 "base_fee_msat {base} does not fit in u32 (LDK limit)"
933 ),
934 }
935 })?;
936 }
937 if let Some(ppm) = ppm {
938 config.forwarding_fee_proportional_millionths =
939 u32::try_from(ppm).map_err(|_| LightningRpcError::FailedToOpenChannel {
940 failure_reason: format!(
941 "parts_per_million {ppm} does not fit in u32 (LDK limit)"
942 ),
943 })?;
944 }
945 Some(config)
946 }
947 };
948
949 let (tx, rx) = oneshot::channel::<Result<OutPoint, String>>();
950
951 {
952 let mut channels = self.pending_channels.write().await;
953 let user_channel_id = self
954 .node
955 .open_announced_channel(
956 pubkey,
957 SocketAddress::from_str(&host).map_err(|e| {
958 LightningRpcError::FailedToConnectToPeer {
959 failure_reason: e.to_string(),
960 }
961 })?,
962 channel_size_sats,
963 push_amount_msats_or,
964 channel_config,
965 )
966 .map_err(|e| LightningRpcError::FailedToOpenChannel {
967 failure_reason: e.to_string(),
968 })?;
969
970 channels.insert(UserChannelId(user_channel_id), tx);
971 }
972
973 match rx
974 .await
975 .map_err(|err| LightningRpcError::FailedToOpenChannel {
976 failure_reason: err.to_string(),
977 })? {
978 Ok(outpoint) => {
979 let funding_txid = outpoint.txid;
980
981 Ok(OpenChannelResponse {
982 funding_txid: funding_txid.to_string(),
983 })
984 }
985 Err(failure_reason) => Err(LightningRpcError::FailedToOpenChannel { failure_reason }),
986 }
987 }
988
989 async fn connect_peer(&self, payload: ConnectPeerRequest) -> Result<(), LightningRpcError> {
990 let NodeAddress { pubkey, address } = payload.node_address;
991 self.node.connect(pubkey, address, true).map_err(|e| {
997 LightningRpcError::FailedToConnectToPeer {
998 failure_reason: e.to_string(),
999 }
1000 })
1001 }
1002
1003 async fn close_channels_with_peer(
1004 &self,
1005 CloseChannelsWithPeerRequest {
1006 pubkey,
1007 force,
1008 sats_per_vbyte: _,
1009 }: CloseChannelsWithPeerRequest,
1010 ) -> Result<CloseChannelsWithPeerResponse, LightningRpcError> {
1011 let mut num_channels_closed = 0;
1012
1013 info!(%pubkey, "Closing all channels with peer");
1014 for channel_with_peer in self
1015 .node
1016 .list_channels()
1017 .iter()
1018 .filter(|channel| channel.counterparty_node_id == pubkey)
1019 {
1020 if force {
1021 match self.node.force_close_channel(
1022 &channel_with_peer.user_channel_id,
1023 pubkey,
1024 Some("User initiated force close".to_string()),
1025 ) {
1026 Ok(()) => num_channels_closed += 1,
1027 Err(err) => {
1028 error!(%pubkey, err = %err.fmt_compact(), "Could not force close channel");
1029 }
1030 }
1031 } else {
1032 match self
1033 .node
1034 .close_channel(&channel_with_peer.user_channel_id, pubkey)
1035 {
1036 Ok(()) => {
1037 num_channels_closed += 1;
1038 }
1039 Err(err) => {
1040 error!(%pubkey, err = %err.fmt_compact(), "Could not close channel");
1041 }
1042 }
1043 }
1044 }
1045
1046 Ok(CloseChannelsWithPeerResponse {
1047 num_channels_closed,
1048 })
1049 }
1050
1051 async fn list_channels(&self) -> Result<ListChannelsResponse, LightningRpcError> {
1052 let mut channels = Vec::new();
1053 let network_graph = self.node.network_graph();
1054
1055 let peer_addresses: std::collections::HashMap<_, _> = self
1057 .node
1058 .list_peers()
1059 .into_iter()
1060 .map(|peer| (peer.node_id, peer.address.to_string()))
1061 .collect();
1062
1063 for channel_details in self.node.list_channels().iter() {
1064 let node_id = NodeId::from_pubkey(&channel_details.counterparty_node_id);
1065 let node_info = network_graph.node(&node_id);
1066
1067 let remote_node_alias = node_info.as_ref().and_then(|info| {
1069 info.announcement_info.as_ref().and_then(|announcement| {
1070 let alias = announcement.alias().to_string();
1071 if alias.is_empty() { None } else { Some(alias) }
1072 })
1073 });
1074
1075 let remote_address = peer_addresses
1076 .get(&channel_details.counterparty_node_id)
1077 .cloned();
1078
1079 channels.push(ChannelInfo {
1080 remote_pubkey: channel_details.counterparty_node_id,
1081 channel_size_sats: channel_details.channel_value_sats,
1082 outbound_liquidity_sats: channel_details.outbound_capacity_msat / 1000,
1083 inbound_liquidity_sats: channel_details.inbound_capacity_msat / 1000,
1084 is_active: channel_details.is_usable,
1085 funding_outpoint: channel_details.funding_txo,
1086 remote_node_alias,
1087 remote_address,
1088 base_fee_msat: Some(u64::from(channel_details.config.forwarding_fee_base_msat)),
1089 parts_per_million: Some(u64::from(
1090 channel_details
1091 .config
1092 .forwarding_fee_proportional_millionths,
1093 )),
1094 });
1095 }
1096
1097 Ok(ListChannelsResponse { channels })
1098 }
1099
1100 async fn set_channel_fees(
1101 &self,
1102 payload: SetChannelFeesRequest,
1103 ) -> Result<(), LightningRpcError> {
1104 let channel = self
1108 .node
1109 .list_channels()
1110 .into_iter()
1111 .find(|c| c.funding_txo == Some(payload.funding_outpoint))
1112 .ok_or_else(|| LightningRpcError::FailedToSetChannelFees {
1113 failure_reason: format!(
1114 "No channel found with funding outpoint {}",
1115 payload.funding_outpoint,
1116 ),
1117 })?;
1118
1119 let forwarding_fee_base_msat = u32::try_from(payload.base_fee_msat).map_err(|_| {
1120 LightningRpcError::FailedToSetChannelFees {
1121 failure_reason: format!(
1122 "base_fee_msat {} does not fit in u32 (LDK limit)",
1123 payload.base_fee_msat,
1124 ),
1125 }
1126 })?;
1127 let forwarding_fee_proportional_millionths = u32::try_from(payload.parts_per_million)
1128 .map_err(|_| LightningRpcError::FailedToSetChannelFees {
1129 failure_reason: format!(
1130 "parts_per_million {} does not fit in u32 (LDK limit)",
1131 payload.parts_per_million,
1132 ),
1133 })?;
1134
1135 let new_config = ChannelConfig {
1138 forwarding_fee_base_msat,
1139 forwarding_fee_proportional_millionths,
1140 ..channel.config
1141 };
1142
1143 self.node
1144 .update_channel_config(
1145 &channel.user_channel_id,
1146 channel.counterparty_node_id,
1147 new_config,
1148 )
1149 .map_err(|e| LightningRpcError::FailedToSetChannelFees {
1150 failure_reason: e.to_string(),
1151 })?;
1152
1153 Ok(())
1154 }
1155
1156 async fn get_balances(&self) -> Result<GetBalancesResponse, LightningRpcError> {
1157 let balances = self.node.list_balances();
1158 let channel_lists = self
1159 .node
1160 .list_channels()
1161 .into_iter()
1162 .filter(|chan| chan.is_usable)
1163 .collect::<Vec<_>>();
1164 let total_inbound_liquidity_balance_msat: u64 = channel_lists
1166 .iter()
1167 .map(|channel| channel.inbound_capacity_msat)
1168 .sum();
1169
1170 Ok(GetBalancesResponse {
1171 onchain_balance_sats: balances.total_onchain_balance_sats,
1172 spendable_onchain_balance_sats: balances.spendable_onchain_balance_sats,
1173 lightning_balance_msats: balances.total_lightning_balance_sats * 1000,
1174 inbound_lightning_liquidity_msats: total_inbound_liquidity_balance_msat,
1175 })
1176 }
1177
1178 async fn get_invoice(
1179 &self,
1180 get_invoice_request: GetInvoiceRequest,
1181 ) -> Result<Option<GetInvoiceResponse>, LightningRpcError> {
1182 let invoices = self
1183 .node
1184 .list_payments_with_filter(|details| {
1185 details.direction == PaymentDirection::Inbound
1186 && details.id == PaymentId(get_invoice_request.payment_hash.to_byte_array())
1187 && !matches!(details.kind, PaymentKind::Onchain { .. })
1188 })
1189 .iter()
1190 .map(|details| {
1191 let (preimage, payment_hash, _) = get_preimage_and_payment_hash(&details.kind);
1192 let status = match details.status {
1193 PaymentStatus::Failed => fedimint_gateway_common::PaymentStatus::Failed,
1194 PaymentStatus::Succeeded => fedimint_gateway_common::PaymentStatus::Succeeded,
1195 PaymentStatus::Pending => fedimint_gateway_common::PaymentStatus::Pending,
1196 };
1197 GetInvoiceResponse {
1198 preimage: preimage.map(|p| p.to_string()),
1199 payment_hash,
1200 amount: Amount::from_msats(
1201 details
1202 .amount_msat
1203 .expect("amountless invoices are not supported"),
1204 ),
1205 created_at: UNIX_EPOCH + Duration::from_secs(details.latest_update_timestamp),
1206 status,
1207 }
1208 })
1209 .collect::<Vec<_>>();
1210
1211 Ok(invoices.first().cloned())
1212 }
1213
1214 async fn list_transactions(
1215 &self,
1216 start_secs: u64,
1217 end_secs: u64,
1218 ) -> Result<ListTransactionsResponse, LightningRpcError> {
1219 let transactions = self
1220 .node
1221 .list_payments_with_filter(|details| {
1222 !matches!(details.kind, PaymentKind::Onchain { .. })
1223 && details.latest_update_timestamp >= start_secs
1224 && details.latest_update_timestamp < end_secs
1225 })
1226 .iter()
1227 .map(|details| {
1228 let (preimage, payment_hash, payment_kind) =
1229 get_preimage_and_payment_hash(&details.kind);
1230 let direction = match details.direction {
1231 PaymentDirection::Outbound => {
1232 fedimint_gateway_common::PaymentDirection::Outbound
1233 }
1234 PaymentDirection::Inbound => fedimint_gateway_common::PaymentDirection::Inbound,
1235 };
1236 let status = match details.status {
1237 PaymentStatus::Failed => fedimint_gateway_common::PaymentStatus::Failed,
1238 PaymentStatus::Succeeded => fedimint_gateway_common::PaymentStatus::Succeeded,
1239 PaymentStatus::Pending => fedimint_gateway_common::PaymentStatus::Pending,
1240 };
1241 fedimint_gateway_common::PaymentDetails {
1242 payment_hash,
1243 preimage: preimage.map(|p| p.to_string()),
1244 payment_kind,
1245 amount: Amount::from_msats(
1246 details
1247 .amount_msat
1248 .expect("amountless invoices are not supported"),
1249 ),
1250 direction,
1251 status,
1252 timestamp_secs: details.latest_update_timestamp,
1253 }
1254 })
1255 .collect::<Vec<_>>();
1256 Ok(ListTransactionsResponse { transactions })
1257 }
1258
1259 fn create_offer(
1260 &self,
1261 amount: Option<Amount>,
1262 description: Option<String>,
1263 expiry_secs: Option<u32>,
1264 quantity: Option<u64>,
1265 ) -> Result<String, LightningRpcError> {
1266 let description = description.unwrap_or_default();
1267 let offer = if let Some(amount) = amount {
1268 self.node
1269 .bolt12_payment()
1270 .receive(amount.msats, &description, expiry_secs, quantity)
1271 .map_err(|err| LightningRpcError::Bolt12Error {
1272 failure_reason: err.to_string(),
1273 })?
1274 } else {
1275 self.node
1276 .bolt12_payment()
1277 .receive_variable_amount(&description, expiry_secs)
1278 .map_err(|err| LightningRpcError::Bolt12Error {
1279 failure_reason: err.to_string(),
1280 })?
1281 };
1282
1283 Ok(offer.to_string())
1284 }
1285
1286 async fn pay_offer(
1287 &self,
1288 offer: String,
1289 quantity: Option<u64>,
1290 amount: Option<Amount>,
1291 payer_note: Option<String>,
1292 ) -> Result<Preimage, LightningRpcError> {
1293 let offer = Offer::from_str(&offer).map_err(|_| LightningRpcError::Bolt12Error {
1294 failure_reason: "Failed to parse Bolt12 Offer".to_string(),
1295 })?;
1296
1297 let _offer_lock_guard = self
1298 .outbound_offer_lock_pool
1299 .blocking_lock(LdkOfferId(offer.id()));
1300
1301 let payment_id = if let Some(amount) = amount {
1302 self.node
1303 .bolt12_payment()
1304 .send_using_amount(&offer, amount.msats, quantity, payer_note, None)
1305 .map_err(|err| LightningRpcError::Bolt12Error {
1306 failure_reason: err.to_string(),
1307 })?
1308 } else {
1309 self.node
1310 .bolt12_payment()
1311 .send(&offer, quantity, payer_note, None)
1312 .map_err(|err| LightningRpcError::Bolt12Error {
1313 failure_reason: err.to_string(),
1314 })?
1315 };
1316
1317 loop {
1318 if let Some(payment_details) = self.node.payment(&payment_id) {
1319 match payment_details.status {
1320 PaymentStatus::Pending => {}
1321 PaymentStatus::Succeeded => match payment_details.kind {
1322 PaymentKind::Bolt12Offer {
1323 preimage: Some(preimage),
1324 ..
1325 } => {
1326 info!(target: LOG_LIGHTNING, offer = %offer, payment_id = %payment_id, preimage = %preimage, "Successfully paid offer");
1327 return Ok(Preimage(preimage.0));
1328 }
1329 _ => {
1330 return Err(LightningRpcError::FailedPayment {
1331 failure_reason: "Unexpected payment kind".to_string(),
1332 });
1333 }
1334 },
1335 PaymentStatus::Failed => {
1336 return Err(LightningRpcError::FailedPayment {
1337 failure_reason: "Bolt12 payment failed".to_string(),
1338 });
1339 }
1340 }
1341 }
1342 fedimint_core::runtime::sleep(Duration::from_millis(100)).await;
1343 }
1344 }
1345
1346 fn sync_wallet(&self) -> Result<(), LightningRpcError> {
1347 block_in_place(|| {
1348 let _ = self.node.sync_wallets();
1349 });
1350 Ok(())
1351 }
1352}
1353
1354fn get_preimage_and_payment_hash(
1357 kind: &PaymentKind,
1358) -> (
1359 Option<Preimage>,
1360 Option<sha256::Hash>,
1361 fedimint_gateway_common::PaymentKind,
1362) {
1363 match kind {
1364 PaymentKind::Bolt11 {
1365 hash,
1366 preimage,
1367 secret: _,
1368 } => (
1369 preimage.map(|p| Preimage(p.0)),
1370 Some(sha256::Hash::from_slice(&hash.0).expect("Failed to convert payment hash")),
1371 fedimint_gateway_common::PaymentKind::Bolt11,
1372 ),
1373 PaymentKind::Bolt11Jit {
1374 hash,
1375 preimage,
1376 secret: _,
1377 lsp_fee_limits: _,
1378 ..
1379 } => (
1380 preimage.map(|p| Preimage(p.0)),
1381 Some(sha256::Hash::from_slice(&hash.0).expect("Failed to convert payment hash")),
1382 fedimint_gateway_common::PaymentKind::Bolt11,
1383 ),
1384 PaymentKind::Bolt12Offer {
1385 hash,
1386 preimage,
1387 secret: _,
1388 offer_id: _,
1389 payer_note: _,
1390 quantity: _,
1391 } => (
1392 preimage.map(|p| Preimage(p.0)),
1393 hash.map(|h| sha256::Hash::from_slice(&h.0).expect("Failed to convert payment hash")),
1394 fedimint_gateway_common::PaymentKind::Bolt12Offer,
1395 ),
1396 PaymentKind::Bolt12Refund {
1397 hash,
1398 preimage,
1399 secret: _,
1400 payer_note: _,
1401 quantity: _,
1402 } => (
1403 preimage.map(|p| Preimage(p.0)),
1404 hash.map(|h| sha256::Hash::from_slice(&h.0).expect("Failed to convert payment hash")),
1405 fedimint_gateway_common::PaymentKind::Bolt12Refund,
1406 ),
1407 PaymentKind::Spontaneous { hash, preimage } => (
1408 preimage.map(|p| Preimage(p.0)),
1409 Some(sha256::Hash::from_slice(&hash.0).expect("Failed to convert payment hash")),
1410 fedimint_gateway_common::PaymentKind::Bolt11,
1411 ),
1412 PaymentKind::Onchain { .. } => (None, None, fedimint_gateway_common::PaymentKind::Onchain),
1413 }
1414}
1415
1416fn get_esplora_url(server_url: SafeUrl) -> Result<String, LdkClientInitError> {
1424 let host = server_url
1426 .host_str()
1427 .ok_or(LdkClientInitError::MissingEsploraHost)?;
1428 let server_url = if let Some(port) = server_url.port() {
1429 format!("{}://{}:{}", server_url.scheme(), host, port)
1430 } else {
1431 server_url.to_string()
1432 };
1433 Ok(server_url)
1434}
1435
1436#[derive(Debug, Clone, Copy, Eq, PartialEq)]
1438enum PendingPaymentWakeup {
1439 NoWaiter,
1441 Woken,
1443 ReceiverDropped,
1445}
1446
1447#[derive(Debug, Clone, Copy, Eq, PartialEq)]
1448struct LdkOfferId(OfferId);
1449
1450impl std::hash::Hash for LdkOfferId {
1451 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1452 state.write(&self.0.0);
1453 }
1454}
1455
1456#[derive(Debug, Copy, Clone, PartialEq, Eq)]
1457pub struct UserChannelId(pub ldk_node::UserChannelId);
1458
1459impl PartialOrd for UserChannelId {
1460 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1461 Some(self.cmp(other))
1462 }
1463}
1464
1465impl Ord for UserChannelId {
1466 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1467 self.0.0.cmp(&other.0.0)
1468 }
1469}
1470
1471fn channel_push_amount_msats(push_amount_sats: u64) -> Result<Option<u64>, LightningRpcError> {
1472 if push_amount_sats == 0 {
1473 return Ok(None);
1474 }
1475
1476 push_amount_sats.checked_mul(1000).map(Some).ok_or_else(|| {
1477 LightningRpcError::FailedToOpenChannel {
1478 failure_reason: format!(
1479 "push_amount_sats {push_amount_sats} overflows u64 millisatoshis (LDK limit)"
1480 ),
1481 }
1482 })
1483}
1484
1485#[cfg(test)]
1486mod tests;