lib.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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, 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_any_incoming_payment(
  136. &self,
  137. ) -> Result<Pin<Box<dyn Stream<Item = WaitPaymentResponse> + 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| (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. if unit != &CurrencyUnit::Sat {
  168. return Err(Self::Err::Anyhow(anyhow!("Unsupported unit")));
  169. }
  170. match options {
  171. OutgoingPaymentOptions::Bolt11(bolt11_options) => {
  172. let amount_msat = match bolt11_options.melt_options {
  173. Some(amount) => {
  174. if matches!(amount, MeltOptions::Mpp { mpp: _ }) {
  175. return Err(payment::Error::UnsupportedPaymentOption);
  176. }
  177. amount.amount_msat()
  178. }
  179. None => bolt11_options
  180. .bolt11
  181. .amount_milli_satoshis()
  182. .ok_or(Error::UnknownInvoiceAmount)?
  183. .into(),
  184. };
  185. let amount = amount_msat / MSAT_IN_SAT.into();
  186. let relative_fee_reserve =
  187. (self.fee_reserve.percent_fee_reserve * u64::from(amount) as f32) as u64;
  188. let absolute_fee_reserve: u64 = self.fee_reserve.min_fee_reserve.into();
  189. let fee = max(relative_fee_reserve, absolute_fee_reserve);
  190. Ok(PaymentQuoteResponse {
  191. request_lookup_id: Some(PaymentIdentifier::PaymentHash(
  192. *bolt11_options.bolt11.payment_hash().as_ref(),
  193. )),
  194. amount,
  195. fee: fee.into(),
  196. state: MeltQuoteState::Unpaid,
  197. unit: unit.clone(),
  198. })
  199. }
  200. OutgoingPaymentOptions::Bolt12(_bolt12_options) => {
  201. Err(Self::Err::Anyhow(anyhow!("BOLT12 not supported by LNbits")))
  202. }
  203. }
  204. }
  205. async fn make_payment(
  206. &self,
  207. _unit: &CurrencyUnit,
  208. options: OutgoingPaymentOptions,
  209. ) -> Result<MakePaymentResponse, Self::Err> {
  210. match options {
  211. OutgoingPaymentOptions::Bolt11(bolt11_options) => {
  212. let pay_response = self
  213. .lnbits_api
  214. .pay_invoice(&bolt11_options.bolt11.to_string(), None)
  215. .await
  216. .map_err(|err| {
  217. tracing::error!("Could not pay invoice");
  218. tracing::error!("{}", err.to_string());
  219. Self::Err::Anyhow(anyhow!("Could not pay invoice"))
  220. })?;
  221. let invoice_info = self
  222. .lnbits_api
  223. .get_payment_info(&pay_response.payment_hash)
  224. .await
  225. .map_err(|err| {
  226. tracing::error!("Could not find invoice");
  227. tracing::error!("{}", err.to_string());
  228. Self::Err::Anyhow(anyhow!("Could not find invoice"))
  229. })?;
  230. let status = if invoice_info.paid {
  231. MeltQuoteState::Paid
  232. } else {
  233. MeltQuoteState::Unpaid
  234. };
  235. let total_spent = Amount::from(
  236. (invoice_info
  237. .details
  238. .amount
  239. .checked_add(invoice_info.details.fee)
  240. .ok_or(Error::AmountOverflow)?)
  241. .unsigned_abs(),
  242. );
  243. Ok(MakePaymentResponse {
  244. payment_lookup_id: PaymentIdentifier::PaymentHash(
  245. hex::decode(pay_response.payment_hash)
  246. .map_err(|_| Error::InvalidPaymentHash)?
  247. .try_into()
  248. .map_err(|_| Error::InvalidPaymentHash)?,
  249. ),
  250. payment_proof: Some(invoice_info.details.payment_hash),
  251. status,
  252. total_spent,
  253. unit: CurrencyUnit::Msat,
  254. })
  255. }
  256. OutgoingPaymentOptions::Bolt12(_) => {
  257. Err(Self::Err::Anyhow(anyhow!("BOLT12 not supported by LNbits")))
  258. }
  259. }
  260. }
  261. async fn create_incoming_payment_request(
  262. &self,
  263. unit: &CurrencyUnit,
  264. options: IncomingPaymentOptions,
  265. ) -> Result<CreateIncomingPaymentResponse, Self::Err> {
  266. if unit != &CurrencyUnit::Sat {
  267. return Err(Self::Err::Anyhow(anyhow!("Unsupported unit")));
  268. }
  269. match options {
  270. IncomingPaymentOptions::Bolt11(bolt11_options) => {
  271. let description = bolt11_options.description.unwrap_or_default();
  272. let amount = bolt11_options.amount;
  273. let unix_expiry = bolt11_options.unix_expiry;
  274. let time_now = unix_time();
  275. let expiry = unix_expiry.map(|t| t - time_now);
  276. let invoice_request = CreateInvoiceRequest {
  277. amount: to_unit(amount, unit, &CurrencyUnit::Sat)?.into(),
  278. memo: Some(description),
  279. unit: unit.to_string(),
  280. expiry,
  281. internal: None,
  282. out: false,
  283. };
  284. let create_invoice_response = self
  285. .lnbits_api
  286. .create_invoice(&invoice_request)
  287. .await
  288. .map_err(|err| {
  289. tracing::error!("Could not create invoice");
  290. tracing::error!("{}", err.to_string());
  291. Self::Err::Anyhow(anyhow!("Could not create invoice"))
  292. })?;
  293. let request: Bolt11Invoice = create_invoice_response.bolt11().parse()?;
  294. let expiry = request.expires_at().map(|t| t.as_secs());
  295. Ok(CreateIncomingPaymentResponse {
  296. request_lookup_id: PaymentIdentifier::PaymentHash(
  297. *request.payment_hash().as_ref(),
  298. ),
  299. request: request.to_string(),
  300. expiry,
  301. })
  302. }
  303. IncomingPaymentOptions::Bolt12(_) => {
  304. Err(Self::Err::Anyhow(anyhow!("BOLT12 not supported by LNbits")))
  305. }
  306. }
  307. }
  308. async fn check_incoming_payment_status(
  309. &self,
  310. payment_identifier: &PaymentIdentifier,
  311. ) -> Result<Vec<WaitPaymentResponse>, Self::Err> {
  312. let payment = self
  313. .lnbits_api
  314. .get_payment_info(&payment_identifier.to_string())
  315. .await
  316. .map_err(|err| {
  317. tracing::error!("Could not check invoice status");
  318. tracing::error!("{}", err.to_string());
  319. Self::Err::Anyhow(anyhow!("Could not check invoice status"))
  320. })?;
  321. let amount = payment.details.amount;
  322. if amount == i64::MIN {
  323. return Err(Error::AmountOverflow.into());
  324. }
  325. match payment.paid {
  326. true => Ok(vec![WaitPaymentResponse {
  327. payment_identifier: payment_identifier.clone(),
  328. payment_amount: Amount::from(amount.unsigned_abs()),
  329. unit: CurrencyUnit::Msat,
  330. payment_id: payment.details.payment_hash,
  331. }]),
  332. false => Ok(vec![]),
  333. }
  334. }
  335. async fn check_outgoing_payment(
  336. &self,
  337. payment_identifier: &PaymentIdentifier,
  338. ) -> Result<MakePaymentResponse, Self::Err> {
  339. let payment = self
  340. .lnbits_api
  341. .get_payment_info(&payment_identifier.to_string())
  342. .await
  343. .map_err(|err| {
  344. tracing::error!("Could not check invoice status");
  345. tracing::error!("{}", err.to_string());
  346. Self::Err::Anyhow(anyhow!("Could not check invoice status"))
  347. })?;
  348. let pay_response = MakePaymentResponse {
  349. payment_lookup_id: payment_identifier.clone(),
  350. payment_proof: payment.preimage,
  351. status: lnbits_to_melt_status(&payment.details.status),
  352. total_spent: Amount::from(
  353. payment.details.amount.unsigned_abs() + payment.details.fee.unsigned_abs(),
  354. ),
  355. unit: CurrencyUnit::Msat,
  356. };
  357. Ok(pay_response)
  358. }
  359. }
  360. fn lnbits_to_melt_status(status: &str) -> MeltQuoteState {
  361. match status {
  362. "success" => MeltQuoteState::Paid,
  363. "failed" => MeltQuoteState::Unpaid,
  364. "pending" => MeltQuoteState::Pending,
  365. _ => MeltQuoteState::Unknown,
  366. }
  367. }