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