lib.rs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. //! CDK lightning backend for LND
  2. // Copyright (c) 2023 Steffen (MIT)
  3. #![warn(missing_docs)]
  4. #![warn(rustdoc::bare_urls)]
  5. use std::cmp::max;
  6. use std::path::PathBuf;
  7. use std::pin::Pin;
  8. use std::str::FromStr;
  9. use std::sync::atomic::{AtomicBool, Ordering};
  10. use std::sync::Arc;
  11. use anyhow::anyhow;
  12. use async_trait::async_trait;
  13. use cdk::amount::{to_unit, Amount, MSAT_IN_SAT};
  14. use cdk::cdk_payment::{
  15. self, Bolt11Settings, CreateIncomingPaymentResponse, MakePaymentResponse, MintPayment,
  16. PaymentQuoteResponse,
  17. };
  18. use cdk::nuts::{CurrencyUnit, MeltOptions, MeltQuoteState, MintQuoteState};
  19. use cdk::secp256k1::hashes::Hash;
  20. use cdk::types::FeeReserve;
  21. use cdk::util::hex;
  22. use cdk::{mint, Bolt11Invoice};
  23. use error::Error;
  24. use fedimint_tonic_lnd::lnrpc::fee_limit::Limit;
  25. use fedimint_tonic_lnd::lnrpc::payment::PaymentStatus;
  26. use fedimint_tonic_lnd::lnrpc::{FeeLimit, Hop, HtlcAttempt, MppRecord};
  27. use fedimint_tonic_lnd::tonic::Code;
  28. use fedimint_tonic_lnd::Client;
  29. use futures::{Stream, StreamExt};
  30. use tokio::sync::Mutex;
  31. use tokio_util::sync::CancellationToken;
  32. use tracing::instrument;
  33. pub mod error;
  34. /// Lnd mint backend
  35. #[derive(Clone)]
  36. pub struct Lnd {
  37. address: String,
  38. cert_file: PathBuf,
  39. macaroon_file: PathBuf,
  40. client: Arc<Mutex<Client>>,
  41. fee_reserve: FeeReserve,
  42. wait_invoice_cancel_token: CancellationToken,
  43. wait_invoice_is_active: Arc<AtomicBool>,
  44. settings: Bolt11Settings,
  45. }
  46. impl Lnd {
  47. /// Create new [`Lnd`]
  48. pub async fn new(
  49. address: String,
  50. cert_file: PathBuf,
  51. macaroon_file: PathBuf,
  52. fee_reserve: FeeReserve,
  53. ) -> Result<Self, Error> {
  54. // Validate address is not empty
  55. if address.is_empty() {
  56. return Err(Error::InvalidConfig("LND address cannot be empty".into()));
  57. }
  58. // Validate cert_file exists and is not empty
  59. if !cert_file.exists() || cert_file.metadata().map(|m| m.len() == 0).unwrap_or(true) {
  60. return Err(Error::InvalidConfig(format!(
  61. "LND certificate file not found or empty: {:?}",
  62. cert_file
  63. )));
  64. }
  65. // Validate macaroon_file exists and is not empty
  66. if !macaroon_file.exists()
  67. || macaroon_file
  68. .metadata()
  69. .map(|m| m.len() == 0)
  70. .unwrap_or(true)
  71. {
  72. return Err(Error::InvalidConfig(format!(
  73. "LND macaroon file not found or empty: {:?}",
  74. macaroon_file
  75. )));
  76. }
  77. let client = fedimint_tonic_lnd::connect(address.to_string(), &cert_file, &macaroon_file)
  78. .await
  79. .map_err(|err| {
  80. tracing::error!("Connection error: {}", err.to_string());
  81. Error::Connection
  82. })?;
  83. Ok(Self {
  84. address,
  85. cert_file,
  86. macaroon_file,
  87. client: Arc::new(Mutex::new(client)),
  88. fee_reserve,
  89. wait_invoice_cancel_token: CancellationToken::new(),
  90. wait_invoice_is_active: Arc::new(AtomicBool::new(false)),
  91. settings: Bolt11Settings {
  92. mpp: true,
  93. unit: CurrencyUnit::Msat,
  94. invoice_description: true,
  95. },
  96. })
  97. }
  98. }
  99. #[async_trait]
  100. impl MintPayment for Lnd {
  101. type Err = cdk_payment::Error;
  102. #[instrument(skip_all)]
  103. async fn get_settings(&self) -> Result<serde_json::Value, Self::Err> {
  104. Ok(serde_json::to_value(&self.settings)?)
  105. }
  106. #[instrument(skip_all)]
  107. fn is_wait_invoice_active(&self) -> bool {
  108. self.wait_invoice_is_active.load(Ordering::SeqCst)
  109. }
  110. #[instrument(skip_all)]
  111. fn cancel_wait_invoice(&self) {
  112. self.wait_invoice_cancel_token.cancel()
  113. }
  114. #[instrument(skip_all)]
  115. async fn wait_any_incoming_payment(
  116. &self,
  117. ) -> Result<Pin<Box<dyn Stream<Item = String> + Send>>, Self::Err> {
  118. let mut client =
  119. fedimint_tonic_lnd::connect(self.address.clone(), &self.cert_file, &self.macaroon_file)
  120. .await
  121. .map_err(|_| Error::Connection)?;
  122. let stream_req = fedimint_tonic_lnd::lnrpc::InvoiceSubscription {
  123. add_index: 0,
  124. settle_index: 0,
  125. };
  126. let stream = 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. // Create a request for the routes
  246. let route_req = fedimint_tonic_lnd::lnrpc::QueryRoutesRequest {
  247. pub_key: hex::encode(pub_key.serialize()),
  248. amt_msat: u64::from(partial_amount_msat) as i64,
  249. fee_limit: max_fee.map(|f| {
  250. let limit = Limit::Fixed(u64::from(f) as i64);
  251. FeeLimit { limit: Some(limit) }
  252. }),
  253. ..Default::default()
  254. };
  255. // Query the routes
  256. let routes_response: fedimint_tonic_lnd::lnrpc::QueryRoutesResponse = self
  257. .client
  258. .lock()
  259. .await
  260. .lightning()
  261. .query_routes(route_req)
  262. .await
  263. .map_err(Error::LndError)?
  264. .into_inner();
  265. let mut payment_response: HtlcAttempt = HtlcAttempt {
  266. ..Default::default()
  267. };
  268. // For each route:
  269. // update its MPP record,
  270. // attempt it and check the result
  271. for mut route in routes_response.routes.into_iter() {
  272. let last_hop: &mut Hop = route.hops.last_mut().ok_or(Error::MissingLastHop)?;
  273. let mpp_record = MppRecord {
  274. payment_addr: payer_addr.clone(),
  275. total_amt_msat: amount_msat as i64,
  276. };
  277. last_hop.mpp_record = Some(mpp_record);
  278. tracing::debug!("sendToRouteV2 needle");
  279. payment_response = self
  280. .client
  281. .lock()
  282. .await
  283. .router()
  284. .send_to_route_v2(fedimint_tonic_lnd::routerrpc::SendToRouteRequest {
  285. payment_hash: payment_hash.to_byte_array().to_vec(),
  286. route: Some(route),
  287. ..Default::default()
  288. })
  289. .await
  290. .map_err(Error::LndError)?
  291. .into_inner();
  292. if let Some(failure) = payment_response.failure {
  293. if failure.code == 15 {
  294. // Try a different route
  295. continue;
  296. }
  297. } else {
  298. break;
  299. }
  300. }
  301. // Get status and maybe the preimage
  302. let (status, payment_preimage) = match payment_response.status {
  303. 0 => (MeltQuoteState::Pending, None),
  304. 1 => (
  305. MeltQuoteState::Paid,
  306. Some(hex::encode(payment_response.preimage)),
  307. ),
  308. 2 => (MeltQuoteState::Unpaid, None),
  309. _ => (MeltQuoteState::Unknown, None),
  310. };
  311. // Get the actual amount paid in sats
  312. let mut total_amt: u64 = 0;
  313. if let Some(route) = payment_response.route {
  314. total_amt = (route.total_amt_msat / 1000) as u64;
  315. }
  316. Ok(MakePaymentResponse {
  317. payment_lookup_id: hex::encode(payment_hash),
  318. payment_proof: payment_preimage,
  319. status,
  320. total_spent: total_amt.into(),
  321. unit: CurrencyUnit::Sat,
  322. })
  323. }
  324. None => {
  325. let pay_req = fedimint_tonic_lnd::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 = self
  335. .client
  336. .lock()
  337. .await
  338. .lightning()
  339. .send_payment_sync(fedimint_tonic_lnd::tonic::Request::new(pay_req))
  340. .await
  341. .map_err(|err| {
  342. tracing::warn!("Lightning payment failed: {}", err);
  343. Error::PaymentFailed
  344. })?
  345. .into_inner();
  346. let total_amount = payment_response
  347. .payment_route
  348. .map_or(0, |route| route.total_amt_msat / MSAT_IN_SAT as i64)
  349. as u64;
  350. let (status, payment_preimage) = match total_amount == 0 {
  351. true => (MeltQuoteState::Unpaid, None),
  352. false => (
  353. MeltQuoteState::Paid,
  354. Some(hex::encode(payment_response.payment_preimage)),
  355. ),
  356. };
  357. Ok(MakePaymentResponse {
  358. payment_lookup_id: hex::encode(payment_response.payment_hash),
  359. payment_proof: payment_preimage,
  360. status,
  361. total_spent: total_amount.into(),
  362. unit: CurrencyUnit::Sat,
  363. })
  364. }
  365. }
  366. }
  367. #[instrument(skip(self, description))]
  368. async fn create_incoming_payment_request(
  369. &self,
  370. amount: Amount,
  371. unit: &CurrencyUnit,
  372. description: String,
  373. unix_expiry: Option<u64>,
  374. ) -> Result<CreateIncomingPaymentResponse, Self::Err> {
  375. let amount = to_unit(amount, unit, &CurrencyUnit::Msat)?;
  376. let invoice_request = fedimint_tonic_lnd::lnrpc::Invoice {
  377. value_msat: u64::from(amount) as i64,
  378. memo: description,
  379. ..Default::default()
  380. };
  381. let invoice = self
  382. .client
  383. .lock()
  384. .await
  385. .lightning()
  386. .add_invoice(fedimint_tonic_lnd::tonic::Request::new(invoice_request))
  387. .await
  388. .unwrap()
  389. .into_inner();
  390. let bolt11 = Bolt11Invoice::from_str(&invoice.payment_request)?;
  391. Ok(CreateIncomingPaymentResponse {
  392. request_lookup_id: bolt11.payment_hash().to_string(),
  393. request: bolt11.to_string(),
  394. expiry: unix_expiry,
  395. })
  396. }
  397. #[instrument(skip(self))]
  398. async fn check_incoming_payment_status(
  399. &self,
  400. request_lookup_id: &str,
  401. ) -> Result<MintQuoteState, Self::Err> {
  402. let invoice_request = fedimint_tonic_lnd::lnrpc::PaymentHash {
  403. r_hash: hex::decode(request_lookup_id).unwrap(),
  404. ..Default::default()
  405. };
  406. let invoice = self
  407. .client
  408. .lock()
  409. .await
  410. .lightning()
  411. .lookup_invoice(fedimint_tonic_lnd::tonic::Request::new(invoice_request))
  412. .await
  413. .unwrap()
  414. .into_inner();
  415. match invoice.state {
  416. // Open
  417. 0 => Ok(MintQuoteState::Unpaid),
  418. // Settled
  419. 1 => Ok(MintQuoteState::Paid),
  420. // Canceled
  421. 2 => Ok(MintQuoteState::Unpaid),
  422. // Accepted
  423. 3 => Ok(MintQuoteState::Unpaid),
  424. _ => Err(Self::Err::Anyhow(anyhow!("Invalid status"))),
  425. }
  426. }
  427. #[instrument(skip(self))]
  428. async fn check_outgoing_payment(
  429. &self,
  430. payment_hash: &str,
  431. ) -> Result<MakePaymentResponse, Self::Err> {
  432. let track_request = fedimint_tonic_lnd::routerrpc::TrackPaymentRequest {
  433. payment_hash: hex::decode(payment_hash).map_err(|_| Error::InvalidHash)?,
  434. no_inflight_updates: true,
  435. };
  436. let payment_response = self
  437. .client
  438. .lock()
  439. .await
  440. .router()
  441. .track_payment_v2(track_request)
  442. .await;
  443. let mut payment_stream = match payment_response {
  444. Ok(stream) => stream.into_inner(),
  445. Err(err) => {
  446. let err_code = err.code();
  447. if err_code == Code::NotFound {
  448. return Ok(MakePaymentResponse {
  449. payment_lookup_id: payment_hash.to_string(),
  450. payment_proof: None,
  451. status: MeltQuoteState::Unknown,
  452. total_spent: Amount::ZERO,
  453. unit: self.settings.unit.clone(),
  454. });
  455. } else {
  456. return Err(cdk_payment::Error::UnknownPaymentState);
  457. }
  458. }
  459. };
  460. while let Some(update_result) = payment_stream.next().await {
  461. match update_result {
  462. Ok(update) => {
  463. let status = update.status();
  464. let response = match status {
  465. PaymentStatus::Unknown => MakePaymentResponse {
  466. payment_lookup_id: payment_hash.to_string(),
  467. payment_proof: Some(update.payment_preimage),
  468. status: MeltQuoteState::Unknown,
  469. total_spent: Amount::ZERO,
  470. unit: self.settings.unit.clone(),
  471. },
  472. PaymentStatus::InFlight => {
  473. // Continue waiting for the next update
  474. continue;
  475. }
  476. PaymentStatus::Succeeded => MakePaymentResponse {
  477. payment_lookup_id: payment_hash.to_string(),
  478. payment_proof: Some(update.payment_preimage),
  479. status: MeltQuoteState::Paid,
  480. total_spent: Amount::from(
  481. (update
  482. .value_sat
  483. .checked_add(update.fee_sat)
  484. .ok_or(Error::AmountOverflow)?)
  485. as u64,
  486. ),
  487. unit: CurrencyUnit::Sat,
  488. },
  489. PaymentStatus::Failed => MakePaymentResponse {
  490. payment_lookup_id: payment_hash.to_string(),
  491. payment_proof: Some(update.payment_preimage),
  492. status: MeltQuoteState::Failed,
  493. total_spent: Amount::ZERO,
  494. unit: self.settings.unit.clone(),
  495. },
  496. };
  497. return Ok(response);
  498. }
  499. Err(_) => {
  500. // Handle the case where the update itself is an error (e.g., stream failure)
  501. return Err(Error::UnknownPaymentStatus.into());
  502. }
  503. }
  504. }
  505. // If the stream is exhausted without a final status
  506. Err(Error::UnknownPaymentStatus.into())
  507. }
  508. }