lib.rs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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 fedimint_tonic_lnd::lnrpc::fee_limit::Limit;
  26. use fedimint_tonic_lnd::lnrpc::payment::PaymentStatus;
  27. use fedimint_tonic_lnd::lnrpc::{FeeLimit, Hop, 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. /// 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 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 = 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. for attempt in 0..Self::MAX_ROUTE_RETRIES {
  248. // Create a request for the routes
  249. let route_req = fedimint_tonic_lnd::lnrpc::QueryRoutesRequest {
  250. pub_key: hex::encode(pub_key.serialize()),
  251. amt_msat: u64::from(partial_amount_msat) as i64,
  252. fee_limit: max_fee.map(|f| {
  253. let limit = Limit::Fixed(u64::from(f) as i64);
  254. FeeLimit { limit: Some(limit) }
  255. }),
  256. use_mission_control: true,
  257. ..Default::default()
  258. };
  259. // Query the routes
  260. let mut routes_response: fedimint_tonic_lnd::lnrpc::QueryRoutesResponse = self
  261. .client
  262. .lock()
  263. .await
  264. .lightning()
  265. .query_routes(route_req)
  266. .await
  267. .map_err(Error::LndError)?
  268. .into_inner();
  269. // update its MPP record,
  270. // attempt it and check the result
  271. let last_hop: &mut Hop = routes_response.routes[0]
  272. .hops
  273. .last_mut()
  274. .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. let payment_response = self
  281. .client
  282. .lock()
  283. .await
  284. .router()
  285. .send_to_route_v2(fedimint_tonic_lnd::routerrpc::SendToRouteRequest {
  286. payment_hash: payment_hash.to_byte_array().to_vec(),
  287. route: Some(routes_response.routes[0].clone()),
  288. ..Default::default()
  289. })
  290. .await
  291. .map_err(Error::LndError)?
  292. .into_inner();
  293. if let Some(failure) = payment_response.failure {
  294. if failure.code == 15 {
  295. tracing::debug!(
  296. "Attempt number {}: route has failed. Re-querying...",
  297. attempt + 1
  298. );
  299. continue;
  300. }
  301. }
  302. // Get status and maybe the preimage
  303. let (status, payment_preimage) = match payment_response.status {
  304. 0 => (MeltQuoteState::Pending, None),
  305. 1 => (
  306. MeltQuoteState::Paid,
  307. Some(hex::encode(payment_response.preimage)),
  308. ),
  309. 2 => (MeltQuoteState::Unpaid, None),
  310. _ => (MeltQuoteState::Unknown, None),
  311. };
  312. // Get the actual amount paid in sats
  313. let mut total_amt: u64 = 0;
  314. if let Some(route) = payment_response.route {
  315. total_amt = (route.total_amt_msat / 1000) as u64;
  316. }
  317. return Ok(MakePaymentResponse {
  318. payment_lookup_id: hex::encode(payment_hash),
  319. payment_proof: payment_preimage,
  320. status,
  321. total_spent: total_amt.into(),
  322. unit: CurrencyUnit::Sat,
  323. });
  324. }
  325. // "We have exhausted all tactical options" -- STEM, Upgrade (2018)
  326. // The payment was not possible within 50 retries.
  327. tracing::error!("Limit of retries reached, payment couldn't succeed.");
  328. Err(Error::PaymentFailed.into())
  329. }
  330. None => {
  331. let pay_req = fedimint_tonic_lnd::lnrpc::SendRequest {
  332. payment_request,
  333. fee_limit: max_fee.map(|f| {
  334. let limit = Limit::Fixed(u64::from(f) as i64);
  335. FeeLimit { limit: Some(limit) }
  336. }),
  337. amt_msat: amount_msat as i64,
  338. ..Default::default()
  339. };
  340. let payment_response = self
  341. .client
  342. .lock()
  343. .await
  344. .lightning()
  345. .send_payment_sync(fedimint_tonic_lnd::tonic::Request::new(pay_req))
  346. .await
  347. .map_err(|err| {
  348. tracing::warn!("Lightning payment failed: {}", err);
  349. Error::PaymentFailed
  350. })?
  351. .into_inner();
  352. let total_amount = payment_response
  353. .payment_route
  354. .map_or(0, |route| route.total_amt_msat / MSAT_IN_SAT as i64)
  355. as u64;
  356. let (status, payment_preimage) = match total_amount == 0 {
  357. true => (MeltQuoteState::Unpaid, None),
  358. false => (
  359. MeltQuoteState::Paid,
  360. Some(hex::encode(payment_response.payment_preimage)),
  361. ),
  362. };
  363. Ok(MakePaymentResponse {
  364. payment_lookup_id: hex::encode(payment_response.payment_hash),
  365. payment_proof: payment_preimage,
  366. status,
  367. total_spent: total_amount.into(),
  368. unit: CurrencyUnit::Sat,
  369. })
  370. }
  371. }
  372. }
  373. #[instrument(skip(self, description))]
  374. async fn create_incoming_payment_request(
  375. &self,
  376. amount: Amount,
  377. unit: &CurrencyUnit,
  378. description: String,
  379. unix_expiry: Option<u64>,
  380. ) -> Result<CreateIncomingPaymentResponse, Self::Err> {
  381. let amount = to_unit(amount, unit, &CurrencyUnit::Msat)?;
  382. let invoice_request = fedimint_tonic_lnd::lnrpc::Invoice {
  383. value_msat: u64::from(amount) as i64,
  384. memo: description,
  385. ..Default::default()
  386. };
  387. let invoice = self
  388. .client
  389. .lock()
  390. .await
  391. .lightning()
  392. .add_invoice(fedimint_tonic_lnd::tonic::Request::new(invoice_request))
  393. .await
  394. .unwrap()
  395. .into_inner();
  396. let bolt11 = Bolt11Invoice::from_str(&invoice.payment_request)?;
  397. Ok(CreateIncomingPaymentResponse {
  398. request_lookup_id: bolt11.payment_hash().to_string(),
  399. request: bolt11.to_string(),
  400. expiry: unix_expiry,
  401. })
  402. }
  403. #[instrument(skip(self))]
  404. async fn check_incoming_payment_status(
  405. &self,
  406. request_lookup_id: &str,
  407. ) -> Result<MintQuoteState, Self::Err> {
  408. let invoice_request = fedimint_tonic_lnd::lnrpc::PaymentHash {
  409. r_hash: hex::decode(request_lookup_id).unwrap(),
  410. ..Default::default()
  411. };
  412. let invoice = self
  413. .client
  414. .lock()
  415. .await
  416. .lightning()
  417. .lookup_invoice(fedimint_tonic_lnd::tonic::Request::new(invoice_request))
  418. .await
  419. .unwrap()
  420. .into_inner();
  421. match invoice.state {
  422. // Open
  423. 0 => Ok(MintQuoteState::Unpaid),
  424. // Settled
  425. 1 => Ok(MintQuoteState::Paid),
  426. // Canceled
  427. 2 => Ok(MintQuoteState::Unpaid),
  428. // Accepted
  429. 3 => Ok(MintQuoteState::Unpaid),
  430. _ => Err(Self::Err::Anyhow(anyhow!("Invalid status"))),
  431. }
  432. }
  433. #[instrument(skip(self))]
  434. async fn check_outgoing_payment(
  435. &self,
  436. payment_hash: &str,
  437. ) -> Result<MakePaymentResponse, Self::Err> {
  438. let track_request = fedimint_tonic_lnd::routerrpc::TrackPaymentRequest {
  439. payment_hash: hex::decode(payment_hash).map_err(|_| Error::InvalidHash)?,
  440. no_inflight_updates: true,
  441. };
  442. let payment_response = self
  443. .client
  444. .lock()
  445. .await
  446. .router()
  447. .track_payment_v2(track_request)
  448. .await;
  449. let mut payment_stream = match payment_response {
  450. Ok(stream) => stream.into_inner(),
  451. Err(err) => {
  452. let err_code = err.code();
  453. if err_code == Code::NotFound {
  454. return Ok(MakePaymentResponse {
  455. payment_lookup_id: payment_hash.to_string(),
  456. payment_proof: None,
  457. status: MeltQuoteState::Unknown,
  458. total_spent: Amount::ZERO,
  459. unit: self.settings.unit.clone(),
  460. });
  461. } else {
  462. return Err(payment::Error::UnknownPaymentState);
  463. }
  464. }
  465. };
  466. while let Some(update_result) = payment_stream.next().await {
  467. match update_result {
  468. Ok(update) => {
  469. let status = update.status();
  470. let response = match status {
  471. PaymentStatus::Unknown => MakePaymentResponse {
  472. payment_lookup_id: payment_hash.to_string(),
  473. payment_proof: Some(update.payment_preimage),
  474. status: MeltQuoteState::Unknown,
  475. total_spent: Amount::ZERO,
  476. unit: self.settings.unit.clone(),
  477. },
  478. PaymentStatus::InFlight => {
  479. // Continue waiting for the next update
  480. continue;
  481. }
  482. PaymentStatus::Succeeded => MakePaymentResponse {
  483. payment_lookup_id: payment_hash.to_string(),
  484. payment_proof: Some(update.payment_preimage),
  485. status: MeltQuoteState::Paid,
  486. total_spent: Amount::from(
  487. (update
  488. .value_sat
  489. .checked_add(update.fee_sat)
  490. .ok_or(Error::AmountOverflow)?)
  491. as u64,
  492. ),
  493. unit: CurrencyUnit::Sat,
  494. },
  495. PaymentStatus::Failed => MakePaymentResponse {
  496. payment_lookup_id: payment_hash.to_string(),
  497. payment_proof: Some(update.payment_preimage),
  498. status: MeltQuoteState::Failed,
  499. total_spent: Amount::ZERO,
  500. unit: self.settings.unit.clone(),
  501. },
  502. };
  503. return Ok(response);
  504. }
  505. Err(_) => {
  506. // Handle the case where the update itself is an error (e.g., stream failure)
  507. return Err(Error::UnknownPaymentStatus.into());
  508. }
  509. }
  510. }
  511. // If the stream is exhausted without a final status
  512. Err(Error::UnknownPaymentStatus.into())
  513. }
  514. }