lib.rs 17 KB

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