lib.rs 10 KB

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