lib.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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. })?)
  102. }
  103. #[instrument(skip_all)]
  104. fn is_wait_invoice_active(&self) -> bool {
  105. self.wait_invoice_is_active.load(Ordering::SeqCst)
  106. }
  107. #[instrument(skip_all)]
  108. fn cancel_wait_invoice(&self) {
  109. self.wait_invoice_cancel_token.cancel()
  110. }
  111. #[instrument(skip_all)]
  112. async fn wait_any_incoming_payment(
  113. &self,
  114. ) -> Result<Pin<Box<dyn Stream<Item = String> + Send>>, Self::Err> {
  115. tracing::info!("Starting stream for fake invoices");
  116. let receiver = self.receiver.lock().await.take().ok_or(Error::NoReceiver)?;
  117. let receiver_stream = ReceiverStream::new(receiver);
  118. Ok(Box::pin(receiver_stream.map(|label| label)))
  119. }
  120. #[instrument(skip_all)]
  121. async fn get_payment_quote(
  122. &self,
  123. request: &str,
  124. unit: &CurrencyUnit,
  125. options: Option<MeltOptions>,
  126. ) -> Result<PaymentQuoteResponse, Self::Err> {
  127. let bolt11 = Bolt11Invoice::from_str(request)?;
  128. let amount_msat = match options {
  129. Some(amount) => amount.amount_msat(),
  130. None => bolt11
  131. .amount_milli_satoshis()
  132. .ok_or(Error::UnknownInvoiceAmount)?
  133. .into(),
  134. };
  135. let amount = to_unit(amount_msat, &CurrencyUnit::Msat, unit)?;
  136. let relative_fee_reserve =
  137. (self.fee_reserve.percent_fee_reserve * u64::from(amount) as f32) as u64;
  138. let absolute_fee_reserve: u64 = self.fee_reserve.min_fee_reserve.into();
  139. let fee = max(relative_fee_reserve, absolute_fee_reserve);
  140. Ok(PaymentQuoteResponse {
  141. request_lookup_id: bolt11.payment_hash().to_string(),
  142. amount,
  143. fee: fee.into(),
  144. state: MeltQuoteState::Unpaid,
  145. })
  146. }
  147. #[instrument(skip_all)]
  148. async fn make_payment(
  149. &self,
  150. melt_quote: mint::MeltQuote,
  151. _partial_msats: Option<Amount>,
  152. _max_fee_msats: Option<Amount>,
  153. ) -> Result<MakePaymentResponse, Self::Err> {
  154. let bolt11 = Bolt11Invoice::from_str(&melt_quote.request)?;
  155. let payment_hash = bolt11.payment_hash().to_string();
  156. let description = bolt11.description().to_string();
  157. let status: Option<FakeInvoiceDescription> = serde_json::from_str(&description).ok();
  158. let mut payment_states = self.payment_states.lock().await;
  159. let payment_status = status
  160. .clone()
  161. .map(|s| s.pay_invoice_state)
  162. .unwrap_or(MeltQuoteState::Paid);
  163. let checkout_going_status = status
  164. .clone()
  165. .map(|s| s.check_payment_state)
  166. .unwrap_or(MeltQuoteState::Paid);
  167. payment_states.insert(payment_hash.clone(), checkout_going_status);
  168. if let Some(description) = status {
  169. if description.check_err {
  170. let mut fail = self.failed_payment_check.lock().await;
  171. fail.insert(payment_hash.clone());
  172. }
  173. ensure_cdk!(!description.pay_err, Error::UnknownInvoice.into());
  174. }
  175. Ok(MakePaymentResponse {
  176. payment_proof: Some("".to_string()),
  177. payment_lookup_id: payment_hash,
  178. status: payment_status,
  179. total_spent: melt_quote.amount,
  180. unit: melt_quote.unit,
  181. })
  182. }
  183. #[instrument(skip_all)]
  184. async fn create_incoming_payment_request(
  185. &self,
  186. amount: Amount,
  187. _unit: &CurrencyUnit,
  188. description: String,
  189. _unix_expiry: Option<u64>,
  190. ) -> Result<CreateIncomingPaymentResponse, Self::Err> {
  191. // Since this is fake we just use the amount no matter the unit to create an invoice
  192. let amount_msat = amount;
  193. let invoice = create_fake_invoice(amount_msat.into(), description);
  194. let sender = self.sender.clone();
  195. let payment_hash = invoice.payment_hash();
  196. let payment_hash_clone = payment_hash.to_string();
  197. let duration = time::Duration::from_secs(self.payment_delay);
  198. tokio::spawn(async move {
  199. // Wait for the random delay to elapse
  200. time::sleep(duration).await;
  201. // Send the message after waiting for the specified duration
  202. if sender.send(payment_hash_clone.clone()).await.is_err() {
  203. tracing::error!("Failed to send label: {}", payment_hash_clone);
  204. }
  205. });
  206. let expiry = invoice.expires_at().map(|t| t.as_secs());
  207. Ok(CreateIncomingPaymentResponse {
  208. request_lookup_id: payment_hash.to_string(),
  209. request: invoice.to_string(),
  210. expiry,
  211. })
  212. }
  213. #[instrument(skip_all)]
  214. async fn check_incoming_payment_status(
  215. &self,
  216. _request_lookup_id: &str,
  217. ) -> Result<MintQuoteState, Self::Err> {
  218. Ok(MintQuoteState::Paid)
  219. }
  220. #[instrument(skip_all)]
  221. async fn check_outgoing_payment(
  222. &self,
  223. request_lookup_id: &str,
  224. ) -> Result<MakePaymentResponse, Self::Err> {
  225. // For fake wallet if the state is not explicitly set default to paid
  226. let states = self.payment_states.lock().await;
  227. let status = states.get(request_lookup_id).cloned();
  228. let status = status.unwrap_or(MeltQuoteState::Paid);
  229. let fail_payments = self.failed_payment_check.lock().await;
  230. if fail_payments.contains(request_lookup_id) {
  231. return Err(cdk_payment::Error::InvoicePaymentPending);
  232. }
  233. Ok(MakePaymentResponse {
  234. payment_proof: Some("".to_string()),
  235. payment_lookup_id: request_lookup_id.to_string(),
  236. status,
  237. total_spent: Amount::ZERO,
  238. unit: CurrencyUnit::Msat,
  239. })
  240. }
  241. }
  242. /// Create fake invoice
  243. #[instrument]
  244. pub fn create_fake_invoice(amount_msat: u64, description: String) -> Bolt11Invoice {
  245. let private_key = SecretKey::from_slice(
  246. &[
  247. 0xe1, 0x26, 0xf6, 0x8f, 0x7e, 0xaf, 0xcc, 0x8b, 0x74, 0xf5, 0x4d, 0x26, 0x9f, 0xe2,
  248. 0x06, 0xbe, 0x71, 0x50, 0x00, 0xf9, 0x4d, 0xac, 0x06, 0x7d, 0x1c, 0x04, 0xa8, 0xca,
  249. 0x3b, 0x2d, 0xb7, 0x34,
  250. ][..],
  251. )
  252. .unwrap();
  253. let mut rng = thread_rng();
  254. let mut random_bytes = [0u8; 32];
  255. rng.fill(&mut random_bytes);
  256. let payment_hash = sha256::Hash::from_slice(&random_bytes).unwrap();
  257. let payment_secret = PaymentSecret([42u8; 32]);
  258. InvoiceBuilder::new(Currency::Bitcoin)
  259. .description(description)
  260. .payment_hash(payment_hash)
  261. .payment_secret(payment_secret)
  262. .amount_milli_satoshis(amount_msat)
  263. .current_timestamp()
  264. .min_final_cltv_expiry_delta(144)
  265. .build_signed(|hash| Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key))
  266. .unwrap()
  267. }