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