lib.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. //! CDK lightning backend for LND
  2. // Copyright (c) 2023 Steffen (MIT)
  3. #![warn(missing_docs)]
  4. #![warn(rustdoc::bare_urls)]
  5. use std::path::PathBuf;
  6. use std::pin::Pin;
  7. use std::str::FromStr;
  8. use std::sync::atomic::{AtomicBool, Ordering};
  9. use std::sync::Arc;
  10. use anyhow::anyhow;
  11. use async_trait::async_trait;
  12. use cdk::amount::{to_unit, Amount, MSAT_IN_SAT};
  13. use cdk::cdk_lightning::{
  14. self, CreateInvoiceResponse, MintLightning, PayInvoiceResponse, PaymentQuoteResponse, Settings,
  15. };
  16. use cdk::mint::FeeReserve;
  17. use cdk::nuts::{CurrencyUnit, MeltQuoteBolt11Request, MeltQuoteState, MintQuoteState};
  18. use cdk::util::{hex, unix_time};
  19. use cdk::{mint, Bolt11Invoice};
  20. use error::Error;
  21. use fedimint_tonic_lnd::lnrpc::fee_limit::Limit;
  22. use fedimint_tonic_lnd::lnrpc::payment::PaymentStatus;
  23. use fedimint_tonic_lnd::lnrpc::FeeLimit;
  24. use fedimint_tonic_lnd::Client;
  25. use futures::{Stream, StreamExt};
  26. use tokio::sync::Mutex;
  27. use tokio_util::sync::CancellationToken;
  28. pub mod error;
  29. /// Lnd mint backend
  30. #[derive(Clone)]
  31. pub struct Lnd {
  32. address: String,
  33. cert_file: PathBuf,
  34. macaroon_file: PathBuf,
  35. client: Arc<Mutex<Client>>,
  36. fee_reserve: FeeReserve,
  37. wait_invoice_cancel_token: CancellationToken,
  38. wait_invoice_is_active: Arc<AtomicBool>,
  39. }
  40. impl Lnd {
  41. /// Create new [`Lnd`]
  42. pub async fn new(
  43. address: String,
  44. cert_file: PathBuf,
  45. macaroon_file: PathBuf,
  46. fee_reserve: FeeReserve,
  47. ) -> Result<Self, Error> {
  48. let client = fedimint_tonic_lnd::connect(address.to_string(), &cert_file, &macaroon_file)
  49. .await
  50. .map_err(|err| {
  51. tracing::error!("Connection error: {}", err.to_string());
  52. Error::Connection
  53. })?;
  54. Ok(Self {
  55. address,
  56. cert_file,
  57. macaroon_file,
  58. client: Arc::new(Mutex::new(client)),
  59. fee_reserve,
  60. wait_invoice_cancel_token: CancellationToken::new(),
  61. wait_invoice_is_active: Arc::new(AtomicBool::new(false)),
  62. })
  63. }
  64. }
  65. #[async_trait]
  66. impl MintLightning for Lnd {
  67. type Err = cdk_lightning::Error;
  68. fn get_settings(&self) -> Settings {
  69. Settings {
  70. mpp: false,
  71. unit: CurrencyUnit::Msat,
  72. invoice_description: true,
  73. }
  74. }
  75. fn is_wait_invoice_active(&self) -> bool {
  76. self.wait_invoice_is_active.load(Ordering::SeqCst)
  77. }
  78. fn cancel_wait_invoice(&self) {
  79. self.wait_invoice_cancel_token.cancel()
  80. }
  81. async fn wait_any_invoice(
  82. &self,
  83. ) -> Result<Pin<Box<dyn Stream<Item = String> + Send>>, Self::Err> {
  84. let mut client =
  85. fedimint_tonic_lnd::connect(self.address.clone(), &self.cert_file, &self.macaroon_file)
  86. .await
  87. .map_err(|_| Error::Connection)?;
  88. let stream_req = fedimint_tonic_lnd::lnrpc::InvoiceSubscription {
  89. add_index: 0,
  90. settle_index: 0,
  91. };
  92. let stream = client
  93. .lightning()
  94. .subscribe_invoices(stream_req)
  95. .await
  96. .map_err(|_err| {
  97. tracing::error!("Could not subscribe to invoice");
  98. Error::Connection
  99. })?
  100. .into_inner();
  101. let cancel_token = self.wait_invoice_cancel_token.clone();
  102. Ok(futures::stream::unfold(
  103. (
  104. stream,
  105. cancel_token,
  106. Arc::clone(&self.wait_invoice_is_active),
  107. ),
  108. |(mut stream, cancel_token, is_active)| async move {
  109. is_active.store(true, Ordering::SeqCst);
  110. tokio::select! {
  111. _ = cancel_token.cancelled() => {
  112. // Stream is cancelled
  113. is_active.store(false, Ordering::SeqCst);
  114. tracing::info!("Waiting for lnd invoice ending");
  115. None
  116. }
  117. msg = stream.message() => {
  118. match msg {
  119. Ok(Some(msg)) => {
  120. if msg.state == 1 {
  121. Some((hex::encode(msg.r_hash), (stream, cancel_token, is_active)))
  122. } else {
  123. None
  124. }
  125. }
  126. Ok(None) => {
  127. is_active.store(false, Ordering::SeqCst);
  128. tracing::info!("LND invoice stream ended.");
  129. None
  130. }, // End of stream
  131. Err(err) => {
  132. is_active.store(false, Ordering::SeqCst);
  133. tracing::warn!("Encounrdered error in LND invoice stream. Stream ending");
  134. tracing::error!("{:?}", err);
  135. None
  136. }, // Handle errors gracefully, ends the stream on error
  137. }
  138. }
  139. }
  140. },
  141. )
  142. .boxed())
  143. }
  144. async fn get_payment_quote(
  145. &self,
  146. melt_quote_request: &MeltQuoteBolt11Request,
  147. ) -> Result<PaymentQuoteResponse, Self::Err> {
  148. let amount = melt_quote_request.amount_msat()?;
  149. let amount = amount / MSAT_IN_SAT.into();
  150. let relative_fee_reserve =
  151. (self.fee_reserve.percent_fee_reserve * u64::from(amount) as f32) as u64;
  152. let absolute_fee_reserve: u64 = self.fee_reserve.min_fee_reserve.into();
  153. let fee = match relative_fee_reserve > absolute_fee_reserve {
  154. true => relative_fee_reserve,
  155. false => absolute_fee_reserve,
  156. };
  157. Ok(PaymentQuoteResponse {
  158. request_lookup_id: melt_quote_request.request.payment_hash().to_string(),
  159. amount,
  160. fee: fee.into(),
  161. state: MeltQuoteState::Unpaid,
  162. })
  163. }
  164. async fn pay_invoice(
  165. &self,
  166. melt_quote: mint::MeltQuote,
  167. _partial_amount: Option<Amount>,
  168. max_fee: Option<Amount>,
  169. ) -> Result<PayInvoiceResponse, Self::Err> {
  170. let payment_request = melt_quote.request;
  171. let amount_msat: u64 = match melt_quote.msat_to_pay {
  172. Some(amount_msat) => amount_msat.into(),
  173. None => {
  174. let bolt11 = Bolt11Invoice::from_str(&payment_request)?;
  175. bolt11
  176. .amount_milli_satoshis()
  177. .ok_or(Error::UnknownInvoiceAmount)?
  178. }
  179. };
  180. let pay_req = fedimint_tonic_lnd::lnrpc::SendRequest {
  181. payment_request,
  182. fee_limit: max_fee.map(|f| {
  183. let limit = Limit::Fixed(u64::from(f) as i64);
  184. FeeLimit { limit: Some(limit) }
  185. }),
  186. amt_msat: amount_msat as i64,
  187. ..Default::default()
  188. };
  189. let payment_response = self
  190. .client
  191. .lock()
  192. .await
  193. .lightning()
  194. .send_payment_sync(fedimint_tonic_lnd::tonic::Request::new(pay_req))
  195. .await
  196. .map_err(|_| Error::PaymentFailed)?
  197. .into_inner();
  198. let total_amount = payment_response
  199. .payment_route
  200. .map_or(0, |route| route.total_amt_msat / MSAT_IN_SAT as i64)
  201. as u64;
  202. let (status, payment_preimage) = match total_amount == 0 {
  203. true => (MeltQuoteState::Unpaid, None),
  204. false => (
  205. MeltQuoteState::Paid,
  206. Some(hex::encode(payment_response.payment_preimage)),
  207. ),
  208. };
  209. Ok(PayInvoiceResponse {
  210. payment_lookup_id: hex::encode(payment_response.payment_hash),
  211. payment_preimage,
  212. status,
  213. total_spent: total_amount.into(),
  214. unit: CurrencyUnit::Sat,
  215. })
  216. }
  217. async fn create_invoice(
  218. &self,
  219. amount: Amount,
  220. unit: &CurrencyUnit,
  221. description: String,
  222. unix_expiry: u64,
  223. ) -> Result<CreateInvoiceResponse, Self::Err> {
  224. let time_now = unix_time();
  225. assert!(unix_expiry > time_now);
  226. let amount = to_unit(amount, unit, &CurrencyUnit::Msat)?;
  227. let invoice_request = fedimint_tonic_lnd::lnrpc::Invoice {
  228. value_msat: u64::from(amount) as i64,
  229. memo: description,
  230. ..Default::default()
  231. };
  232. let invoice = self
  233. .client
  234. .lock()
  235. .await
  236. .lightning()
  237. .add_invoice(fedimint_tonic_lnd::tonic::Request::new(invoice_request))
  238. .await
  239. .unwrap()
  240. .into_inner();
  241. let bolt11 = Bolt11Invoice::from_str(&invoice.payment_request)?;
  242. Ok(CreateInvoiceResponse {
  243. request_lookup_id: bolt11.payment_hash().to_string(),
  244. request: bolt11,
  245. expiry: Some(unix_expiry),
  246. })
  247. }
  248. async fn check_incoming_invoice_status(
  249. &self,
  250. request_lookup_id: &str,
  251. ) -> Result<MintQuoteState, Self::Err> {
  252. let invoice_request = fedimint_tonic_lnd::lnrpc::PaymentHash {
  253. r_hash: hex::decode(request_lookup_id).unwrap(),
  254. ..Default::default()
  255. };
  256. let invoice = self
  257. .client
  258. .lock()
  259. .await
  260. .lightning()
  261. .lookup_invoice(fedimint_tonic_lnd::tonic::Request::new(invoice_request))
  262. .await
  263. .unwrap()
  264. .into_inner();
  265. match invoice.state {
  266. // Open
  267. 0 => Ok(MintQuoteState::Unpaid),
  268. // Settled
  269. 1 => Ok(MintQuoteState::Paid),
  270. // Canceled
  271. 2 => Ok(MintQuoteState::Unpaid),
  272. // Accepted
  273. 3 => Ok(MintQuoteState::Unpaid),
  274. _ => Err(Self::Err::Anyhow(anyhow!("Invalid status"))),
  275. }
  276. }
  277. async fn check_outgoing_payment(
  278. &self,
  279. payment_hash: &str,
  280. ) -> Result<PayInvoiceResponse, Self::Err> {
  281. let track_request = fedimint_tonic_lnd::routerrpc::TrackPaymentRequest {
  282. payment_hash: hex::decode(payment_hash).map_err(|_| Error::InvalidHash)?,
  283. no_inflight_updates: true,
  284. };
  285. let mut payment_stream = self
  286. .client
  287. .lock()
  288. .await
  289. .router()
  290. .track_payment_v2(track_request)
  291. .await
  292. .unwrap()
  293. .into_inner();
  294. while let Some(update_result) = payment_stream.next().await {
  295. match update_result {
  296. Ok(update) => {
  297. let status = update.status();
  298. let response = match status {
  299. PaymentStatus::Unknown => PayInvoiceResponse {
  300. payment_lookup_id: payment_hash.to_string(),
  301. payment_preimage: Some(update.payment_preimage),
  302. status: MeltQuoteState::Unknown,
  303. total_spent: Amount::ZERO,
  304. unit: self.get_settings().unit,
  305. },
  306. PaymentStatus::InFlight => {
  307. // Continue waiting for the next update
  308. continue;
  309. }
  310. PaymentStatus::Succeeded => PayInvoiceResponse {
  311. payment_lookup_id: payment_hash.to_string(),
  312. payment_preimage: Some(update.payment_preimage),
  313. status: MeltQuoteState::Paid,
  314. total_spent: Amount::from((update.value_sat + update.fee_sat) as u64),
  315. unit: CurrencyUnit::Sat,
  316. },
  317. PaymentStatus::Failed => PayInvoiceResponse {
  318. payment_lookup_id: payment_hash.to_string(),
  319. payment_preimage: Some(update.payment_preimage),
  320. status: MeltQuoteState::Failed,
  321. total_spent: Amount::ZERO,
  322. unit: self.get_settings().unit,
  323. },
  324. };
  325. return Ok(response);
  326. }
  327. Err(_) => {
  328. // Handle the case where the update itself is an error (e.g., stream failure)
  329. return Err(Error::UnknownPaymentStatus.into());
  330. }
  331. }
  332. }
  333. // If the stream is exhausted without a final status
  334. Err(Error::UnknownPaymentStatus.into())
  335. }
  336. }