lib.rs 16 KB

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