lib.rs 11 KB

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