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