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};
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 = self.fee_reserve.min_fee_reserve.into();
248
249 let fee = max(relative_fee_reserve, absolute_fee_reserve);
250
251 Ok(PaymentQuoteResponse {
252 request_lookup_id: Some(PaymentIdentifier::PaymentHash(
253 *bolt11_options.bolt11.payment_hash().as_ref(),
254 )),
255 amount: to_unit(amount_msat, &CurrencyUnit::Msat, unit)?,
256 fee: fee.into(),
257 state: MeltQuoteState::Unpaid,
258 unit: unit.clone(),
259 })
260 }
261 OutgoingPaymentOptions::Bolt12(_bolt12_options) => {
262 Err(Self::Err::Anyhow(anyhow!("BOLT12 not supported by LNbits")))
263 }
264 }
265 }
266
267 async fn make_payment(
268 &self,
269 _unit: &CurrencyUnit,
270 options: OutgoingPaymentOptions,
271 ) -> Result<MakePaymentResponse, Self::Err> {
272 match options {
273 OutgoingPaymentOptions::Bolt11(bolt11_options) => {
274 let pay_response = self
275 .lnbits_api
276 .pay_invoice(&bolt11_options.bolt11.to_string(), None)
277 .await
278 .map_err(|err| {
279 tracing::error!("Could not pay invoice");
280 tracing::error!("{}", err.to_string());
281 Self::Err::Anyhow(anyhow!("Could not pay invoice"))
282 })?;
283
284 let invoice_info = self
285 .lnbits_api
286 .get_payment_info(&pay_response.payment_hash)
287 .await
288 .map_err(|err| {
289 tracing::error!("Could not find invoice");
290 tracing::error!("{}", err.to_string());
291 Self::Err::Anyhow(anyhow!("Could not find invoice"))
292 })?;
293
294 let status = if invoice_info.paid {
295 MeltQuoteState::Paid
296 } else {
297 MeltQuoteState::Unpaid
298 };
299
300 let total_spent = Amount::from(
301 (invoice_info
302 .details
303 .amount
304 .checked_add(invoice_info.details.fee)
305 .ok_or(Error::AmountOverflow)?)
306 .unsigned_abs(),
307 );
308
309 Ok(MakePaymentResponse {
310 payment_lookup_id: PaymentIdentifier::PaymentHash(
311 hex::decode(pay_response.payment_hash)
312 .map_err(|_| Error::InvalidPaymentHash)?
313 .try_into()
314 .map_err(|_| Error::InvalidPaymentHash)?,
315 ),
316 payment_proof: Some(invoice_info.details.payment_hash),
317 status,
318 total_spent,
319 unit: CurrencyUnit::Msat,
320 })
321 }
322 OutgoingPaymentOptions::Bolt12(_) => {
323 Err(Self::Err::Anyhow(anyhow!("BOLT12 not supported by LNbits")))
324 }
325 }
326 }
327
328 async fn create_incoming_payment_request(
329 &self,
330 unit: &CurrencyUnit,
331 options: IncomingPaymentOptions,
332 ) -> Result<CreateIncomingPaymentResponse, Self::Err> {
333 match options {
334 IncomingPaymentOptions::Bolt11(bolt11_options) => {
335 let description = bolt11_options.description.unwrap_or_default();
336 let amount = bolt11_options.amount;
337 let unix_expiry = bolt11_options.unix_expiry;
338
339 let time_now = unix_time();
340 let expiry = unix_expiry.map(|t| t - time_now);
341
342 let invoice_request = CreateInvoiceRequest {
343 amount: to_unit(amount, unit, &CurrencyUnit::Sat)?.into(),
344 memo: Some(description),
345 unit: unit.to_string(),
346 expiry,
347 internal: None,
348 out: false,
349 };
350
351 let create_invoice_response = self
352 .lnbits_api
353 .create_invoice(&invoice_request)
354 .await
355 .map_err(|err| {
356 tracing::error!("Could not create invoice");
357 tracing::error!("{}", err.to_string());
358 Self::Err::Anyhow(anyhow!("Could not create invoice"))
359 })?;
360
361 let request: Bolt11Invoice = create_invoice_response.bolt11().parse()?;
362
363 let expiry = request.expires_at().map(|t| t.as_secs());
364
365 Ok(CreateIncomingPaymentResponse {
366 request_lookup_id: PaymentIdentifier::PaymentHash(
367 *request.payment_hash().as_ref(),
368 ),
369 request: request.to_string(),
370 expiry,
371 })
372 }
373 IncomingPaymentOptions::Bolt12(_) => {
374 Err(Self::Err::Anyhow(anyhow!("BOLT12 not supported by LNbits")))
375 }
376 }
377 }
378
379 async fn check_incoming_payment_status(
380 &self,
381 payment_identifier: &PaymentIdentifier,
382 ) -> Result<Vec<WaitPaymentResponse>, Self::Err> {
383 let payment = self
384 .lnbits_api
385 .get_payment_info(&payment_identifier.to_string())
386 .await
387 .map_err(|err| {
388 tracing::error!("Could not check invoice status");
389 tracing::error!("{}", err.to_string());
390 Self::Err::Anyhow(anyhow!("Could not check invoice status"))
391 })?;
392
393 let amount = payment.details.amount;
394
395 if amount == i64::MIN {
396 return Err(Error::AmountOverflow.into());
397 }
398
399 match payment.paid {
400 true => Ok(vec![WaitPaymentResponse {
401 payment_identifier: payment_identifier.clone(),
402 payment_amount: Amount::from(amount.unsigned_abs()),
403 unit: CurrencyUnit::Msat,
404 payment_id: payment.details.payment_hash,
405 }]),
406 false => Ok(vec![]),
407 }
408 }
409
410 async fn check_outgoing_payment(
411 &self,
412 payment_identifier: &PaymentIdentifier,
413 ) -> Result<MakePaymentResponse, Self::Err> {
414 let payment = self
415 .lnbits_api
416 .get_payment_info(&payment_identifier.to_string())
417 .await
418 .map_err(|err| {
419 tracing::error!("Could not check invoice status");
420 tracing::error!("{}", err.to_string());
421 Self::Err::Anyhow(anyhow!("Could not check invoice status"))
422 })?;
423
424 let pay_response = MakePaymentResponse {
425 payment_lookup_id: payment_identifier.clone(),
426 payment_proof: payment.preimage,
427 status: lnbits_to_melt_status(&payment.details.status),
428 total_spent: Amount::from(
429 payment.details.amount.unsigned_abs() + payment.details.fee.unsigned_abs(),
430 ),
431 unit: CurrencyUnit::Msat,
432 };
433
434 Ok(pay_response)
435 }
436}
437
438fn lnbits_to_melt_status(status: &str) -> MeltQuoteState {
439 match status {
440 "success" => MeltQuoteState::Paid,
441 "failed" => MeltQuoteState::Unpaid,
442 "pending" => MeltQuoteState::Pending,
443 _ => MeltQuoteState::Unknown,
444 }
445}