lib.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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, MSAT_IN_SAT};
  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, 0u32),
  143. |(api, cancel_token, is_active, mut retry_count)| async move {
  144. is_active.store(true, Ordering::SeqCst);
  145. loop {
  146. tracing::debug!("LNbits: Starting wait loop, attempting to get receiver");
  147. let receiver = api.receiver();
  148. let mut receiver = receiver.lock().await;
  149. tracing::debug!("LNbits: Got receiver lock, waiting for messages");
  150. tokio::select! {
  151. _ = cancel_token.cancelled() => {
  152. is_active.store(false, Ordering::SeqCst);
  153. tracing::info!("Waiting for lnbits invoice ending");
  154. return None;
  155. }
  156. msg_option = receiver.recv() => {
  157. tracing::debug!("LNbits: Received message from websocket: {:?}", msg_option.as_ref().map(|_| "Some(message)"));
  158. match msg_option {
  159. Some(_) => {
  160. // Successfully received a message, reset retry count
  161. retry_count = 0;
  162. let result = Self::process_message(msg_option, &api, &is_active).await;
  163. return result.map(|response| {
  164. (Event::PaymentReceived(response), (api, cancel_token, is_active, retry_count))
  165. });
  166. }
  167. None => {
  168. // Connection lost, need to reconnect
  169. drop(receiver); // Drop the lock before reconnecting
  170. tracing::warn!("LNbits websocket connection lost (receiver returned None), attempting to reconnect...");
  171. // Exponential backoff: 1s, 2s, 4s, 8s, max 10s
  172. let backoff_secs = std::cmp::min(2u64.pow(retry_count), 10);
  173. tracing::info!("Retrying in {} seconds (attempt {})", backoff_secs, retry_count + 1);
  174. tokio::time::sleep(std::time::Duration::from_secs(backoff_secs)).await;
  175. // Attempt to resubscribe
  176. if let Err(err) = api.subscribe_to_websocket().await {
  177. tracing::error!("Failed to resubscribe to LNbits websocket: {:?}", err);
  178. } else {
  179. tracing::info!("Successfully reconnected to LNbits websocket");
  180. }
  181. retry_count += 1;
  182. // Continue the loop to try again
  183. continue;
  184. }
  185. }
  186. }
  187. }
  188. }
  189. },
  190. )))
  191. }
  192. async fn get_payment_quote(
  193. &self,
  194. unit: &CurrencyUnit,
  195. options: OutgoingPaymentOptions,
  196. ) -> Result<PaymentQuoteResponse, Self::Err> {
  197. match options {
  198. OutgoingPaymentOptions::Bolt11(bolt11_options) => {
  199. let amount_msat = match bolt11_options.melt_options {
  200. Some(amount) => {
  201. if matches!(amount, MeltOptions::Mpp { mpp: _ }) {
  202. return Err(payment::Error::UnsupportedPaymentOption);
  203. }
  204. amount.amount_msat()
  205. }
  206. None => bolt11_options
  207. .bolt11
  208. .amount_milli_satoshis()
  209. .ok_or(Error::UnknownInvoiceAmount)?
  210. .into(),
  211. };
  212. let relative_fee_reserve =
  213. (self.fee_reserve.percent_fee_reserve * u64::from(amount_msat) as f32) as u64;
  214. let absolute_fee_reserve: u64 =
  215. u64::from(self.fee_reserve.min_fee_reserve) * MSAT_IN_SAT;
  216. let fee = max(relative_fee_reserve, absolute_fee_reserve);
  217. Ok(PaymentQuoteResponse {
  218. request_lookup_id: Some(PaymentIdentifier::PaymentHash(
  219. *bolt11_options.bolt11.payment_hash().as_ref(),
  220. )),
  221. amount: to_unit(amount_msat, &CurrencyUnit::Msat, unit)?,
  222. fee: to_unit(fee, &CurrencyUnit::Msat, unit)?,
  223. state: MeltQuoteState::Unpaid,
  224. unit: unit.clone(),
  225. })
  226. }
  227. OutgoingPaymentOptions::Bolt12(_bolt12_options) => {
  228. Err(Self::Err::Anyhow(anyhow!("BOLT12 not supported by LNbits")))
  229. }
  230. }
  231. }
  232. async fn make_payment(
  233. &self,
  234. _unit: &CurrencyUnit,
  235. options: OutgoingPaymentOptions,
  236. ) -> Result<MakePaymentResponse, Self::Err> {
  237. match options {
  238. OutgoingPaymentOptions::Bolt11(bolt11_options) => {
  239. let pay_response = self
  240. .lnbits_api
  241. .pay_invoice(&bolt11_options.bolt11.to_string(), None)
  242. .await
  243. .map_err(|err| {
  244. tracing::error!("Could not pay invoice");
  245. tracing::error!("{}", err.to_string());
  246. Self::Err::Anyhow(anyhow!("Could not pay invoice"))
  247. })?;
  248. let invoice_info = self
  249. .lnbits_api
  250. .get_payment_info(&pay_response.payment_hash)
  251. .await
  252. .map_err(|err| {
  253. tracing::error!("Could not find invoice");
  254. tracing::error!("{}", err.to_string());
  255. Self::Err::Anyhow(anyhow!("Could not find invoice"))
  256. })?;
  257. let status = if invoice_info.paid {
  258. MeltQuoteState::Paid
  259. } else {
  260. MeltQuoteState::Unpaid
  261. };
  262. let total_spent = Amount::from(
  263. (invoice_info
  264. .details
  265. .amount
  266. .checked_add(invoice_info.details.fee)
  267. .ok_or(Error::AmountOverflow)?)
  268. .unsigned_abs(),
  269. );
  270. Ok(MakePaymentResponse {
  271. payment_lookup_id: PaymentIdentifier::PaymentHash(
  272. hex::decode(pay_response.payment_hash)
  273. .map_err(|_| Error::InvalidPaymentHash)?
  274. .try_into()
  275. .map_err(|_| Error::InvalidPaymentHash)?,
  276. ),
  277. payment_proof: Some(invoice_info.details.payment_hash),
  278. status,
  279. total_spent,
  280. unit: CurrencyUnit::Msat,
  281. })
  282. }
  283. OutgoingPaymentOptions::Bolt12(_) => {
  284. Err(Self::Err::Anyhow(anyhow!("BOLT12 not supported by LNbits")))
  285. }
  286. }
  287. }
  288. async fn create_incoming_payment_request(
  289. &self,
  290. unit: &CurrencyUnit,
  291. options: IncomingPaymentOptions,
  292. ) -> Result<CreateIncomingPaymentResponse, Self::Err> {
  293. match options {
  294. IncomingPaymentOptions::Bolt11(bolt11_options) => {
  295. let description = bolt11_options.description.unwrap_or_default();
  296. let amount = bolt11_options.amount;
  297. let unix_expiry = bolt11_options.unix_expiry;
  298. let time_now = unix_time();
  299. let expiry = unix_expiry.map(|t| t - time_now);
  300. let invoice_request = CreateInvoiceRequest {
  301. amount: to_unit(amount, unit, &CurrencyUnit::Sat)?.into(),
  302. memo: Some(description),
  303. unit: unit.to_string(),
  304. expiry,
  305. internal: None,
  306. out: false,
  307. };
  308. let create_invoice_response = self
  309. .lnbits_api
  310. .create_invoice(&invoice_request)
  311. .await
  312. .map_err(|err| {
  313. tracing::error!("Could not create invoice");
  314. tracing::error!("{}", err.to_string());
  315. Self::Err::Anyhow(anyhow!("Could not create invoice"))
  316. })?;
  317. let request: Bolt11Invoice = create_invoice_response.bolt11().parse()?;
  318. let expiry = request.expires_at().map(|t| t.as_secs());
  319. Ok(CreateIncomingPaymentResponse {
  320. request_lookup_id: PaymentIdentifier::PaymentHash(
  321. *request.payment_hash().as_ref(),
  322. ),
  323. request: request.to_string(),
  324. expiry,
  325. })
  326. }
  327. IncomingPaymentOptions::Bolt12(_) => {
  328. Err(Self::Err::Anyhow(anyhow!("BOLT12 not supported by LNbits")))
  329. }
  330. }
  331. }
  332. async fn check_incoming_payment_status(
  333. &self,
  334. payment_identifier: &PaymentIdentifier,
  335. ) -> Result<Vec<WaitPaymentResponse>, Self::Err> {
  336. let payment = self
  337. .lnbits_api
  338. .get_payment_info(&payment_identifier.to_string())
  339. .await
  340. .map_err(|err| {
  341. tracing::error!("Could not check invoice status");
  342. tracing::error!("{}", err.to_string());
  343. Self::Err::Anyhow(anyhow!("Could not check invoice status"))
  344. })?;
  345. let amount = payment.details.amount;
  346. if amount == i64::MIN {
  347. return Err(Error::AmountOverflow.into());
  348. }
  349. match payment.paid {
  350. true => Ok(vec![WaitPaymentResponse {
  351. payment_identifier: payment_identifier.clone(),
  352. payment_amount: Amount::from(amount.unsigned_abs()),
  353. unit: CurrencyUnit::Msat,
  354. payment_id: payment.details.payment_hash,
  355. }]),
  356. false => Ok(vec![]),
  357. }
  358. }
  359. async fn check_outgoing_payment(
  360. &self,
  361. payment_identifier: &PaymentIdentifier,
  362. ) -> Result<MakePaymentResponse, Self::Err> {
  363. let payment = self
  364. .lnbits_api
  365. .get_payment_info(&payment_identifier.to_string())
  366. .await
  367. .map_err(|err| {
  368. tracing::error!("Could not check invoice status");
  369. tracing::error!("{}", err.to_string());
  370. Self::Err::Anyhow(anyhow!("Could not check invoice status"))
  371. })?;
  372. let pay_response = MakePaymentResponse {
  373. payment_lookup_id: payment_identifier.clone(),
  374. payment_proof: payment.preimage,
  375. status: lnbits_to_melt_status(&payment.details.status),
  376. total_spent: Amount::from(
  377. payment.details.amount.unsigned_abs() + payment.details.fee.unsigned_abs(),
  378. ),
  379. unit: CurrencyUnit::Msat,
  380. };
  381. Ok(pay_response)
  382. }
  383. }
  384. fn lnbits_to_melt_status(status: &str) -> MeltQuoteState {
  385. match status {
  386. "success" => MeltQuoteState::Paid,
  387. "failed" => MeltQuoteState::Unpaid,
  388. "pending" => MeltQuoteState::Pending,
  389. _ => MeltQuoteState::Unknown,
  390. }
  391. }