lib.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. //! CDK lightning backend for lnbits
  2. #![doc = include_str!("../README.md")]
  3. #![warn(missing_docs)]
  4. #![warn(rustdoc::bare_urls)]
  5. use std::cmp::max;
  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 axum::Router;
  13. use cdk_common::amount::{to_unit, Amount, MSAT_IN_SAT};
  14. use cdk_common::common::FeeReserve;
  15. use cdk_common::nuts::{CurrencyUnit, MeltOptions, MeltQuoteState, MintQuoteState};
  16. use cdk_common::payment::{
  17. self, Bolt11Settings, CreateIncomingPaymentResponse, MakePaymentResponse, MintPayment,
  18. PaymentQuoteResponse,
  19. };
  20. use cdk_common::util::unix_time;
  21. use cdk_common::{mint, Bolt11Invoice};
  22. use error::Error;
  23. use futures::Stream;
  24. use lnbits_rs::api::invoice::CreateInvoiceRequest;
  25. use lnbits_rs::LNBitsClient;
  26. use serde_json::Value;
  27. use tokio_util::sync::CancellationToken;
  28. pub mod error;
  29. /// LNbits
  30. #[derive(Clone)]
  31. pub struct LNbits {
  32. lnbits_api: LNBitsClient,
  33. fee_reserve: FeeReserve,
  34. webhook_url: Option<String>,
  35. wait_invoice_cancel_token: CancellationToken,
  36. wait_invoice_is_active: Arc<AtomicBool>,
  37. settings: Bolt11Settings,
  38. }
  39. impl LNbits {
  40. /// Create new [`LNbits`] wallet
  41. #[allow(clippy::too_many_arguments)]
  42. pub async fn new(
  43. admin_api_key: String,
  44. invoice_api_key: String,
  45. api_url: String,
  46. fee_reserve: FeeReserve,
  47. webhook_url: Option<String>,
  48. ) -> Result<Self, Error> {
  49. let lnbits_api = LNBitsClient::new("", &admin_api_key, &invoice_api_key, &api_url, None)?;
  50. Ok(Self {
  51. lnbits_api,
  52. fee_reserve,
  53. webhook_url,
  54. wait_invoice_cancel_token: CancellationToken::new(),
  55. wait_invoice_is_active: Arc::new(AtomicBool::new(false)),
  56. settings: Bolt11Settings {
  57. mpp: false,
  58. unit: CurrencyUnit::Sat,
  59. invoice_description: true,
  60. amountless: false,
  61. },
  62. })
  63. }
  64. /// Subscribe to lnbits ws
  65. pub async fn subscribe_ws(&self) -> Result<(), Error> {
  66. self.lnbits_api
  67. .subscribe_to_websocket()
  68. .await
  69. .map_err(|err| {
  70. tracing::error!("Could not subscribe to lnbits ws");
  71. Error::Anyhow(err)
  72. })
  73. }
  74. }
  75. #[async_trait]
  76. impl MintPayment for LNbits {
  77. type Err = payment::Error;
  78. async fn get_settings(&self) -> Result<Value, Self::Err> {
  79. Ok(serde_json::to_value(&self.settings)?)
  80. }
  81. fn is_wait_invoice_active(&self) -> bool {
  82. self.wait_invoice_is_active.load(Ordering::SeqCst)
  83. }
  84. fn cancel_wait_invoice(&self) {
  85. self.wait_invoice_cancel_token.cancel()
  86. }
  87. async fn wait_any_incoming_payment(
  88. &self,
  89. ) -> Result<Pin<Box<dyn Stream<Item = String> + Send>>, Self::Err> {
  90. let api = self.lnbits_api.clone();
  91. let cancel_token = self.wait_invoice_cancel_token.clone();
  92. let is_active = Arc::clone(&self.wait_invoice_is_active);
  93. Ok(Box::pin(futures::stream::unfold(
  94. (api, cancel_token, is_active),
  95. |(api, cancel_token, is_active)| async move {
  96. is_active.store(true, Ordering::SeqCst);
  97. let receiver = api.receiver();
  98. let mut receiver = receiver.lock().await;
  99. tokio::select! {
  100. _ = cancel_token.cancelled() => {
  101. // Stream is cancelled
  102. is_active.store(false, Ordering::SeqCst);
  103. tracing::info!("Waiting for lnbits invoice ending");
  104. None
  105. }
  106. msg_option = receiver.recv() => {
  107. match msg_option {
  108. Some(msg) => {
  109. let check = api.is_invoice_paid(&msg).await;
  110. match check {
  111. Ok(state) => {
  112. if state {
  113. Some((msg, (api, cancel_token, is_active)))
  114. } else {
  115. Some(("".to_string(), (api, cancel_token, is_active)))
  116. }
  117. }
  118. _ => Some(("".to_string(), (api, cancel_token, is_active))),
  119. }
  120. }
  121. None => {
  122. is_active.store(false, Ordering::SeqCst);
  123. None
  124. },
  125. }
  126. }
  127. }
  128. },
  129. )))
  130. }
  131. async fn get_payment_quote(
  132. &self,
  133. request: &str,
  134. unit: &CurrencyUnit,
  135. options: Option<MeltOptions>,
  136. ) -> Result<PaymentQuoteResponse, Self::Err> {
  137. if unit != &CurrencyUnit::Sat {
  138. return Err(Self::Err::Anyhow(anyhow!("Unsupported unit")));
  139. }
  140. let bolt11 = Bolt11Invoice::from_str(request)?;
  141. let amount_msat = match options {
  142. Some(amount) => {
  143. if matches!(amount, MeltOptions::Mpp { mpp: _ }) {
  144. return Err(payment::Error::UnsupportedPaymentOption);
  145. }
  146. amount.amount_msat()
  147. }
  148. None => bolt11
  149. .amount_milli_satoshis()
  150. .ok_or(Error::UnknownInvoiceAmount)?
  151. .into(),
  152. };
  153. let amount = amount_msat / MSAT_IN_SAT.into();
  154. let relative_fee_reserve =
  155. (self.fee_reserve.percent_fee_reserve * u64::from(amount) as f32) as u64;
  156. let absolute_fee_reserve: u64 = self.fee_reserve.min_fee_reserve.into();
  157. let fee = max(relative_fee_reserve, absolute_fee_reserve);
  158. Ok(PaymentQuoteResponse {
  159. request_lookup_id: bolt11.payment_hash().to_string(),
  160. amount,
  161. fee: fee.into(),
  162. state: MeltQuoteState::Unpaid,
  163. })
  164. }
  165. async fn make_payment(
  166. &self,
  167. melt_quote: mint::MeltQuote,
  168. _partial_msats: Option<Amount>,
  169. _max_fee_msats: Option<Amount>,
  170. ) -> Result<MakePaymentResponse, Self::Err> {
  171. let pay_response = self
  172. .lnbits_api
  173. .pay_invoice(&melt_quote.request, None)
  174. .await
  175. .map_err(|err| {
  176. tracing::error!("Could not pay invoice");
  177. tracing::error!("{}", err.to_string());
  178. Self::Err::Anyhow(anyhow!("Could not pay invoice"))
  179. })?;
  180. let invoice_info = self
  181. .lnbits_api
  182. .get_payment_info(&pay_response.payment_hash)
  183. .await
  184. .map_err(|err| {
  185. tracing::error!("Could not find invoice");
  186. tracing::error!("{}", err.to_string());
  187. Self::Err::Anyhow(anyhow!("Could not find invoice"))
  188. })?;
  189. let status = match invoice_info.paid {
  190. true => MeltQuoteState::Paid,
  191. false => MeltQuoteState::Unpaid,
  192. };
  193. let total_spent = Amount::from(
  194. (invoice_info
  195. .details
  196. .amount
  197. .checked_add(invoice_info.details.fee)
  198. .ok_or(Error::AmountOverflow)?)
  199. .unsigned_abs(),
  200. );
  201. Ok(MakePaymentResponse {
  202. payment_lookup_id: pay_response.payment_hash,
  203. payment_proof: invoice_info.details.preimage,
  204. status,
  205. total_spent,
  206. unit: CurrencyUnit::Sat,
  207. })
  208. }
  209. async fn create_incoming_payment_request(
  210. &self,
  211. amount: Amount,
  212. unit: &CurrencyUnit,
  213. description: String,
  214. unix_expiry: Option<u64>,
  215. ) -> Result<CreateIncomingPaymentResponse, Self::Err> {
  216. if unit != &CurrencyUnit::Sat {
  217. return Err(Self::Err::Anyhow(anyhow!("Unsupported unit")));
  218. }
  219. let time_now = unix_time();
  220. let expiry = unix_expiry.map(|t| t - time_now);
  221. let invoice_request = CreateInvoiceRequest {
  222. amount: to_unit(amount, unit, &CurrencyUnit::Sat)?.into(),
  223. memo: Some(description),
  224. unit: unit.to_string(),
  225. expiry,
  226. webhook: self.webhook_url.clone(),
  227. internal: None,
  228. out: false,
  229. };
  230. let create_invoice_response = self
  231. .lnbits_api
  232. .create_invoice(&invoice_request)
  233. .await
  234. .map_err(|err| {
  235. tracing::error!("Could not create invoice");
  236. tracing::error!("{}", err.to_string());
  237. Self::Err::Anyhow(anyhow!("Could not create invoice"))
  238. })?;
  239. let request: Bolt11Invoice = create_invoice_response
  240. .bolt11()
  241. .ok_or_else(|| Self::Err::Anyhow(anyhow!("Missing bolt11 invoice")))?
  242. .parse()?;
  243. let expiry = request.expires_at().map(|t| t.as_secs());
  244. Ok(CreateIncomingPaymentResponse {
  245. request_lookup_id: create_invoice_response.payment_hash().to_string(),
  246. request: request.to_string(),
  247. expiry,
  248. })
  249. }
  250. async fn check_incoming_payment_status(
  251. &self,
  252. payment_hash: &str,
  253. ) -> Result<MintQuoteState, Self::Err> {
  254. let paid = self
  255. .lnbits_api
  256. .is_invoice_paid(payment_hash)
  257. .await
  258. .map_err(|err| {
  259. tracing::error!("Could not check invoice status");
  260. tracing::error!("{}", err.to_string());
  261. Self::Err::Anyhow(anyhow!("Could not check invoice status"))
  262. })?;
  263. let state = match paid {
  264. true => MintQuoteState::Paid,
  265. false => MintQuoteState::Unpaid,
  266. };
  267. Ok(state)
  268. }
  269. async fn check_outgoing_payment(
  270. &self,
  271. payment_hash: &str,
  272. ) -> Result<MakePaymentResponse, Self::Err> {
  273. let payment = self
  274. .lnbits_api
  275. .get_payment_info(payment_hash)
  276. .await
  277. .map_err(|err| {
  278. tracing::error!("Could not check invoice status");
  279. tracing::error!("{}", err.to_string());
  280. Self::Err::Anyhow(anyhow!("Could not check invoice status"))
  281. })?;
  282. let pay_response = MakePaymentResponse {
  283. payment_lookup_id: payment.details.payment_hash,
  284. payment_proof: payment.preimage,
  285. status: lnbits_to_melt_status(&payment.details.status, payment.details.pending),
  286. total_spent: Amount::from(
  287. payment.details.amount.unsigned_abs()
  288. + payment.details.fee.unsigned_abs() / MSAT_IN_SAT,
  289. ),
  290. unit: self.settings.unit.clone(),
  291. };
  292. Ok(pay_response)
  293. }
  294. }
  295. fn lnbits_to_melt_status(status: &str, pending: Option<bool>) -> MeltQuoteState {
  296. if pending.unwrap_or_default() {
  297. return MeltQuoteState::Pending;
  298. }
  299. match status {
  300. "success" => MeltQuoteState::Paid,
  301. "failed" => MeltQuoteState::Unpaid,
  302. "pending" => MeltQuoteState::Pending,
  303. _ => MeltQuoteState::Unknown,
  304. }
  305. }
  306. impl LNbits {
  307. /// Create invoice webhook
  308. pub async fn create_invoice_webhook_router(
  309. &self,
  310. webhook_endpoint: &str,
  311. ) -> anyhow::Result<Router> {
  312. self.lnbits_api
  313. .create_invoice_webhook_router(webhook_endpoint)
  314. .await
  315. }
  316. }