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