lib.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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. Ok(PaymentQuoteResponse {
  147. request_lookup_id: quote.payment_quote_id,
  148. amount: from_strike_amount(quote.amount, &melt_quote_request.unit)?.into(),
  149. fee: fee.into(),
  150. state: MeltQuoteState::Unpaid,
  151. })
  152. }
  153. async fn pay_invoice(
  154. &self,
  155. melt_quote: mint::MeltQuote,
  156. _partial_msats: Option<Amount>,
  157. _max_fee_msats: Option<Amount>,
  158. ) -> Result<PayInvoiceResponse, Self::Err> {
  159. let pay_response = self
  160. .strike_api
  161. .pay_quote(&melt_quote.request_lookup_id)
  162. .await?;
  163. let state = match pay_response.state {
  164. InvoiceState::Paid => MeltQuoteState::Paid,
  165. InvoiceState::Unpaid => MeltQuoteState::Unpaid,
  166. InvoiceState::Completed => MeltQuoteState::Paid,
  167. InvoiceState::Pending => MeltQuoteState::Pending,
  168. };
  169. let total_spent = from_strike_amount(pay_response.total_amount, &melt_quote.unit)?.into();
  170. Ok(PayInvoiceResponse {
  171. payment_lookup_id: pay_response.payment_id,
  172. payment_preimage: None,
  173. status: state,
  174. total_spent,
  175. unit: melt_quote.unit,
  176. })
  177. }
  178. async fn create_invoice(
  179. &self,
  180. amount: Amount,
  181. _unit: &CurrencyUnit,
  182. description: String,
  183. unix_expiry: u64,
  184. ) -> Result<CreateInvoiceResponse, Self::Err> {
  185. let time_now = unix_time();
  186. assert!(unix_expiry > time_now);
  187. let request_lookup_id = Uuid::new_v4();
  188. let invoice_request = InvoiceRequest {
  189. correlation_id: Some(request_lookup_id.to_string()),
  190. amount: to_strike_unit(amount, &self.unit)?,
  191. description: Some(description),
  192. };
  193. let create_invoice_response = self.strike_api.create_invoice(invoice_request).await?;
  194. let quote = self
  195. .strike_api
  196. .invoice_quote(&create_invoice_response.invoice_id)
  197. .await?;
  198. let request: Bolt11Invoice = quote.ln_invoice.parse()?;
  199. let expiry = request.expires_at().map(|t| t.as_secs());
  200. Ok(CreateInvoiceResponse {
  201. request_lookup_id: create_invoice_response.invoice_id,
  202. request: quote.ln_invoice.parse()?,
  203. expiry,
  204. })
  205. }
  206. async fn check_incoming_invoice_status(
  207. &self,
  208. request_lookup_id: &str,
  209. ) -> Result<MintQuoteState, Self::Err> {
  210. let invoice = self
  211. .strike_api
  212. .get_incoming_invoice(request_lookup_id)
  213. .await?;
  214. let state = match invoice.state {
  215. InvoiceState::Paid => MintQuoteState::Paid,
  216. InvoiceState::Unpaid => MintQuoteState::Unpaid,
  217. InvoiceState::Completed => MintQuoteState::Paid,
  218. InvoiceState::Pending => MintQuoteState::Pending,
  219. };
  220. Ok(state)
  221. }
  222. async fn check_outgoing_payment(
  223. &self,
  224. payment_id: &str,
  225. ) -> Result<PayInvoiceResponse, Self::Err> {
  226. let invoice = self.strike_api.get_outgoing_payment(payment_id).await;
  227. let pay_invoice_response = match invoice {
  228. Ok(invoice) => {
  229. let state = match invoice.state {
  230. InvoiceState::Paid => MeltQuoteState::Paid,
  231. InvoiceState::Unpaid => MeltQuoteState::Unpaid,
  232. InvoiceState::Completed => MeltQuoteState::Paid,
  233. InvoiceState::Pending => MeltQuoteState::Pending,
  234. };
  235. PayInvoiceResponse {
  236. payment_lookup_id: invoice.payment_id,
  237. payment_preimage: None,
  238. status: state,
  239. total_spent: from_strike_amount(invoice.total_amount, &self.unit)?.into(),
  240. unit: self.unit.clone(),
  241. }
  242. }
  243. Err(err) => match err {
  244. strike_rs::Error::NotFound => PayInvoiceResponse {
  245. payment_lookup_id: payment_id.to_string(),
  246. payment_preimage: None,
  247. status: MeltQuoteState::Unknown,
  248. total_spent: Amount::ZERO,
  249. unit: self.unit.clone(),
  250. },
  251. _ => {
  252. return Err(Error::from(err).into());
  253. }
  254. },
  255. };
  256. Ok(pay_invoice_response)
  257. }
  258. }
  259. impl Strike {
  260. /// Create invoice webhook
  261. pub async fn create_invoice_webhook(
  262. &self,
  263. webhook_endpoint: &str,
  264. sender: tokio::sync::mpsc::Sender<String>,
  265. ) -> anyhow::Result<Router> {
  266. let subs = self.strike_api.get_current_subscriptions().await?;
  267. tracing::debug!("Got {} current subscriptions", subs.len());
  268. for sub in subs {
  269. tracing::info!("Deleting webhook: {}", &sub.id);
  270. if let Err(err) = self.strike_api.delete_subscription(&sub.id).await {
  271. tracing::error!("Error deleting webhook subscription: {} {}", sub.id, err);
  272. }
  273. }
  274. self.strike_api
  275. .create_invoice_webhook_router(webhook_endpoint, sender)
  276. .await
  277. }
  278. }
  279. pub(crate) fn from_strike_amount(
  280. strike_amount: StrikeAmount,
  281. target_unit: &CurrencyUnit,
  282. ) -> anyhow::Result<u64> {
  283. match target_unit {
  284. CurrencyUnit::Sat => strike_amount.to_sats(),
  285. CurrencyUnit::Msat => Ok(strike_amount.to_sats()? * 1000),
  286. CurrencyUnit::Usd => {
  287. if strike_amount.currency == StrikeCurrencyUnit::USD {
  288. Ok((strike_amount.amount * 100.0).round() as u64)
  289. } else {
  290. bail!("Could not convert strike USD");
  291. }
  292. }
  293. CurrencyUnit::Eur => {
  294. if strike_amount.currency == StrikeCurrencyUnit::EUR {
  295. Ok((strike_amount.amount * 100.0).round() as u64)
  296. } else {
  297. bail!("Could not convert to EUR");
  298. }
  299. }
  300. _ => bail!("Unsupported unit"),
  301. }
  302. }
  303. pub(crate) fn to_strike_unit<T>(
  304. amount: T,
  305. current_unit: &CurrencyUnit,
  306. ) -> anyhow::Result<StrikeAmount>
  307. where
  308. T: Into<u64>,
  309. {
  310. let amount = amount.into();
  311. match current_unit {
  312. CurrencyUnit::Sat => Ok(StrikeAmount::from_sats(amount)),
  313. CurrencyUnit::Msat => Ok(StrikeAmount::from_sats(amount / 1000)),
  314. CurrencyUnit::Usd => {
  315. let dollars = (amount as f64 / 100_f64) * 100.0;
  316. Ok(StrikeAmount {
  317. currency: StrikeCurrencyUnit::USD,
  318. amount: dollars.round() / 100.0,
  319. })
  320. }
  321. CurrencyUnit::Eur => {
  322. let euro = (amount as f64 / 100_f64) * 100.0;
  323. Ok(StrikeAmount {
  324. currency: StrikeCurrencyUnit::EUR,
  325. amount: euro.round() / 100.0,
  326. })
  327. }
  328. _ => bail!("Unsupported unit"),
  329. }
  330. }