lib.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. //! CDK Fake LN Backend
  2. //!
  3. //! Used for testing where quotes are auto filled
  4. #![doc = include_str!("../README.md")]
  5. #![warn(missing_docs)]
  6. #![warn(rustdoc::bare_urls)]
  7. use std::cmp::max;
  8. use std::collections::{HashMap, HashSet};
  9. use std::pin::Pin;
  10. use std::str::FromStr;
  11. use std::sync::atomic::{AtomicBool, Ordering};
  12. use std::sync::Arc;
  13. use async_trait::async_trait;
  14. use bitcoin::hashes::{sha256, Hash};
  15. use bitcoin::secp256k1::rand::{thread_rng, Rng};
  16. use bitcoin::secp256k1::{Secp256k1, SecretKey};
  17. use cdk::amount::{to_unit, Amount};
  18. use cdk::cdk_payment::{
  19. self, Bolt11Settings, CreateIncomingPaymentResponse, MakePaymentResponse, MintPayment,
  20. PaymentQuoteResponse,
  21. };
  22. use cdk::nuts::{CurrencyUnit, MeltOptions, MeltQuoteState, MintQuoteState};
  23. use cdk::types::FeeReserve;
  24. use cdk::{ensure_cdk, mint};
  25. use error::Error;
  26. use futures::stream::StreamExt;
  27. use futures::Stream;
  28. use lightning_invoice::{Bolt11Invoice, Currency, InvoiceBuilder, PaymentSecret};
  29. use reqwest::Client;
  30. use serde::{Deserialize, Serialize};
  31. use serde_json::Value;
  32. use tokio::sync::Mutex;
  33. use tokio::time;
  34. use tokio_stream::wrappers::ReceiverStream;
  35. use tokio_util::sync::CancellationToken;
  36. use tracing::instrument;
  37. pub mod error;
  38. /// Fake Wallet
  39. #[derive(Clone)]
  40. pub struct FakeWallet {
  41. fee_reserve: FeeReserve,
  42. sender: tokio::sync::mpsc::Sender<String>,
  43. receiver: Arc<Mutex<Option<tokio::sync::mpsc::Receiver<String>>>>,
  44. payment_states: Arc<Mutex<HashMap<String, MeltQuoteState>>>,
  45. failed_payment_check: Arc<Mutex<HashSet<String>>>,
  46. payment_delay: u64,
  47. wait_invoice_cancel_token: CancellationToken,
  48. wait_invoice_is_active: Arc<AtomicBool>,
  49. }
  50. impl FakeWallet {
  51. /// Create new [`FakeWallet`]
  52. pub fn new(
  53. fee_reserve: FeeReserve,
  54. payment_states: HashMap<String, MeltQuoteState>,
  55. fail_payment_check: HashSet<String>,
  56. payment_delay: u64,
  57. ) -> Self {
  58. let (sender, receiver) = tokio::sync::mpsc::channel(8);
  59. Self {
  60. fee_reserve,
  61. sender,
  62. receiver: Arc::new(Mutex::new(Some(receiver))),
  63. payment_states: Arc::new(Mutex::new(payment_states)),
  64. failed_payment_check: Arc::new(Mutex::new(fail_payment_check)),
  65. payment_delay,
  66. wait_invoice_cancel_token: CancellationToken::new(),
  67. wait_invoice_is_active: Arc::new(AtomicBool::new(false)),
  68. }
  69. }
  70. }
  71. /// Struct for signaling what methods should respond via invoice description
  72. #[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)]
  73. pub struct FakeInvoiceDescription {
  74. /// State to be returned from pay invoice state
  75. pub pay_invoice_state: MeltQuoteState,
  76. /// State to be returned by check payment state
  77. pub check_payment_state: MeltQuoteState,
  78. /// Should pay invoice error
  79. pub pay_err: bool,
  80. /// Should check failure
  81. pub check_err: bool,
  82. }
  83. impl Default for FakeInvoiceDescription {
  84. fn default() -> Self {
  85. Self {
  86. pay_invoice_state: MeltQuoteState::Paid,
  87. check_payment_state: MeltQuoteState::Paid,
  88. pay_err: false,
  89. check_err: false,
  90. }
  91. }
  92. }
  93. #[async_trait]
  94. impl MintPayment for FakeWallet {
  95. type Err = cdk_payment::Error;
  96. #[instrument(skip_all)]
  97. async fn get_settings(&self) -> Result<Value, Self::Err> {
  98. Ok(serde_json::to_value(Bolt11Settings {
  99. mpp: true,
  100. unit: CurrencyUnit::Msat,
  101. invoice_description: true,
  102. amountless: false,
  103. })?)
  104. }
  105. #[instrument(skip_all)]
  106. fn is_wait_invoice_active(&self) -> bool {
  107. self.wait_invoice_is_active.load(Ordering::SeqCst)
  108. }
  109. #[instrument(skip_all)]
  110. fn cancel_wait_invoice(&self) {
  111. self.wait_invoice_cancel_token.cancel()
  112. }
  113. #[instrument(skip_all)]
  114. async fn wait_any_incoming_payment(
  115. &self,
  116. ) -> Result<Pin<Box<dyn Stream<Item = String> + Send>>, Self::Err> {
  117. tracing::info!("Starting stream for fake invoices");
  118. let receiver = self.receiver.lock().await.take().ok_or(Error::NoReceiver)?;
  119. let receiver_stream = ReceiverStream::new(receiver);
  120. Ok(Box::pin(receiver_stream.map(|label| label)))
  121. }
  122. #[instrument(skip_all)]
  123. async fn get_payment_quote(
  124. &self,
  125. request: &str,
  126. unit: &CurrencyUnit,
  127. options: Option<MeltOptions>,
  128. ) -> Result<PaymentQuoteResponse, Self::Err> {
  129. let bolt11 = Bolt11Invoice::from_str(request)?;
  130. let amount_msat = match options {
  131. Some(amount) => amount.amount_msat(),
  132. None => bolt11
  133. .amount_milli_satoshis()
  134. .ok_or(Error::UnknownInvoiceAmount)?
  135. .into(),
  136. };
  137. let amount = if unit != &CurrencyUnit::Sat && unit != &CurrencyUnit::Msat {
  138. let client = Client::new();
  139. let response: Value = client
  140. .get("https://mempool.space/api/v1/prices")
  141. .send()
  142. .await
  143. .map_err(|_| Error::UnknownInvoice)?
  144. .json()
  145. .await
  146. .unwrap();
  147. let price = response.get(unit.to_string().to_uppercase()).unwrap();
  148. let bitcoin_amount = u64::from(amount_msat) as f64 / 100_000_000_000.0;
  149. let total_price = price.as_f64().unwrap() * bitcoin_amount;
  150. Amount::from((total_price * 100.0).ceil() as u64)
  151. } else {
  152. to_unit(amount_msat, &CurrencyUnit::Msat, unit)?
  153. };
  154. let relative_fee_reserve =
  155. (self.fee_reserve.percent_fee_reserve * u64::from(amount) as f32) as u64;
  156. let absolute_fee_reserve: u64 = self.fee_reserve.min_fee_reserve.into();
  157. let fee = max(relative_fee_reserve, absolute_fee_reserve);
  158. Ok(PaymentQuoteResponse {
  159. request_lookup_id: bolt11.payment_hash().to_string(),
  160. amount,
  161. fee: fee.into(),
  162. unit: unit.clone(),
  163. state: MeltQuoteState::Unpaid,
  164. })
  165. }
  166. #[instrument(skip_all)]
  167. async fn make_payment(
  168. &self,
  169. melt_quote: mint::MeltQuote,
  170. _partial_msats: Option<Amount>,
  171. _max_fee_msats: Option<Amount>,
  172. ) -> Result<MakePaymentResponse, Self::Err> {
  173. let bolt11 = Bolt11Invoice::from_str(&melt_quote.request)?;
  174. let payment_hash = bolt11.payment_hash().to_string();
  175. let description = bolt11.description().to_string();
  176. let status: Option<FakeInvoiceDescription> = serde_json::from_str(&description).ok();
  177. let mut payment_states = self.payment_states.lock().await;
  178. let payment_status = status
  179. .clone()
  180. .map(|s| s.pay_invoice_state)
  181. .unwrap_or(MeltQuoteState::Paid);
  182. let checkout_going_status = status
  183. .clone()
  184. .map(|s| s.check_payment_state)
  185. .unwrap_or(MeltQuoteState::Paid);
  186. payment_states.insert(payment_hash.clone(), checkout_going_status);
  187. if let Some(description) = status {
  188. if description.check_err {
  189. let mut fail = self.failed_payment_check.lock().await;
  190. fail.insert(payment_hash.clone());
  191. }
  192. ensure_cdk!(!description.pay_err, Error::UnknownInvoice.into());
  193. }
  194. Ok(MakePaymentResponse {
  195. payment_proof: Some("".to_string()),
  196. payment_lookup_id: payment_hash,
  197. status: payment_status,
  198. total_spent: melt_quote.amount + 1.into(),
  199. unit: melt_quote.unit,
  200. })
  201. }
  202. #[instrument(skip_all)]
  203. async fn create_incoming_payment_request(
  204. &self,
  205. amount: Amount,
  206. _unit: &CurrencyUnit,
  207. description: String,
  208. _unix_expiry: Option<u64>,
  209. ) -> Result<CreateIncomingPaymentResponse, Self::Err> {
  210. // Since this is fake we just use the amount no matter the unit to create an invoice
  211. let amount_msat = amount;
  212. let invoice = create_fake_invoice(amount_msat.into(), description);
  213. let sender = self.sender.clone();
  214. let payment_hash = invoice.payment_hash();
  215. let payment_hash_clone = payment_hash.to_string();
  216. let duration = time::Duration::from_secs(self.payment_delay);
  217. tokio::spawn(async move {
  218. // Wait for the random delay to elapse
  219. time::sleep(duration).await;
  220. // Send the message after waiting for the specified duration
  221. if sender.send(payment_hash_clone.clone()).await.is_err() {
  222. tracing::error!("Failed to send label: {}", payment_hash_clone);
  223. }
  224. });
  225. let expiry = invoice.expires_at().map(|t| t.as_secs());
  226. Ok(CreateIncomingPaymentResponse {
  227. request_lookup_id: payment_hash.to_string(),
  228. request: invoice.to_string(),
  229. expiry,
  230. })
  231. }
  232. #[instrument(skip_all)]
  233. async fn check_incoming_payment_status(
  234. &self,
  235. _request_lookup_id: &str,
  236. ) -> Result<MintQuoteState, Self::Err> {
  237. Ok(MintQuoteState::Paid)
  238. }
  239. #[instrument(skip_all)]
  240. async fn check_outgoing_payment(
  241. &self,
  242. request_lookup_id: &str,
  243. ) -> Result<MakePaymentResponse, Self::Err> {
  244. // For fake wallet if the state is not explicitly set default to paid
  245. let states = self.payment_states.lock().await;
  246. let status = states.get(request_lookup_id).cloned();
  247. let status = status.unwrap_or(MeltQuoteState::Paid);
  248. let fail_payments = self.failed_payment_check.lock().await;
  249. if fail_payments.contains(request_lookup_id) {
  250. return Err(cdk_payment::Error::InvoicePaymentPending);
  251. }
  252. Ok(MakePaymentResponse {
  253. payment_proof: Some("".to_string()),
  254. payment_lookup_id: request_lookup_id.to_string(),
  255. status,
  256. total_spent: Amount::ZERO,
  257. unit: CurrencyUnit::Msat,
  258. })
  259. }
  260. }
  261. /// Create fake invoice
  262. #[instrument]
  263. pub fn create_fake_invoice(amount_msat: u64, description: String) -> Bolt11Invoice {
  264. let private_key = SecretKey::from_slice(
  265. &[
  266. 0xe1, 0x26, 0xf6, 0x8f, 0x7e, 0xaf, 0xcc, 0x8b, 0x74, 0xf5, 0x4d, 0x26, 0x9f, 0xe2,
  267. 0x06, 0xbe, 0x71, 0x50, 0x00, 0xf9, 0x4d, 0xac, 0x06, 0x7d, 0x1c, 0x04, 0xa8, 0xca,
  268. 0x3b, 0x2d, 0xb7, 0x34,
  269. ][..],
  270. )
  271. .unwrap();
  272. let mut rng = thread_rng();
  273. let mut random_bytes = [0u8; 32];
  274. rng.fill(&mut random_bytes);
  275. let payment_hash = sha256::Hash::from_slice(&random_bytes).unwrap();
  276. let payment_secret = PaymentSecret([42u8; 32]);
  277. InvoiceBuilder::new(Currency::Bitcoin)
  278. .description(description)
  279. .payment_hash(payment_hash)
  280. .payment_secret(payment_secret)
  281. .amount_milli_satoshis(amount_msat)
  282. .current_timestamp()
  283. .min_final_cltv_expiry_delta(144)
  284. .build_signed(|hash| Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key))
  285. .unwrap()
  286. }