lib.rs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. //! CDK lightning backend for LND
  2. // Copyright (c) 2023 Steffen (MIT)
  3. #![doc = include_str!("../README.md")]
  4. #![warn(missing_docs)]
  5. #![warn(rustdoc::bare_urls)]
  6. use std::cmp::max;
  7. use std::path::PathBuf;
  8. use std::pin::Pin;
  9. use std::str::FromStr;
  10. use std::sync::atomic::{AtomicBool, Ordering};
  11. use std::sync::Arc;
  12. use anyhow::anyhow;
  13. use async_trait::async_trait;
  14. use cdk_common::amount::{to_unit, Amount, MSAT_IN_SAT};
  15. use cdk_common::bitcoin::hashes::Hash;
  16. use cdk_common::common::FeeReserve;
  17. use cdk_common::nuts::{CurrencyUnit, MeltOptions, MeltQuoteState, MintQuoteState};
  18. use cdk_common::payment::{
  19. self, Bolt11Settings, CreateIncomingPaymentResponse, MakePaymentResponse, MintPayment,
  20. PaymentQuoteResponse,
  21. };
  22. use cdk_common::util::hex;
  23. use cdk_common::{mint, Bolt11Invoice};
  24. use error::Error;
  25. use futures::{Stream, StreamExt};
  26. use lnrpc::fee_limit::Limit;
  27. use lnrpc::payment::PaymentStatus;
  28. use lnrpc::{FeeLimit, Hop, MppRecord};
  29. use tokio_util::sync::CancellationToken;
  30. use tracing::instrument;
  31. mod client;
  32. pub mod error;
  33. mod proto;
  34. pub(crate) use proto::{lnrpc, routerrpc};
  35. /// Lnd mint backend
  36. #[derive(Clone)]
  37. pub struct Lnd {
  38. _address: String,
  39. _cert_file: PathBuf,
  40. _macaroon_file: PathBuf,
  41. lnd_client: client::Client,
  42. fee_reserve: FeeReserve,
  43. wait_invoice_cancel_token: CancellationToken,
  44. wait_invoice_is_active: Arc<AtomicBool>,
  45. settings: Bolt11Settings,
  46. }
  47. impl Lnd {
  48. /// Maximum number of attempts at a partial payment
  49. pub const MAX_ROUTE_RETRIES: usize = 50;
  50. /// Create new [`Lnd`]
  51. pub async fn new(
  52. address: String,
  53. cert_file: PathBuf,
  54. macaroon_file: PathBuf,
  55. fee_reserve: FeeReserve,
  56. ) -> Result<Self, Error> {
  57. // Validate address is not empty
  58. if address.is_empty() {
  59. return Err(Error::InvalidConfig("LND address cannot be empty".into()));
  60. }
  61. // Validate cert_file exists and is not empty
  62. if !cert_file.exists() || cert_file.metadata().map(|m| m.len() == 0).unwrap_or(true) {
  63. return Err(Error::InvalidConfig(format!(
  64. "LND certificate file not found or empty: {cert_file:?}"
  65. )));
  66. }
  67. // Validate macaroon_file exists and is not empty
  68. if !macaroon_file.exists()
  69. || macaroon_file
  70. .metadata()
  71. .map(|m| m.len() == 0)
  72. .unwrap_or(true)
  73. {
  74. return Err(Error::InvalidConfig(format!(
  75. "LND macaroon file not found or empty: {macaroon_file:?}"
  76. )));
  77. }
  78. let lnd_client = client::connect(&address, &cert_file, &macaroon_file)
  79. .await
  80. .map_err(|err| {
  81. tracing::error!("Connection error: {}", err.to_string());
  82. Error::Connection
  83. })
  84. .unwrap();
  85. Ok(Self {
  86. _address: address,
  87. _cert_file: cert_file,
  88. _macaroon_file: macaroon_file,
  89. lnd_client,
  90. fee_reserve,
  91. wait_invoice_cancel_token: CancellationToken::new(),
  92. wait_invoice_is_active: Arc::new(AtomicBool::new(false)),
  93. settings: Bolt11Settings {
  94. mpp: true,
  95. unit: CurrencyUnit::Msat,
  96. invoice_description: true,
  97. amountless: true,
  98. },
  99. })
  100. }
  101. }
  102. #[async_trait]
  103. impl MintPayment for Lnd {
  104. type Err = payment::Error;
  105. #[instrument(skip_all)]
  106. async fn get_settings(&self) -> Result<serde_json::Value, Self::Err> {
  107. Ok(serde_json::to_value(&self.settings)?)
  108. }
  109. #[instrument(skip_all)]
  110. fn is_wait_invoice_active(&self) -> bool {
  111. self.wait_invoice_is_active.load(Ordering::SeqCst)
  112. }
  113. #[instrument(skip_all)]
  114. fn cancel_wait_invoice(&self) {
  115. self.wait_invoice_cancel_token.cancel()
  116. }
  117. #[instrument(skip_all)]
  118. async fn wait_any_incoming_payment(
  119. &self,
  120. ) -> Result<Pin<Box<dyn Stream<Item = String> + Send>>, Self::Err> {
  121. let mut lnd_client = self.lnd_client.clone();
  122. let stream_req = lnrpc::InvoiceSubscription {
  123. add_index: 0,
  124. settle_index: 0,
  125. };
  126. let stream = lnd_client
  127. .lightning()
  128. .subscribe_invoices(stream_req)
  129. .await
  130. .map_err(|_err| {
  131. tracing::error!("Could not subscribe to invoice");
  132. Error::Connection
  133. })?
  134. .into_inner();
  135. let cancel_token = self.wait_invoice_cancel_token.clone();
  136. Ok(futures::stream::unfold(
  137. (
  138. stream,
  139. cancel_token,
  140. Arc::clone(&self.wait_invoice_is_active),
  141. ),
  142. |(mut stream, cancel_token, is_active)| async move {
  143. is_active.store(true, Ordering::SeqCst);
  144. tokio::select! {
  145. _ = cancel_token.cancelled() => {
  146. // Stream is cancelled
  147. is_active.store(false, Ordering::SeqCst);
  148. tracing::info!("Waiting for lnd invoice ending");
  149. None
  150. }
  151. msg = stream.message() => {
  152. match msg {
  153. Ok(Some(msg)) => {
  154. if msg.state == 1 {
  155. Some((hex::encode(msg.r_hash), (stream, cancel_token, is_active)))
  156. } else {
  157. None
  158. }
  159. }
  160. Ok(None) => {
  161. is_active.store(false, Ordering::SeqCst);
  162. tracing::info!("LND invoice stream ended.");
  163. None
  164. }, // End of stream
  165. Err(err) => {
  166. is_active.store(false, Ordering::SeqCst);
  167. tracing::warn!("Encountered error in LND invoice stream. Stream ending");
  168. tracing::error!("{:?}", err);
  169. None
  170. }, // Handle errors gracefully, ends the stream on error
  171. }
  172. }
  173. }
  174. },
  175. )
  176. .boxed())
  177. }
  178. #[instrument(skip_all)]
  179. async fn get_payment_quote(
  180. &self,
  181. request: &str,
  182. unit: &CurrencyUnit,
  183. options: Option<MeltOptions>,
  184. ) -> Result<PaymentQuoteResponse, Self::Err> {
  185. let bolt11 = Bolt11Invoice::from_str(request)?;
  186. let amount_msat = match options {
  187. Some(amount) => amount.amount_msat(),
  188. None => bolt11
  189. .amount_milli_satoshis()
  190. .ok_or(Error::UnknownInvoiceAmount)?
  191. .into(),
  192. };
  193. let amount = to_unit(amount_msat, &CurrencyUnit::Msat, unit)?;
  194. let relative_fee_reserve =
  195. (self.fee_reserve.percent_fee_reserve * u64::from(amount) as f32) as u64;
  196. let absolute_fee_reserve: u64 = self.fee_reserve.min_fee_reserve.into();
  197. let fee = max(relative_fee_reserve, absolute_fee_reserve);
  198. Ok(PaymentQuoteResponse {
  199. request_lookup_id: bolt11.payment_hash().to_string(),
  200. amount,
  201. fee: fee.into(),
  202. state: MeltQuoteState::Unpaid,
  203. })
  204. }
  205. #[instrument(skip_all)]
  206. async fn make_payment(
  207. &self,
  208. melt_quote: mint::MeltQuote,
  209. partial_amount: Option<Amount>,
  210. max_fee: Option<Amount>,
  211. ) -> Result<MakePaymentResponse, Self::Err> {
  212. let payment_request = melt_quote.request;
  213. let bolt11 = Bolt11Invoice::from_str(&payment_request)?;
  214. let pay_state = self
  215. .check_outgoing_payment(&bolt11.payment_hash().to_string())
  216. .await?;
  217. match pay_state.status {
  218. MeltQuoteState::Unpaid | MeltQuoteState::Unknown | MeltQuoteState::Failed => (),
  219. MeltQuoteState::Paid => {
  220. tracing::debug!("Melt attempted on invoice already paid");
  221. return Err(Self::Err::InvoiceAlreadyPaid);
  222. }
  223. MeltQuoteState::Pending => {
  224. tracing::debug!("Melt attempted on invoice already pending");
  225. return Err(Self::Err::InvoicePaymentPending);
  226. }
  227. }
  228. let bolt11 = Bolt11Invoice::from_str(&payment_request)?;
  229. let amount_msat: u64 = match bolt11.amount_milli_satoshis() {
  230. Some(amount_msat) => amount_msat,
  231. None => melt_quote
  232. .msat_to_pay
  233. .ok_or(Error::UnknownInvoiceAmount)?
  234. .into(),
  235. };
  236. // Detect partial payments
  237. match partial_amount {
  238. Some(part_amt) => {
  239. let partial_amount_msat = to_unit(part_amt, &melt_quote.unit, &CurrencyUnit::Msat)?;
  240. let invoice = Bolt11Invoice::from_str(&payment_request)?;
  241. // Extract information from invoice
  242. let pub_key = invoice.get_payee_pub_key();
  243. let payer_addr = invoice.payment_secret().0.to_vec();
  244. let payment_hash = invoice.payment_hash();
  245. let mut lnd_client = self.lnd_client.clone();
  246. for attempt in 0..Self::MAX_ROUTE_RETRIES {
  247. // Create a request for the routes
  248. let route_req = lnrpc::QueryRoutesRequest {
  249. pub_key: hex::encode(pub_key.serialize()),
  250. amt_msat: u64::from(partial_amount_msat) as i64,
  251. fee_limit: max_fee.map(|f| {
  252. let limit = Limit::Fixed(u64::from(f) as i64);
  253. FeeLimit { limit: Some(limit) }
  254. }),
  255. use_mission_control: true,
  256. ..Default::default()
  257. };
  258. // Query the routes
  259. let mut routes_response = lnd_client
  260. .lightning()
  261. .query_routes(route_req)
  262. .await
  263. .map_err(Error::LndError)?
  264. .into_inner();
  265. // update its MPP record,
  266. // attempt it and check the result
  267. let last_hop: &mut Hop = routes_response.routes[0]
  268. .hops
  269. .last_mut()
  270. .ok_or(Error::MissingLastHop)?;
  271. let mpp_record = MppRecord {
  272. payment_addr: payer_addr.clone(),
  273. total_amt_msat: amount_msat as i64,
  274. };
  275. last_hop.mpp_record = Some(mpp_record);
  276. let payment_response = lnd_client
  277. .router()
  278. .send_to_route_v2(routerrpc::SendToRouteRequest {
  279. payment_hash: payment_hash.to_byte_array().to_vec(),
  280. route: Some(routes_response.routes[0].clone()),
  281. ..Default::default()
  282. })
  283. .await
  284. .map_err(Error::LndError)?
  285. .into_inner();
  286. if let Some(failure) = payment_response.failure {
  287. if failure.code == 15 {
  288. tracing::debug!(
  289. "Attempt number {}: route has failed. Re-querying...",
  290. attempt + 1
  291. );
  292. continue;
  293. }
  294. }
  295. // Get status and maybe the preimage
  296. let (status, payment_preimage) = match payment_response.status {
  297. 0 => (MeltQuoteState::Pending, None),
  298. 1 => (
  299. MeltQuoteState::Paid,
  300. Some(hex::encode(payment_response.preimage)),
  301. ),
  302. 2 => (MeltQuoteState::Unpaid, None),
  303. _ => (MeltQuoteState::Unknown, None),
  304. };
  305. // Get the actual amount paid in sats
  306. let mut total_amt: u64 = 0;
  307. if let Some(route) = payment_response.route {
  308. total_amt = (route.total_amt_msat / 1000) as u64;
  309. }
  310. return Ok(MakePaymentResponse {
  311. payment_lookup_id: hex::encode(payment_hash),
  312. payment_proof: payment_preimage,
  313. status,
  314. total_spent: total_amt.into(),
  315. unit: CurrencyUnit::Sat,
  316. });
  317. }
  318. // "We have exhausted all tactical options" -- STEM, Upgrade (2018)
  319. // The payment was not possible within 50 retries.
  320. tracing::error!("Limit of retries reached, payment couldn't succeed.");
  321. Err(Error::PaymentFailed.into())
  322. }
  323. None => {
  324. let mut lnd_client = self.lnd_client.clone();
  325. let pay_req = lnrpc::SendRequest {
  326. payment_request,
  327. fee_limit: max_fee.map(|f| {
  328. let limit = Limit::Fixed(u64::from(f) as i64);
  329. FeeLimit { limit: Some(limit) }
  330. }),
  331. amt_msat: amount_msat as i64,
  332. ..Default::default()
  333. };
  334. let payment_response = lnd_client
  335. .lightning()
  336. .send_payment_sync(tonic::Request::new(pay_req))
  337. .await
  338. .map_err(|err| {
  339. tracing::warn!("Lightning payment failed: {}", err);
  340. Error::PaymentFailed
  341. })?
  342. .into_inner();
  343. let total_amount = payment_response
  344. .payment_route
  345. .map_or(0, |route| route.total_amt_msat / MSAT_IN_SAT as i64)
  346. as u64;
  347. let (status, payment_preimage) = match total_amount == 0 {
  348. true => (MeltQuoteState::Unpaid, None),
  349. false => (
  350. MeltQuoteState::Paid,
  351. Some(hex::encode(payment_response.payment_preimage)),
  352. ),
  353. };
  354. Ok(MakePaymentResponse {
  355. payment_lookup_id: hex::encode(payment_response.payment_hash),
  356. payment_proof: payment_preimage,
  357. status,
  358. total_spent: total_amount.into(),
  359. unit: CurrencyUnit::Sat,
  360. })
  361. }
  362. }
  363. }
  364. #[instrument(skip(self, description))]
  365. async fn create_incoming_payment_request(
  366. &self,
  367. amount: Amount,
  368. unit: &CurrencyUnit,
  369. description: String,
  370. unix_expiry: Option<u64>,
  371. ) -> Result<CreateIncomingPaymentResponse, Self::Err> {
  372. let amount = to_unit(amount, unit, &CurrencyUnit::Msat)?;
  373. let invoice_request = lnrpc::Invoice {
  374. value_msat: u64::from(amount) as i64,
  375. memo: description,
  376. ..Default::default()
  377. };
  378. let mut lnd_client = self.lnd_client.clone();
  379. let invoice = lnd_client
  380. .lightning()
  381. .add_invoice(tonic::Request::new(invoice_request))
  382. .await
  383. .map_err(|e| payment::Error::Anyhow(anyhow!(e)))?
  384. .into_inner();
  385. let bolt11 = Bolt11Invoice::from_str(&invoice.payment_request)?;
  386. Ok(CreateIncomingPaymentResponse {
  387. request_lookup_id: bolt11.payment_hash().to_string(),
  388. request: bolt11.to_string(),
  389. expiry: unix_expiry,
  390. })
  391. }
  392. #[instrument(skip(self))]
  393. async fn check_incoming_payment_status(
  394. &self,
  395. request_lookup_id: &str,
  396. ) -> Result<MintQuoteState, Self::Err> {
  397. let mut lnd_client = self.lnd_client.clone();
  398. let invoice_request = lnrpc::PaymentHash {
  399. r_hash: hex::decode(request_lookup_id).unwrap(),
  400. ..Default::default()
  401. };
  402. let invoice = lnd_client
  403. .lightning()
  404. .lookup_invoice(tonic::Request::new(invoice_request))
  405. .await
  406. .map_err(|e| payment::Error::Anyhow(anyhow!(e)))?
  407. .into_inner();
  408. match invoice.state {
  409. // Open
  410. 0 => Ok(MintQuoteState::Unpaid),
  411. // Settled
  412. 1 => Ok(MintQuoteState::Paid),
  413. // Canceled
  414. 2 => Ok(MintQuoteState::Unpaid),
  415. // Accepted
  416. 3 => Ok(MintQuoteState::Unpaid),
  417. _ => Err(Self::Err::Anyhow(anyhow!("Invalid status"))),
  418. }
  419. }
  420. #[instrument(skip(self))]
  421. async fn check_outgoing_payment(
  422. &self,
  423. payment_hash: &str,
  424. ) -> Result<MakePaymentResponse, Self::Err> {
  425. let mut lnd_client = self.lnd_client.clone();
  426. let track_request = routerrpc::TrackPaymentRequest {
  427. payment_hash: hex::decode(payment_hash).map_err(|_| Error::InvalidHash)?,
  428. no_inflight_updates: true,
  429. };
  430. let payment_response = lnd_client.router().track_payment_v2(track_request).await;
  431. let mut payment_stream = match payment_response {
  432. Ok(stream) => stream.into_inner(),
  433. Err(err) => {
  434. let err_code = err.code();
  435. if err_code == tonic::Code::NotFound {
  436. return Ok(MakePaymentResponse {
  437. payment_lookup_id: payment_hash.to_string(),
  438. payment_proof: None,
  439. status: MeltQuoteState::Unknown,
  440. total_spent: Amount::ZERO,
  441. unit: self.settings.unit.clone(),
  442. });
  443. } else {
  444. return Err(payment::Error::UnknownPaymentState);
  445. }
  446. }
  447. };
  448. while let Some(update_result) = payment_stream.next().await {
  449. match update_result {
  450. Ok(update) => {
  451. let status = update.status();
  452. let response = match status {
  453. PaymentStatus::Unknown => MakePaymentResponse {
  454. payment_lookup_id: payment_hash.to_string(),
  455. payment_proof: Some(update.payment_preimage),
  456. status: MeltQuoteState::Unknown,
  457. total_spent: Amount::ZERO,
  458. unit: self.settings.unit.clone(),
  459. },
  460. PaymentStatus::InFlight | PaymentStatus::Initiated => {
  461. // Continue waiting for the next update
  462. continue;
  463. }
  464. PaymentStatus::Succeeded => MakePaymentResponse {
  465. payment_lookup_id: payment_hash.to_string(),
  466. payment_proof: Some(update.payment_preimage),
  467. status: MeltQuoteState::Paid,
  468. total_spent: Amount::from(
  469. (update
  470. .value_sat
  471. .checked_add(update.fee_sat)
  472. .ok_or(Error::AmountOverflow)?)
  473. as u64,
  474. ),
  475. unit: CurrencyUnit::Sat,
  476. },
  477. PaymentStatus::Failed => MakePaymentResponse {
  478. payment_lookup_id: payment_hash.to_string(),
  479. payment_proof: Some(update.payment_preimage),
  480. status: MeltQuoteState::Failed,
  481. total_spent: Amount::ZERO,
  482. unit: self.settings.unit.clone(),
  483. },
  484. };
  485. return Ok(response);
  486. }
  487. Err(_) => {
  488. // Handle the case where the update itself is an error (e.g., stream failure)
  489. return Err(Error::UnknownPaymentStatus.into());
  490. }
  491. }
  492. }
  493. // If the stream is exhausted without a final status
  494. Err(Error::UnknownPaymentStatus.into())
  495. }
  496. }