lib.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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::sync::atomic::{AtomicBool, Ordering};
  8. use std::sync::Arc;
  9. use anyhow::anyhow;
  10. use async_trait::async_trait;
  11. use cdk_common::amount::{to_unit, Amount};
  12. use cdk_common::common::FeeReserve;
  13. use cdk_common::nuts::{CurrencyUnit, MeltOptions, MeltQuoteState};
  14. use cdk_common::payment::{
  15. self, Bolt11Settings, CreateIncomingPaymentResponse, Event, IncomingPaymentOptions,
  16. MakePaymentResponse, MintPayment, OutgoingPaymentOptions, PaymentIdentifier,
  17. PaymentQuoteResponse, WaitPaymentResponse,
  18. };
  19. use cdk_common::util::{hex, unix_time};
  20. use cdk_common::Bolt11Invoice;
  21. use error::Error;
  22. use futures::Stream;
  23. use lnbits_rs::api::invoice::CreateInvoiceRequest;
  24. use lnbits_rs::LNBitsClient;
  25. use serde_json::Value;
  26. use tokio_util::sync::CancellationToken;
  27. pub mod error;
  28. /// LNbits
  29. #[derive(Clone)]
  30. pub struct LNbits {
  31. lnbits_api: LNBitsClient,
  32. fee_reserve: FeeReserve,
  33. wait_invoice_cancel_token: CancellationToken,
  34. wait_invoice_is_active: Arc<AtomicBool>,
  35. settings: Bolt11Settings,
  36. }
  37. impl LNbits {
  38. /// Create new [`LNbits`] wallet
  39. #[allow(clippy::too_many_arguments)]
  40. pub async fn new(
  41. admin_api_key: String,
  42. invoice_api_key: String,
  43. api_url: String,
  44. fee_reserve: FeeReserve,
  45. ) -> Result<Self, Error> {
  46. let lnbits_api = LNBitsClient::new("", &admin_api_key, &invoice_api_key, &api_url, None)?;
  47. Ok(Self {
  48. lnbits_api,
  49. fee_reserve,
  50. wait_invoice_cancel_token: CancellationToken::new(),
  51. wait_invoice_is_active: Arc::new(AtomicBool::new(false)),
  52. settings: Bolt11Settings {
  53. mpp: false,
  54. unit: CurrencyUnit::Sat,
  55. invoice_description: true,
  56. amountless: false,
  57. bolt12: false,
  58. },
  59. })
  60. }
  61. /// Subscribe to lnbits ws
  62. pub async fn subscribe_ws(&self) -> Result<(), Error> {
  63. if rustls::crypto::CryptoProvider::get_default().is_none() {
  64. let _ = rustls::crypto::ring::default_provider().install_default();
  65. }
  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. /// Process an incoming message from the websocket receiver
  75. async fn process_message(
  76. msg_option: Option<String>,
  77. api: &LNBitsClient,
  78. _is_active: &Arc<AtomicBool>,
  79. ) -> Option<WaitPaymentResponse> {
  80. let msg = msg_option?;
  81. let payment = match api.get_payment_info(&msg).await {
  82. Ok(payment) => payment,
  83. Err(_) => return None,
  84. };
  85. if !payment.paid {
  86. tracing::warn!(
  87. "Received payment notification but payment not paid for {}",
  88. msg
  89. );
  90. return None;
  91. }
  92. Self::create_payment_response(&msg, &payment).unwrap_or_else(|e| {
  93. tracing::error!("Failed to create payment response: {}", e);
  94. None
  95. })
  96. }
  97. /// Create a payment response from payment info
  98. fn create_payment_response(
  99. msg: &str,
  100. payment: &lnbits_rs::api::payment::Payment,
  101. ) -> Result<Option<WaitPaymentResponse>, Error> {
  102. let amount = payment.details.amount;
  103. if amount == i64::MIN {
  104. return Ok(None);
  105. }
  106. let hash = Self::decode_payment_hash(msg)?;
  107. Ok(Some(WaitPaymentResponse {
  108. payment_identifier: PaymentIdentifier::PaymentHash(hash),
  109. payment_amount: Amount::from(amount.unsigned_abs()),
  110. unit: CurrencyUnit::Msat,
  111. payment_id: msg.to_string(),
  112. }))
  113. }
  114. /// Decode a hex payment hash string into a byte array
  115. fn decode_payment_hash(hash_str: &str) -> Result<[u8; 32], Error> {
  116. let decoded = hex::decode(hash_str)
  117. .map_err(|e| Error::Anyhow(anyhow!("Failed to decode payment hash: {}", e)))?;
  118. decoded
  119. .try_into()
  120. .map_err(|_| Error::Anyhow(anyhow!("Invalid payment hash length")))
  121. }
  122. }
  123. #[async_trait]
  124. impl MintPayment for LNbits {
  125. type Err = payment::Error;
  126. async fn get_settings(&self) -> Result<Value, Self::Err> {
  127. Ok(serde_json::to_value(&self.settings)?)
  128. }
  129. fn is_wait_invoice_active(&self) -> bool {
  130. self.wait_invoice_is_active.load(Ordering::SeqCst)
  131. }
  132. fn cancel_wait_invoice(&self) {
  133. self.wait_invoice_cancel_token.cancel()
  134. }
  135. async fn wait_payment_event(
  136. &self,
  137. ) -> Result<Pin<Box<dyn Stream<Item = Event> + Send>>, Self::Err> {
  138. let api = self.lnbits_api.clone();
  139. let cancel_token = self.wait_invoice_cancel_token.clone();
  140. let is_active = Arc::clone(&self.wait_invoice_is_active);
  141. Ok(Box::pin(futures::stream::unfold(
  142. (api, cancel_token, is_active),
  143. |(api, cancel_token, is_active)| async move {
  144. is_active.store(true, Ordering::SeqCst);
  145. let receiver = api.receiver();
  146. let mut receiver = receiver.lock().await;
  147. tokio::select! {
  148. _ = cancel_token.cancelled() => {
  149. is_active.store(false, Ordering::SeqCst);
  150. tracing::info!("Waiting for lnbits invoice ending");
  151. None
  152. }
  153. msg_option = receiver.recv() => {
  154. Self::process_message(msg_option, &api, &is_active)
  155. .await
  156. .map(|response| (Event::PaymentReceived(response), (api, cancel_token, is_active)))
  157. }
  158. }
  159. },
  160. )))
  161. }
  162. async fn get_payment_quote(
  163. &self,
  164. unit: &CurrencyUnit,
  165. options: OutgoingPaymentOptions,
  166. ) -> Result<PaymentQuoteResponse, Self::Err> {
  167. match options {
  168. OutgoingPaymentOptions::Bolt11(bolt11_options) => {
  169. let amount_msat = match bolt11_options.melt_options {
  170. Some(amount) => {
  171. if matches!(amount, MeltOptions::Mpp { mpp: _ }) {
  172. return Err(payment::Error::UnsupportedPaymentOption);
  173. }
  174. amount.amount_msat()
  175. }
  176. None => bolt11_options
  177. .bolt11
  178. .amount_milli_satoshis()
  179. .ok_or(Error::UnknownInvoiceAmount)?
  180. .into(),
  181. };
  182. let relative_fee_reserve =
  183. (self.fee_reserve.percent_fee_reserve * u64::from(amount_msat) as f32) as u64;
  184. let absolute_fee_reserve: u64 = self.fee_reserve.min_fee_reserve.into();
  185. let fee = max(relative_fee_reserve, absolute_fee_reserve);
  186. Ok(PaymentQuoteResponse {
  187. request_lookup_id: Some(PaymentIdentifier::PaymentHash(
  188. *bolt11_options.bolt11.payment_hash().as_ref(),
  189. )),
  190. amount: to_unit(amount_msat, &CurrencyUnit::Msat, unit)?,
  191. fee: fee.into(),
  192. state: MeltQuoteState::Unpaid,
  193. unit: unit.clone(),
  194. })
  195. }
  196. OutgoingPaymentOptions::Bolt12(_bolt12_options) => {
  197. Err(Self::Err::Anyhow(anyhow!("BOLT12 not supported by LNbits")))
  198. }
  199. }
  200. }
  201. async fn make_payment(
  202. &self,
  203. _unit: &CurrencyUnit,
  204. options: OutgoingPaymentOptions,
  205. ) -> Result<MakePaymentResponse, Self::Err> {
  206. match options {
  207. OutgoingPaymentOptions::Bolt11(bolt11_options) => {
  208. let pay_response = self
  209. .lnbits_api
  210. .pay_invoice(&bolt11_options.bolt11.to_string(), None)
  211. .await
  212. .map_err(|err| {
  213. tracing::error!("Could not pay invoice");
  214. tracing::error!("{}", err.to_string());
  215. Self::Err::Anyhow(anyhow!("Could not pay invoice"))
  216. })?;
  217. let invoice_info = self
  218. .lnbits_api
  219. .get_payment_info(&pay_response.payment_hash)
  220. .await
  221. .map_err(|err| {
  222. tracing::error!("Could not find invoice");
  223. tracing::error!("{}", err.to_string());
  224. Self::Err::Anyhow(anyhow!("Could not find invoice"))
  225. })?;
  226. let status = if invoice_info.paid {
  227. MeltQuoteState::Paid
  228. } else {
  229. MeltQuoteState::Unpaid
  230. };
  231. let total_spent = Amount::from(
  232. (invoice_info
  233. .details
  234. .amount
  235. .checked_add(invoice_info.details.fee)
  236. .ok_or(Error::AmountOverflow)?)
  237. .unsigned_abs(),
  238. );
  239. Ok(MakePaymentResponse {
  240. payment_lookup_id: PaymentIdentifier::PaymentHash(
  241. hex::decode(pay_response.payment_hash)
  242. .map_err(|_| Error::InvalidPaymentHash)?
  243. .try_into()
  244. .map_err(|_| Error::InvalidPaymentHash)?,
  245. ),
  246. payment_proof: Some(invoice_info.details.payment_hash),
  247. status,
  248. total_spent,
  249. unit: CurrencyUnit::Msat,
  250. })
  251. }
  252. OutgoingPaymentOptions::Bolt12(_) => {
  253. Err(Self::Err::Anyhow(anyhow!("BOLT12 not supported by LNbits")))
  254. }
  255. }
  256. }
  257. async fn create_incoming_payment_request(
  258. &self,
  259. unit: &CurrencyUnit,
  260. options: IncomingPaymentOptions,
  261. ) -> Result<CreateIncomingPaymentResponse, Self::Err> {
  262. match options {
  263. IncomingPaymentOptions::Bolt11(bolt11_options) => {
  264. let description = bolt11_options.description.unwrap_or_default();
  265. let amount = bolt11_options.amount;
  266. let unix_expiry = bolt11_options.unix_expiry;
  267. let time_now = unix_time();
  268. let expiry = unix_expiry.map(|t| t - time_now);
  269. let invoice_request = CreateInvoiceRequest {
  270. amount: to_unit(amount, unit, &CurrencyUnit::Sat)?.into(),
  271. memo: Some(description),
  272. unit: unit.to_string(),
  273. expiry,
  274. internal: None,
  275. out: false,
  276. };
  277. let create_invoice_response = self
  278. .lnbits_api
  279. .create_invoice(&invoice_request)
  280. .await
  281. .map_err(|err| {
  282. tracing::error!("Could not create invoice");
  283. tracing::error!("{}", err.to_string());
  284. Self::Err::Anyhow(anyhow!("Could not create invoice"))
  285. })?;
  286. let request: Bolt11Invoice = create_invoice_response.bolt11().parse()?;
  287. let expiry = request.expires_at().map(|t| t.as_secs());
  288. Ok(CreateIncomingPaymentResponse {
  289. request_lookup_id: PaymentIdentifier::PaymentHash(
  290. *request.payment_hash().as_ref(),
  291. ),
  292. request: request.to_string(),
  293. expiry,
  294. })
  295. }
  296. IncomingPaymentOptions::Bolt12(_) => {
  297. Err(Self::Err::Anyhow(anyhow!("BOLT12 not supported by LNbits")))
  298. }
  299. }
  300. }
  301. async fn check_incoming_payment_status(
  302. &self,
  303. payment_identifier: &PaymentIdentifier,
  304. ) -> Result<Vec<WaitPaymentResponse>, Self::Err> {
  305. let payment = self
  306. .lnbits_api
  307. .get_payment_info(&payment_identifier.to_string())
  308. .await
  309. .map_err(|err| {
  310. tracing::error!("Could not check invoice status");
  311. tracing::error!("{}", err.to_string());
  312. Self::Err::Anyhow(anyhow!("Could not check invoice status"))
  313. })?;
  314. let amount = payment.details.amount;
  315. if amount == i64::MIN {
  316. return Err(Error::AmountOverflow.into());
  317. }
  318. match payment.paid {
  319. true => Ok(vec![WaitPaymentResponse {
  320. payment_identifier: payment_identifier.clone(),
  321. payment_amount: Amount::from(amount.unsigned_abs()),
  322. unit: CurrencyUnit::Msat,
  323. payment_id: payment.details.payment_hash,
  324. }]),
  325. false => Ok(vec![]),
  326. }
  327. }
  328. async fn check_outgoing_payment(
  329. &self,
  330. payment_identifier: &PaymentIdentifier,
  331. ) -> Result<MakePaymentResponse, Self::Err> {
  332. let payment = self
  333. .lnbits_api
  334. .get_payment_info(&payment_identifier.to_string())
  335. .await
  336. .map_err(|err| {
  337. tracing::error!("Could not check invoice status");
  338. tracing::error!("{}", err.to_string());
  339. Self::Err::Anyhow(anyhow!("Could not check invoice status"))
  340. })?;
  341. let pay_response = MakePaymentResponse {
  342. payment_lookup_id: payment_identifier.clone(),
  343. payment_proof: payment.preimage,
  344. status: lnbits_to_melt_status(&payment.details.status),
  345. total_spent: Amount::from(
  346. payment.details.amount.unsigned_abs() + payment.details.fee.unsigned_abs(),
  347. ),
  348. unit: CurrencyUnit::Msat,
  349. };
  350. Ok(pay_response)
  351. }
  352. }
  353. fn lnbits_to_melt_status(status: &str) -> MeltQuoteState {
  354. match status {
  355. "success" => MeltQuoteState::Paid,
  356. "failed" => MeltQuoteState::Unpaid,
  357. "pending" => MeltQuoteState::Pending,
  358. _ => MeltQuoteState::Unknown,
  359. }
  360. }