lib.rs 20 KB

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