lib.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. //! CDK lightning backend for Strike
  2. #![warn(missing_docs)]
  3. #![warn(rustdoc::bare_urls)]
  4. use std::pin::Pin;
  5. use std::sync::atomic::{AtomicBool, Ordering};
  6. use std::sync::Arc;
  7. use anyhow::{anyhow, bail};
  8. use async_trait::async_trait;
  9. use axum::Router;
  10. use cdk::amount::Amount;
  11. use cdk::cdk_lightning::{
  12. self, CreateInvoiceResponse, MintLightning, PayInvoiceResponse, PaymentQuoteResponse, Settings,
  13. };
  14. use cdk::nuts::{CurrencyUnit, MeltQuoteBolt11Request, MeltQuoteState, MintQuoteState};
  15. use cdk::util::unix_time;
  16. use cdk::{mint, Bolt11Invoice};
  17. use error::Error;
  18. use futures::stream::StreamExt;
  19. use futures::Stream;
  20. use strike_rs::{
  21. Amount as StrikeAmount, Currency as StrikeCurrencyUnit, InvoiceRequest, InvoiceState,
  22. PayInvoiceQuoteRequest, Strike as StrikeApi,
  23. };
  24. use tokio::sync::Mutex;
  25. use tokio_util::sync::CancellationToken;
  26. use uuid::Uuid;
  27. pub mod error;
  28. /// Strike
  29. #[derive(Clone)]
  30. pub struct Strike {
  31. strike_api: StrikeApi,
  32. unit: CurrencyUnit,
  33. receiver: Arc<Mutex<Option<tokio::sync::mpsc::Receiver<String>>>>,
  34. webhook_url: String,
  35. wait_invoice_cancel_token: CancellationToken,
  36. wait_invoice_is_active: Arc<AtomicBool>,
  37. }
  38. impl Strike {
  39. /// Create new [`Strike`] wallet
  40. pub async fn new(
  41. api_key: String,
  42. unit: CurrencyUnit,
  43. receiver: Arc<Mutex<Option<tokio::sync::mpsc::Receiver<String>>>>,
  44. webhook_url: String,
  45. ) -> Result<Self, Error> {
  46. let strike = StrikeApi::new(&api_key, None)?;
  47. Ok(Self {
  48. strike_api: strike,
  49. receiver,
  50. unit,
  51. webhook_url,
  52. wait_invoice_cancel_token: CancellationToken::new(),
  53. wait_invoice_is_active: Arc::new(AtomicBool::new(false)),
  54. })
  55. }
  56. }
  57. #[async_trait]
  58. impl MintLightning for Strike {
  59. type Err = cdk_lightning::Error;
  60. fn get_settings(&self) -> Settings {
  61. Settings {
  62. mpp: false,
  63. unit: self.unit.clone(),
  64. invoice_description: true,
  65. }
  66. }
  67. fn is_wait_invoice_active(&self) -> bool {
  68. self.wait_invoice_is_active.load(Ordering::SeqCst)
  69. }
  70. fn cancel_wait_invoice(&self) {
  71. self.wait_invoice_cancel_token.cancel()
  72. }
  73. #[allow(clippy::incompatible_msrv)]
  74. async fn wait_any_invoice(
  75. &self,
  76. ) -> Result<Pin<Box<dyn Stream<Item = String> + Send>>, Self::Err> {
  77. self.strike_api
  78. .subscribe_to_invoice_webhook(self.webhook_url.clone())
  79. .await?;
  80. let receiver = self
  81. .receiver
  82. .lock()
  83. .await
  84. .take()
  85. .ok_or(anyhow!("No receiver"))?;
  86. let strike_api = self.strike_api.clone();
  87. let cancel_token = self.wait_invoice_cancel_token.clone();
  88. Ok(futures::stream::unfold(
  89. (
  90. receiver,
  91. strike_api,
  92. cancel_token,
  93. Arc::clone(&self.wait_invoice_is_active),
  94. ),
  95. |(mut receiver, strike_api, cancel_token, is_active)| async move {
  96. tokio::select! {
  97. _ = cancel_token.cancelled() => {
  98. // Stream is cancelled
  99. is_active.store(false, Ordering::SeqCst);
  100. tracing::info!("Waiting for phonixd invoice ending");
  101. None
  102. }
  103. msg_option = receiver.recv() => {
  104. match msg_option {
  105. Some(msg) => {
  106. let check = strike_api.get_incoming_invoice(&msg).await;
  107. match check {
  108. Ok(state) => {
  109. if state.state == InvoiceState::Paid {
  110. Some((msg, (receiver, strike_api, cancel_token, is_active)))
  111. } else {
  112. None
  113. }
  114. }
  115. _ => None,
  116. }
  117. }
  118. None => None,
  119. }
  120. }
  121. }
  122. },
  123. )
  124. .boxed())
  125. }
  126. async fn get_payment_quote(
  127. &self,
  128. melt_quote_request: &MeltQuoteBolt11Request,
  129. ) -> Result<PaymentQuoteResponse, Self::Err> {
  130. if melt_quote_request.unit != self.unit {
  131. return Err(Self::Err::Anyhow(anyhow!("Unsupported unit")));
  132. }
  133. let source_currency = match melt_quote_request.unit {
  134. CurrencyUnit::Sat => StrikeCurrencyUnit::BTC,
  135. CurrencyUnit::Msat => StrikeCurrencyUnit::BTC,
  136. CurrencyUnit::Usd => StrikeCurrencyUnit::USD,
  137. CurrencyUnit::Eur => StrikeCurrencyUnit::EUR,
  138. _ => return Err(Self::Err::UnsupportedUnit),
  139. };
  140. let payment_quote_request = PayInvoiceQuoteRequest {
  141. ln_invoice: melt_quote_request.request.to_string(),
  142. source_currency,
  143. };
  144. let quote = self.strike_api.payment_quote(payment_quote_request).await?;
  145. let fee = from_strike_amount(quote.lightning_network_fee, &melt_quote_request.unit)?;
  146. let amount = from_strike_amount(quote.amount, &melt_quote_request.unit)?.into();
  147. Ok(PaymentQuoteResponse {
  148. request_lookup_id: quote.payment_quote_id,
  149. amount,
  150. fee: fee.into(),
  151. state: MeltQuoteState::Unpaid,
  152. })
  153. }
  154. async fn pay_invoice(
  155. &self,
  156. melt_quote: mint::MeltQuote,
  157. _partial_msats: Option<Amount>,
  158. _max_fee_msats: Option<Amount>,
  159. ) -> Result<PayInvoiceResponse, Self::Err> {
  160. let pay_response = self
  161. .strike_api
  162. .pay_quote(&melt_quote.request_lookup_id)
  163. .await?;
  164. let state = match pay_response.state {
  165. InvoiceState::Paid => MeltQuoteState::Paid,
  166. InvoiceState::Unpaid => MeltQuoteState::Unpaid,
  167. InvoiceState::Completed => MeltQuoteState::Paid,
  168. InvoiceState::Pending => MeltQuoteState::Pending,
  169. };
  170. let total_spent = from_strike_amount(pay_response.total_amount, &melt_quote.unit)?.into();
  171. Ok(PayInvoiceResponse {
  172. payment_lookup_id: pay_response.payment_id,
  173. payment_preimage: None,
  174. status: state,
  175. total_spent,
  176. unit: melt_quote.unit,
  177. })
  178. }
  179. async fn create_invoice(
  180. &self,
  181. amount: Amount,
  182. _unit: &CurrencyUnit,
  183. description: String,
  184. unix_expiry: u64,
  185. ) -> Result<CreateInvoiceResponse, Self::Err> {
  186. let time_now = unix_time();
  187. assert!(unix_expiry > time_now);
  188. let request_lookup_id = Uuid::new_v4();
  189. let invoice_request = InvoiceRequest {
  190. correlation_id: Some(request_lookup_id.to_string()),
  191. amount: to_strike_unit(amount, &self.unit)?,
  192. description: Some(description),
  193. };
  194. let create_invoice_response = self.strike_api.create_invoice(invoice_request).await?;
  195. let quote = self
  196. .strike_api
  197. .invoice_quote(&create_invoice_response.invoice_id)
  198. .await?;
  199. let request: Bolt11Invoice = quote.ln_invoice.parse()?;
  200. let expiry = request.expires_at().map(|t| t.as_secs());
  201. Ok(CreateInvoiceResponse {
  202. request_lookup_id: create_invoice_response.invoice_id,
  203. request: quote.ln_invoice.parse()?,
  204. expiry,
  205. })
  206. }
  207. async fn check_incoming_invoice_status(
  208. &self,
  209. request_lookup_id: &str,
  210. ) -> Result<MintQuoteState, Self::Err> {
  211. let invoice = self
  212. .strike_api
  213. .get_incoming_invoice(request_lookup_id)
  214. .await?;
  215. let state = match invoice.state {
  216. InvoiceState::Paid => MintQuoteState::Paid,
  217. InvoiceState::Unpaid => MintQuoteState::Unpaid,
  218. InvoiceState::Completed => MintQuoteState::Paid,
  219. InvoiceState::Pending => MintQuoteState::Pending,
  220. };
  221. Ok(state)
  222. }
  223. async fn check_outgoing_payment(
  224. &self,
  225. payment_id: &str,
  226. ) -> Result<PayInvoiceResponse, Self::Err> {
  227. let invoice = self.strike_api.get_outgoing_payment(payment_id).await;
  228. let pay_invoice_response = match invoice {
  229. Ok(invoice) => {
  230. let state = match invoice.state {
  231. InvoiceState::Paid => MeltQuoteState::Paid,
  232. InvoiceState::Unpaid => MeltQuoteState::Unpaid,
  233. InvoiceState::Completed => MeltQuoteState::Paid,
  234. InvoiceState::Pending => MeltQuoteState::Pending,
  235. };
  236. PayInvoiceResponse {
  237. payment_lookup_id: invoice.payment_id,
  238. payment_preimage: None,
  239. status: state,
  240. total_spent: from_strike_amount(invoice.total_amount, &self.unit)?.into(),
  241. unit: self.unit.clone(),
  242. }
  243. }
  244. Err(err) => match err {
  245. strike_rs::Error::NotFound => PayInvoiceResponse {
  246. payment_lookup_id: payment_id.to_string(),
  247. payment_preimage: None,
  248. status: MeltQuoteState::Unknown,
  249. total_spent: Amount::ZERO,
  250. unit: self.unit.clone(),
  251. },
  252. _ => {
  253. return Err(Error::from(err).into());
  254. }
  255. },
  256. };
  257. Ok(pay_invoice_response)
  258. }
  259. }
  260. impl Strike {
  261. /// Create invoice webhook
  262. pub async fn create_invoice_webhook(
  263. &self,
  264. webhook_endpoint: &str,
  265. sender: tokio::sync::mpsc::Sender<String>,
  266. ) -> anyhow::Result<Router> {
  267. let subs = self.strike_api.get_current_subscriptions().await?;
  268. tracing::debug!("Got {} current subscriptions", subs.len());
  269. for sub in subs {
  270. tracing::info!("Deleting webhook: {}", &sub.id);
  271. if let Err(err) = self.strike_api.delete_subscription(&sub.id).await {
  272. tracing::error!("Error deleting webhook subscription: {} {}", sub.id, err);
  273. }
  274. }
  275. self.strike_api
  276. .create_invoice_webhook_router(webhook_endpoint, sender)
  277. .await
  278. }
  279. }
  280. pub(crate) fn from_strike_amount(
  281. strike_amount: StrikeAmount,
  282. target_unit: &CurrencyUnit,
  283. ) -> anyhow::Result<u64> {
  284. match target_unit {
  285. CurrencyUnit::Sat => strike_amount.to_sats(),
  286. CurrencyUnit::Msat => Ok(strike_amount.to_sats()? * 1000),
  287. CurrencyUnit::Usd => {
  288. if strike_amount.currency == StrikeCurrencyUnit::USD {
  289. Ok((strike_amount.amount * 100.0).round() as u64)
  290. } else {
  291. bail!("Could not convert strike USD");
  292. }
  293. }
  294. CurrencyUnit::Eur => {
  295. if strike_amount.currency == StrikeCurrencyUnit::EUR {
  296. Ok((strike_amount.amount * 100.0).round() as u64)
  297. } else {
  298. bail!("Could not convert to EUR");
  299. }
  300. }
  301. _ => bail!("Unsupported unit"),
  302. }
  303. }
  304. pub(crate) fn to_strike_unit<T>(
  305. amount: T,
  306. current_unit: &CurrencyUnit,
  307. ) -> anyhow::Result<StrikeAmount>
  308. where
  309. T: Into<u64>,
  310. {
  311. let amount = amount.into();
  312. match current_unit {
  313. CurrencyUnit::Sat => Ok(StrikeAmount::from_sats(amount)),
  314. CurrencyUnit::Msat => Ok(StrikeAmount::from_sats(amount / 1000)),
  315. CurrencyUnit::Usd => {
  316. let dollars = (amount as f64 / 100_f64) * 100.0;
  317. Ok(StrikeAmount {
  318. currency: StrikeCurrencyUnit::USD,
  319. amount: dollars.round() / 100.0,
  320. })
  321. }
  322. CurrencyUnit::Eur => {
  323. let euro = (amount as f64 / 100_f64) * 100.0;
  324. Ok(StrikeAmount {
  325. currency: StrikeCurrencyUnit::EUR,
  326. amount: euro.round() / 100.0,
  327. })
  328. }
  329. _ => bail!("Unsupported unit"),
  330. }
  331. }