lib.rs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  1. //! CDK lightning backend for LND
  2. // Copyright (c) 2023 Steffen (MIT)
  3. #![doc = include_str!("../README.md")]
  4. use std::cmp::max;
  5. use std::path::PathBuf;
  6. use std::pin::Pin;
  7. use std::str::FromStr;
  8. use std::sync::atomic::{AtomicBool, Ordering};
  9. use std::sync::Arc;
  10. use anyhow::anyhow;
  11. use async_trait::async_trait;
  12. use cdk_common::amount::{Amount, MSAT_IN_SAT};
  13. use cdk_common::bitcoin::hashes::Hash;
  14. use cdk_common::common::FeeReserve;
  15. use cdk_common::database::DynKVStore;
  16. use cdk_common::nuts::{CurrencyUnit, MeltOptions, MeltQuoteState};
  17. use cdk_common::payment::{
  18. self, CreateIncomingPaymentResponse, Event, IncomingPaymentOptions, MakePaymentResponse,
  19. MintPayment, OutgoingPaymentOptions, PaymentIdentifier, PaymentQuoteResponse, SettingsResponse,
  20. WaitPaymentResponse,
  21. };
  22. use cdk_common::util::hex;
  23. use cdk_common::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. use crate::lnrpc::invoice::InvoiceState;
  36. /// LND KV Store constants
  37. const LND_KV_PRIMARY_NAMESPACE: &str = "cdk_lnd_lightning_backend";
  38. const LND_KV_SECONDARY_NAMESPACE: &str = "payment_indices";
  39. const LAST_ADD_INDEX_KV_KEY: &str = "last_add_index";
  40. const LAST_SETTLE_INDEX_KV_KEY: &str = "last_settle_index";
  41. /// Lnd mint backend
  42. #[derive(Clone)]
  43. pub struct Lnd {
  44. _address: String,
  45. _cert_file: PathBuf,
  46. _macaroon_file: PathBuf,
  47. lnd_client: client::Client,
  48. fee_reserve: FeeReserve,
  49. kv_store: DynKVStore,
  50. wait_invoice_cancel_token: CancellationToken,
  51. wait_invoice_is_active: Arc<AtomicBool>,
  52. settings: SettingsResponse,
  53. unit: CurrencyUnit,
  54. }
  55. impl Lnd {
  56. /// Maximum number of attempts at a partial payment
  57. pub const MAX_ROUTE_RETRIES: usize = 50;
  58. /// Create new [`Lnd`]
  59. pub async fn new(
  60. address: String,
  61. cert_file: PathBuf,
  62. macaroon_file: PathBuf,
  63. fee_reserve: FeeReserve,
  64. kv_store: DynKVStore,
  65. ) -> Result<Self, Error> {
  66. // Validate address is not empty
  67. if address.is_empty() {
  68. return Err(Error::InvalidConfig("LND address cannot be empty".into()));
  69. }
  70. // Validate cert_file exists and is not empty
  71. if !cert_file.exists() || cert_file.metadata().map(|m| m.len() == 0).unwrap_or(true) {
  72. return Err(Error::InvalidConfig(format!(
  73. "LND certificate file not found or empty: {cert_file:?}"
  74. )));
  75. }
  76. // Validate macaroon_file exists and is not empty
  77. if !macaroon_file.exists()
  78. || macaroon_file
  79. .metadata()
  80. .map(|m| m.len() == 0)
  81. .unwrap_or(true)
  82. {
  83. return Err(Error::InvalidConfig(format!(
  84. "LND macaroon file not found or empty: {macaroon_file:?}"
  85. )));
  86. }
  87. let lnd_client = client::connect(&address, &cert_file, &macaroon_file)
  88. .await
  89. .map_err(|err| {
  90. tracing::error!("Connection error: {}", err.to_string());
  91. Error::Connection
  92. })?;
  93. let unit = CurrencyUnit::Msat;
  94. Ok(Self {
  95. _address: address,
  96. _cert_file: cert_file,
  97. _macaroon_file: macaroon_file,
  98. lnd_client,
  99. fee_reserve,
  100. kv_store,
  101. wait_invoice_cancel_token: CancellationToken::new(),
  102. wait_invoice_is_active: Arc::new(AtomicBool::new(false)),
  103. settings: SettingsResponse {
  104. unit: unit.to_string(),
  105. bolt11: Some(payment::Bolt11Settings {
  106. mpp: true,
  107. amountless: true,
  108. invoice_description: true,
  109. }),
  110. bolt12: None,
  111. custom: std::collections::HashMap::new(),
  112. },
  113. unit,
  114. })
  115. }
  116. /// Get last add and settle indices from KV store
  117. #[instrument(skip_all)]
  118. async fn get_last_indices(&self) -> Result<(Option<u64>, Option<u64>), Error> {
  119. let add_index = if let Some(stored_index) = self
  120. .kv_store
  121. .kv_read(
  122. LND_KV_PRIMARY_NAMESPACE,
  123. LND_KV_SECONDARY_NAMESPACE,
  124. LAST_ADD_INDEX_KV_KEY,
  125. )
  126. .await
  127. .map_err(|e| Error::Database(e.to_string()))?
  128. {
  129. if let Ok(index_str) = std::str::from_utf8(stored_index.as_slice()) {
  130. index_str.parse::<u64>().ok()
  131. } else {
  132. None
  133. }
  134. } else {
  135. None
  136. };
  137. let settle_index = if let Some(stored_index) = self
  138. .kv_store
  139. .kv_read(
  140. LND_KV_PRIMARY_NAMESPACE,
  141. LND_KV_SECONDARY_NAMESPACE,
  142. LAST_SETTLE_INDEX_KV_KEY,
  143. )
  144. .await
  145. .map_err(|e| Error::Database(e.to_string()))?
  146. {
  147. if let Ok(index_str) = std::str::from_utf8(stored_index.as_slice()) {
  148. index_str.parse::<u64>().ok()
  149. } else {
  150. None
  151. }
  152. } else {
  153. None
  154. };
  155. tracing::debug!(
  156. "LND: Retrieved last indices from KV store - add_index: {:?}, settle_index: {:?}",
  157. add_index,
  158. settle_index
  159. );
  160. Ok((add_index, settle_index))
  161. }
  162. }
  163. #[async_trait]
  164. impl MintPayment for Lnd {
  165. type Err = payment::Error;
  166. #[instrument(skip_all)]
  167. async fn get_settings(&self) -> Result<SettingsResponse, Self::Err> {
  168. Ok(self.settings.clone())
  169. }
  170. #[instrument(skip_all)]
  171. fn is_wait_invoice_active(&self) -> bool {
  172. self.wait_invoice_is_active.load(Ordering::SeqCst)
  173. }
  174. #[instrument(skip_all)]
  175. fn cancel_wait_invoice(&self) {
  176. self.wait_invoice_cancel_token.cancel()
  177. }
  178. #[instrument(skip_all)]
  179. async fn wait_payment_event(
  180. &self,
  181. ) -> Result<Pin<Box<dyn Stream<Item = Event> + Send>>, Self::Err> {
  182. let mut lnd_client = self.lnd_client.clone();
  183. // Get last indices from KV store
  184. let (last_add_index, last_settle_index) =
  185. self.get_last_indices().await.unwrap_or((None, None));
  186. let stream_req = lnrpc::InvoiceSubscription {
  187. add_index: last_add_index.unwrap_or(0),
  188. settle_index: last_settle_index.unwrap_or(0),
  189. };
  190. tracing::debug!(
  191. "LND: Starting invoice subscription with add_index: {}, settle_index: {}",
  192. stream_req.add_index,
  193. stream_req.settle_index
  194. );
  195. let stream = lnd_client
  196. .lightning()
  197. .subscribe_invoices(stream_req)
  198. .await
  199. .map_err(|_err| {
  200. tracing::error!("Could not subscribe to invoice");
  201. Error::Connection
  202. })?
  203. .into_inner();
  204. let cancel_token = self.wait_invoice_cancel_token.clone();
  205. let kv_store = self.kv_store.clone();
  206. let event_stream = futures::stream::unfold(
  207. (
  208. stream,
  209. cancel_token,
  210. Arc::clone(&self.wait_invoice_is_active),
  211. kv_store,
  212. last_add_index.unwrap_or(0),
  213. last_settle_index.unwrap_or(0),
  214. ),
  215. |(
  216. mut stream,
  217. cancel_token,
  218. is_active,
  219. kv_store,
  220. mut current_add_index,
  221. mut current_settle_index,
  222. )| async move {
  223. is_active.store(true, Ordering::SeqCst);
  224. loop {
  225. tokio::select! {
  226. _ = cancel_token.cancelled() => {
  227. // Stream is cancelled
  228. is_active.store(false, Ordering::SeqCst);
  229. tracing::info!("Waiting for lnd invoice ending");
  230. return None;
  231. }
  232. msg = stream.message() => {
  233. match msg {
  234. Ok(Some(msg)) => {
  235. // Update indices based on the message
  236. current_add_index = current_add_index.max(msg.add_index);
  237. current_settle_index = current_settle_index.max(msg.settle_index);
  238. // Store the updated indices in KV store regardless of settlement status
  239. let add_index_str = current_add_index.to_string();
  240. let settle_index_str = current_settle_index.to_string();
  241. if let Ok(mut tx) = kv_store.begin_transaction().await {
  242. let mut has_error = false;
  243. if let Err(e) = tx.kv_write(LND_KV_PRIMARY_NAMESPACE, LND_KV_SECONDARY_NAMESPACE, LAST_ADD_INDEX_KV_KEY, add_index_str.as_bytes()).await {
  244. tracing::warn!("LND: Failed to write add_index {} to KV store: {}", current_add_index, e);
  245. has_error = true;
  246. }
  247. if let Err(e) = tx.kv_write(LND_KV_PRIMARY_NAMESPACE, LND_KV_SECONDARY_NAMESPACE, LAST_SETTLE_INDEX_KV_KEY, settle_index_str.as_bytes()).await {
  248. tracing::warn!("LND: Failed to write settle_index {} to KV store: {}", current_settle_index, e);
  249. has_error = true;
  250. }
  251. if !has_error {
  252. if let Err(e) = tx.commit().await {
  253. tracing::warn!("LND: Failed to commit indices to KV store: {}", e);
  254. } else {
  255. tracing::debug!("LND: Stored updated indices - add_index: {}, settle_index: {}", current_add_index, current_settle_index);
  256. }
  257. }
  258. } else {
  259. tracing::warn!("LND: Failed to begin KV transaction for storing indices");
  260. }
  261. // Only emit event for settled invoices
  262. if msg.state() == InvoiceState::Settled {
  263. let hash_slice: Result<[u8;32], _> = msg.r_hash.try_into();
  264. if let Ok(hash_slice) = hash_slice {
  265. let hash = hex::encode(hash_slice);
  266. tracing::info!("LND: Payment for {} with amount {} msat", hash, msg.amt_paid_msat);
  267. let wait_response = WaitPaymentResponse {
  268. payment_identifier: PaymentIdentifier::PaymentHash(hash_slice),
  269. payment_amount: Amount::new(msg.amt_paid_msat as u64, CurrencyUnit::Msat),
  270. payment_id: hash,
  271. };
  272. let event = Event::PaymentReceived(wait_response);
  273. return Some((event, (stream, cancel_token, is_active, kv_store, current_add_index, current_settle_index)));
  274. } else {
  275. // Invalid hash, skip this message but continue streaming
  276. tracing::error!("LND returned invalid payment hash");
  277. // Continue the loop without yielding
  278. continue;
  279. }
  280. } else {
  281. // Not a settled invoice, continue but don't emit event
  282. tracing::debug!("LND: Received non-settled invoice, continuing to wait for settled invoices");
  283. // Continue the loop without yielding
  284. continue;
  285. }
  286. }
  287. Ok(None) => {
  288. is_active.store(false, Ordering::SeqCst);
  289. tracing::info!("LND invoice stream ended.");
  290. return None;
  291. }
  292. Err(err) => {
  293. is_active.store(false, Ordering::SeqCst);
  294. tracing::warn!("Encountered error in LND invoice stream. Stream ending");
  295. tracing::error!("{:?}", err);
  296. return None;
  297. }
  298. }
  299. }
  300. }
  301. }
  302. },
  303. );
  304. Ok(Box::pin(event_stream))
  305. }
  306. #[instrument(skip_all)]
  307. async fn get_payment_quote(
  308. &self,
  309. unit: &CurrencyUnit,
  310. options: OutgoingPaymentOptions,
  311. ) -> Result<PaymentQuoteResponse, Self::Err> {
  312. match options {
  313. OutgoingPaymentOptions::Bolt11(bolt11_options) => {
  314. let amount_msat = match bolt11_options.melt_options {
  315. Some(amount) => amount.amount_msat(),
  316. None => bolt11_options
  317. .bolt11
  318. .amount_milli_satoshis()
  319. .ok_or(Error::UnknownInvoiceAmount)?
  320. .into(),
  321. };
  322. let amount =
  323. Amount::new(amount_msat.into(), CurrencyUnit::Msat).convert_to(unit)?;
  324. let relative_fee_reserve =
  325. (self.fee_reserve.percent_fee_reserve * amount.value() as f32) as u64;
  326. let absolute_fee_reserve: u64 = self.fee_reserve.min_fee_reserve.into();
  327. let fee = max(relative_fee_reserve, absolute_fee_reserve);
  328. Ok(PaymentQuoteResponse {
  329. request_lookup_id: Some(PaymentIdentifier::PaymentHash(
  330. *bolt11_options.bolt11.payment_hash().as_ref(),
  331. )),
  332. amount,
  333. fee: Amount::new(fee, unit.clone()),
  334. state: MeltQuoteState::Unpaid,
  335. })
  336. }
  337. OutgoingPaymentOptions::Bolt12(_) => {
  338. Err(Self::Err::Anyhow(anyhow!("BOLT12 not supported by LND")))
  339. }
  340. OutgoingPaymentOptions::Custom(_) => Err(payment::Error::UnsupportedPaymentOption),
  341. }
  342. }
  343. #[instrument(skip_all)]
  344. async fn make_payment(
  345. &self,
  346. _unit: &CurrencyUnit,
  347. options: OutgoingPaymentOptions,
  348. ) -> Result<MakePaymentResponse, Self::Err> {
  349. match options {
  350. OutgoingPaymentOptions::Bolt11(bolt11_options) => {
  351. let bolt11 = bolt11_options.bolt11;
  352. let pay_state = self
  353. .check_outgoing_payment(&PaymentIdentifier::PaymentHash(
  354. *bolt11.payment_hash().as_ref(),
  355. ))
  356. .await?;
  357. match pay_state.status {
  358. MeltQuoteState::Unpaid | MeltQuoteState::Unknown | MeltQuoteState::Failed => (),
  359. MeltQuoteState::Paid => {
  360. tracing::debug!("Melt attempted on invoice already paid");
  361. return Err(Self::Err::InvoiceAlreadyPaid);
  362. }
  363. MeltQuoteState::Pending => {
  364. tracing::debug!("Melt attempted on invoice already pending");
  365. return Err(Self::Err::InvoicePaymentPending);
  366. }
  367. }
  368. // Detect partial payments
  369. match bolt11_options.melt_options {
  370. Some(MeltOptions::Mpp { mpp }) => {
  371. let amount_msat: u64 = bolt11
  372. .amount_milli_satoshis()
  373. .ok_or(Error::UnknownInvoiceAmount)?;
  374. {
  375. let partial_amount_msat = mpp.amount;
  376. let invoice = bolt11;
  377. let max_fee: Option<Amount> = bolt11_options.max_fee_amount;
  378. // Extract information from invoice
  379. let pub_key = invoice.get_payee_pub_key();
  380. let payer_addr = invoice.payment_secret().0.to_vec();
  381. let payment_hash = invoice.payment_hash();
  382. let mut lnd_client = self.lnd_client.clone();
  383. for attempt in 0..Self::MAX_ROUTE_RETRIES {
  384. // Create a request for the routes
  385. let route_req = lnrpc::QueryRoutesRequest {
  386. pub_key: hex::encode(pub_key.serialize()),
  387. amt_msat: u64::from(partial_amount_msat) as i64,
  388. fee_limit: max_fee.map(|f| {
  389. let limit = Limit::Fixed(u64::from(f) as i64);
  390. FeeLimit { limit: Some(limit) }
  391. }),
  392. use_mission_control: true,
  393. ..Default::default()
  394. };
  395. // Query the routes
  396. let mut routes_response = lnd_client
  397. .lightning()
  398. .query_routes(route_req)
  399. .await
  400. .map_err(Error::LndError)?
  401. .into_inner();
  402. // update its MPP record,
  403. // attempt it and check the result
  404. let last_hop: &mut Hop = routes_response.routes[0]
  405. .hops
  406. .last_mut()
  407. .ok_or(Error::MissingLastHop)?;
  408. let mpp_record = MppRecord {
  409. payment_addr: payer_addr.clone(),
  410. total_amt_msat: amount_msat as i64,
  411. };
  412. last_hop.mpp_record = Some(mpp_record);
  413. let payment_response = lnd_client
  414. .router()
  415. .send_to_route_v2(routerrpc::SendToRouteRequest {
  416. payment_hash: payment_hash.to_byte_array().to_vec(),
  417. route: Some(routes_response.routes[0].clone()),
  418. ..Default::default()
  419. })
  420. .await
  421. .map_err(Error::LndError)?
  422. .into_inner();
  423. if let Some(failure) = payment_response.failure {
  424. if failure.code == 15 {
  425. tracing::debug!(
  426. "Attempt number {}: route has failed. Re-querying...",
  427. attempt + 1
  428. );
  429. continue;
  430. }
  431. }
  432. // Get status and maybe the preimage
  433. let (status, payment_preimage) = match payment_response.status {
  434. 0 => (MeltQuoteState::Pending, None),
  435. 1 => (
  436. MeltQuoteState::Paid,
  437. Some(hex::encode(payment_response.preimage)),
  438. ),
  439. 2 => (MeltQuoteState::Unpaid, None),
  440. _ => (MeltQuoteState::Unknown, None),
  441. };
  442. // Get the actual amount paid in sats
  443. let mut total_amt: u64 = 0;
  444. if let Some(route) = payment_response.route {
  445. total_amt = (route.total_amt_msat / 1000) as u64;
  446. }
  447. return Ok(MakePaymentResponse {
  448. payment_lookup_id: PaymentIdentifier::PaymentHash(
  449. payment_hash.to_byte_array(),
  450. ),
  451. payment_proof: payment_preimage,
  452. status,
  453. total_spent: Amount::new(total_amt, CurrencyUnit::Sat),
  454. });
  455. }
  456. // "We have exhausted all tactical options" -- STEM, Upgrade (2018)
  457. // The payment was not possible within 50 retries.
  458. tracing::error!("Limit of retries reached, payment couldn't succeed.");
  459. Err(Error::PaymentFailed.into())
  460. }
  461. }
  462. _ => {
  463. let mut lnd_client = self.lnd_client.clone();
  464. let max_fee: Option<Amount> = bolt11_options.max_fee_amount;
  465. let amount_msat = u64::from(
  466. bolt11_options
  467. .melt_options
  468. .map(|a| a.amount_msat())
  469. .unwrap_or_default(),
  470. );
  471. let pay_req = lnrpc::SendRequest {
  472. payment_request: bolt11.to_string(),
  473. fee_limit: max_fee.map(|f| {
  474. let limit = Limit::Fixed(u64::from(f) as i64);
  475. FeeLimit { limit: Some(limit) }
  476. }),
  477. amt_msat: amount_msat as i64,
  478. ..Default::default()
  479. };
  480. let payment_response = lnd_client
  481. .lightning()
  482. .send_payment_sync(tonic::Request::new(pay_req))
  483. .await
  484. .map_err(|err| {
  485. tracing::warn!("Lightning payment failed: {}", err);
  486. Error::PaymentFailed
  487. })?
  488. .into_inner();
  489. let total_amount = payment_response
  490. .payment_route
  491. .map_or(0, |route| route.total_amt_msat / MSAT_IN_SAT as i64)
  492. as u64;
  493. let (status, payment_preimage) = match total_amount == 0 {
  494. true => (MeltQuoteState::Unpaid, None),
  495. false => (
  496. MeltQuoteState::Paid,
  497. Some(hex::encode(payment_response.payment_preimage)),
  498. ),
  499. };
  500. let payment_identifier =
  501. PaymentIdentifier::PaymentHash(*bolt11.payment_hash().as_ref());
  502. Ok(MakePaymentResponse {
  503. payment_lookup_id: payment_identifier,
  504. payment_proof: payment_preimage,
  505. status,
  506. total_spent: Amount::new(total_amount, CurrencyUnit::Sat),
  507. })
  508. }
  509. }
  510. }
  511. OutgoingPaymentOptions::Bolt12(_) => {
  512. Err(Self::Err::Anyhow(anyhow!("BOLT12 not supported by LND")))
  513. }
  514. OutgoingPaymentOptions::Custom(_) => Err(payment::Error::UnsupportedPaymentOption),
  515. }
  516. }
  517. #[instrument(skip(self, options))]
  518. async fn create_incoming_payment_request(
  519. &self,
  520. unit: &CurrencyUnit,
  521. options: IncomingPaymentOptions,
  522. ) -> Result<CreateIncomingPaymentResponse, Self::Err> {
  523. match options {
  524. IncomingPaymentOptions::Bolt11(bolt11_options) => {
  525. let description = bolt11_options.description.unwrap_or_default();
  526. let amount = bolt11_options.amount;
  527. let unix_expiry = bolt11_options.unix_expiry;
  528. let amount_msat: Amount = Amount::new(amount.into(), unit.clone())
  529. .convert_to(&CurrencyUnit::Msat)?
  530. .into();
  531. let invoice_request = lnrpc::Invoice {
  532. value_msat: u64::from(amount_msat) as i64,
  533. memo: description,
  534. ..Default::default()
  535. };
  536. let mut lnd_client = self.lnd_client.clone();
  537. let invoice = lnd_client
  538. .lightning()
  539. .add_invoice(tonic::Request::new(invoice_request))
  540. .await
  541. .map_err(|e| payment::Error::Anyhow(anyhow!(e)))?
  542. .into_inner();
  543. let bolt11 = Bolt11Invoice::from_str(&invoice.payment_request)?;
  544. let payment_identifier =
  545. PaymentIdentifier::PaymentHash(*bolt11.payment_hash().as_ref());
  546. Ok(CreateIncomingPaymentResponse {
  547. request_lookup_id: payment_identifier,
  548. request: bolt11.to_string(),
  549. expiry: unix_expiry,
  550. extra_json: None,
  551. })
  552. }
  553. IncomingPaymentOptions::Bolt12(_) => {
  554. Err(Self::Err::Anyhow(anyhow!("BOLT12 not supported by LND")))
  555. }
  556. IncomingPaymentOptions::Custom(_) => Err(payment::Error::UnsupportedPaymentOption),
  557. }
  558. }
  559. #[instrument(skip(self))]
  560. async fn check_incoming_payment_status(
  561. &self,
  562. payment_identifier: &PaymentIdentifier,
  563. ) -> Result<Vec<WaitPaymentResponse>, Self::Err> {
  564. let mut lnd_client = self.lnd_client.clone();
  565. let invoice_request = lnrpc::PaymentHash {
  566. r_hash: hex::decode(payment_identifier.to_string())?,
  567. ..Default::default()
  568. };
  569. let invoice = lnd_client
  570. .lightning()
  571. .lookup_invoice(tonic::Request::new(invoice_request))
  572. .await
  573. .map_err(|e| payment::Error::Anyhow(anyhow!(e)))?
  574. .into_inner();
  575. if invoice.state() == InvoiceState::Settled {
  576. Ok(vec![WaitPaymentResponse {
  577. payment_identifier: payment_identifier.clone(),
  578. payment_amount: Amount::new(invoice.amt_paid_msat as u64, CurrencyUnit::Msat),
  579. payment_id: hex::encode(invoice.r_hash),
  580. }])
  581. } else {
  582. Ok(vec![])
  583. }
  584. }
  585. #[instrument(skip(self))]
  586. async fn check_outgoing_payment(
  587. &self,
  588. payment_identifier: &PaymentIdentifier,
  589. ) -> Result<MakePaymentResponse, Self::Err> {
  590. let mut lnd_client = self.lnd_client.clone();
  591. let payment_hash = &payment_identifier.to_string();
  592. let track_request = routerrpc::TrackPaymentRequest {
  593. payment_hash: hex::decode(payment_hash).map_err(|_| Error::InvalidHash)?,
  594. no_inflight_updates: true,
  595. };
  596. let payment_response = lnd_client.router().track_payment_v2(track_request).await;
  597. let mut payment_stream = match payment_response {
  598. Ok(stream) => stream.into_inner(),
  599. Err(err) => {
  600. let err_code = err.code();
  601. if err_code == tonic::Code::NotFound {
  602. return Ok(MakePaymentResponse {
  603. payment_lookup_id: payment_identifier.clone(),
  604. payment_proof: None,
  605. status: MeltQuoteState::Unknown,
  606. total_spent: Amount::new(0, self.unit.clone()),
  607. });
  608. } else {
  609. return Err(payment::Error::UnknownPaymentState);
  610. }
  611. }
  612. };
  613. while let Some(update_result) = payment_stream.next().await {
  614. match update_result {
  615. Ok(update) => {
  616. let status = update.status();
  617. let response = match status {
  618. PaymentStatus::Unknown => MakePaymentResponse {
  619. payment_lookup_id: payment_identifier.clone(),
  620. payment_proof: Some(update.payment_preimage),
  621. status: MeltQuoteState::Unknown,
  622. total_spent: Amount::new(0, self.unit.clone()),
  623. },
  624. PaymentStatus::InFlight | PaymentStatus::Initiated => {
  625. // Continue waiting for the next update
  626. continue;
  627. }
  628. PaymentStatus::Succeeded => MakePaymentResponse {
  629. payment_lookup_id: payment_identifier.clone(),
  630. payment_proof: Some(update.payment_preimage),
  631. status: MeltQuoteState::Paid,
  632. total_spent: Amount::new(
  633. (update
  634. .value_sat
  635. .checked_add(update.fee_sat)
  636. .ok_or(Error::AmountOverflow)?)
  637. as u64,
  638. CurrencyUnit::Sat,
  639. ),
  640. },
  641. PaymentStatus::Failed => MakePaymentResponse {
  642. payment_lookup_id: payment_identifier.clone(),
  643. payment_proof: Some(update.payment_preimage),
  644. status: MeltQuoteState::Failed,
  645. total_spent: Amount::new(0, self.unit.clone()),
  646. },
  647. };
  648. return Ok(response);
  649. }
  650. Err(_) => {
  651. // Handle the case where the update itself is an error (e.g., stream failure)
  652. return Err(Error::UnknownPaymentStatus.into());
  653. }
  654. }
  655. }
  656. // If the stream is exhausted without a final status
  657. Err(Error::UnknownPaymentStatus.into())
  658. }
  659. }