lib.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. unit: unit.clone(),
  162. fee: fee.into(),
  163. state: MeltQuoteState::Unpaid,
  164. })
  165. }
  166. async fn make_payment(
  167. &self,
  168. melt_quote: mint::MeltQuote,
  169. _partial_msats: Option<Amount>,
  170. _max_fee_msats: Option<Amount>,
  171. ) -> Result<MakePaymentResponse, Self::Err> {
  172. let pay_response = self
  173. .lnbits_api
  174. .pay_invoice(&melt_quote.request, None)
  175. .await
  176. .map_err(|err| {
  177. tracing::error!("Could not pay invoice");
  178. tracing::error!("{}", err.to_string());
  179. Self::Err::Anyhow(anyhow!("Could not pay invoice"))
  180. })?;
  181. let invoice_info = self
  182. .lnbits_api
  183. .get_payment_info(&pay_response.payment_hash)
  184. .await
  185. .map_err(|err| {
  186. tracing::error!("Could not find invoice");
  187. tracing::error!("{}", err.to_string());
  188. Self::Err::Anyhow(anyhow!("Could not find invoice"))
  189. })?;
  190. let status = match invoice_info.paid {
  191. true => MeltQuoteState::Paid,
  192. false => MeltQuoteState::Unpaid,
  193. };
  194. let total_spent = Amount::from(
  195. (invoice_info
  196. .details
  197. .amount
  198. .checked_add(invoice_info.details.fee)
  199. .ok_or(Error::AmountOverflow)?)
  200. .unsigned_abs(),
  201. );
  202. Ok(MakePaymentResponse {
  203. payment_lookup_id: pay_response.payment_hash,
  204. payment_proof: invoice_info.details.preimage,
  205. status,
  206. total_spent,
  207. unit: CurrencyUnit::Sat,
  208. })
  209. }
  210. async fn create_incoming_payment_request(
  211. &self,
  212. amount: Amount,
  213. unit: &CurrencyUnit,
  214. description: String,
  215. unix_expiry: Option<u64>,
  216. ) -> Result<CreateIncomingPaymentResponse, Self::Err> {
  217. if unit != &CurrencyUnit::Sat {
  218. return Err(Self::Err::Anyhow(anyhow!("Unsupported unit")));
  219. }
  220. let time_now = unix_time();
  221. let expiry = unix_expiry.map(|t| t - time_now);
  222. let invoice_request = CreateInvoiceRequest {
  223. amount: to_unit(amount, unit, &CurrencyUnit::Sat)?.into(),
  224. memo: Some(description),
  225. unit: unit.to_string(),
  226. expiry,
  227. webhook: self.webhook_url.clone(),
  228. internal: None,
  229. out: false,
  230. };
  231. let create_invoice_response = self
  232. .lnbits_api
  233. .create_invoice(&invoice_request)
  234. .await
  235. .map_err(|err| {
  236. tracing::error!("Could not create invoice");
  237. tracing::error!("{}", err.to_string());
  238. Self::Err::Anyhow(anyhow!("Could not create invoice"))
  239. })?;
  240. let request: Bolt11Invoice = create_invoice_response
  241. .bolt11()
  242. .ok_or_else(|| Self::Err::Anyhow(anyhow!("Missing bolt11 invoice")))?
  243. .parse()?;
  244. let expiry = request.expires_at().map(|t| t.as_secs());
  245. Ok(CreateIncomingPaymentResponse {
  246. request_lookup_id: create_invoice_response.payment_hash().to_string(),
  247. request: request.to_string(),
  248. expiry,
  249. })
  250. }
  251. async fn check_incoming_payment_status(
  252. &self,
  253. payment_hash: &str,
  254. ) -> Result<MintQuoteState, Self::Err> {
  255. let paid = self
  256. .lnbits_api
  257. .is_invoice_paid(payment_hash)
  258. .await
  259. .map_err(|err| {
  260. tracing::error!("Could not check invoice status");
  261. tracing::error!("{}", err.to_string());
  262. Self::Err::Anyhow(anyhow!("Could not check invoice status"))
  263. })?;
  264. let state = match paid {
  265. true => MintQuoteState::Paid,
  266. false => MintQuoteState::Unpaid,
  267. };
  268. Ok(state)
  269. }
  270. async fn check_outgoing_payment(
  271. &self,
  272. payment_hash: &str,
  273. ) -> Result<MakePaymentResponse, Self::Err> {
  274. let payment = self
  275. .lnbits_api
  276. .get_payment_info(payment_hash)
  277. .await
  278. .map_err(|err| {
  279. tracing::error!("Could not check invoice status");
  280. tracing::error!("{}", err.to_string());
  281. Self::Err::Anyhow(anyhow!("Could not check invoice status"))
  282. })?;
  283. let pay_response = MakePaymentResponse {
  284. payment_lookup_id: payment.details.payment_hash,
  285. payment_proof: payment.preimage,
  286. status: lnbits_to_melt_status(&payment.details.status, payment.details.pending),
  287. total_spent: Amount::from(
  288. payment.details.amount.unsigned_abs()
  289. + payment.details.fee.unsigned_abs() / MSAT_IN_SAT,
  290. ),
  291. unit: self.settings.unit.clone(),
  292. };
  293. Ok(pay_response)
  294. }
  295. }
  296. fn lnbits_to_melt_status(status: &str, pending: Option<bool>) -> MeltQuoteState {
  297. if pending.unwrap_or_default() {
  298. return MeltQuoteState::Pending;
  299. }
  300. match status {
  301. "success" => MeltQuoteState::Paid,
  302. "failed" => MeltQuoteState::Unpaid,
  303. "pending" => MeltQuoteState::Pending,
  304. _ => MeltQuoteState::Unknown,
  305. }
  306. }
  307. impl LNbits {
  308. /// Create invoice webhook
  309. pub async fn create_invoice_webhook_router(
  310. &self,
  311. webhook_endpoint: &str,
  312. ) -> anyhow::Result<Router> {
  313. self.lnbits_api
  314. .create_invoice_webhook_router(webhook_endpoint)
  315. .await
  316. }
  317. }