lib.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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::sync::atomic::{AtomicBool, Ordering};
  11. use std::sync::Arc;
  12. use async_trait::async_trait;
  13. use bitcoin::hashes::{sha256, Hash};
  14. use bitcoin::secp256k1::rand::{thread_rng, Rng};
  15. use bitcoin::secp256k1::{Secp256k1, SecretKey};
  16. use cdk_common::amount::{to_unit, Amount};
  17. use cdk_common::common::FeeReserve;
  18. use cdk_common::ensure_cdk;
  19. use cdk_common::nuts::{CurrencyUnit, MeltOptions, MeltQuoteState};
  20. use cdk_common::payment::{
  21. self, Bolt11Settings, CreateIncomingPaymentResponse, IncomingPaymentOptions,
  22. MakePaymentResponse, MintPayment, OutgoingPaymentOptions, PaymentIdentifier,
  23. PaymentQuoteResponse, WaitPaymentResponse,
  24. };
  25. use error::Error;
  26. use futures::stream::StreamExt;
  27. use futures::Stream;
  28. use lightning::offers::offer::OfferBuilder;
  29. use lightning_invoice::{Bolt11Invoice, Currency, InvoiceBuilder, PaymentSecret};
  30. use serde::{Deserialize, Serialize};
  31. use serde_json::Value;
  32. use tokio::sync::{Mutex, RwLock};
  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. #[allow(clippy::type_complexity)]
  43. sender: tokio::sync::mpsc::Sender<(PaymentIdentifier, Amount)>,
  44. #[allow(clippy::type_complexity)]
  45. receiver: Arc<Mutex<Option<tokio::sync::mpsc::Receiver<(PaymentIdentifier, Amount)>>>>,
  46. payment_states: Arc<Mutex<HashMap<String, MeltQuoteState>>>,
  47. failed_payment_check: Arc<Mutex<HashSet<String>>>,
  48. payment_delay: u64,
  49. wait_invoice_cancel_token: CancellationToken,
  50. wait_invoice_is_active: Arc<AtomicBool>,
  51. incoming_payments: Arc<RwLock<HashMap<PaymentIdentifier, Vec<WaitPaymentResponse>>>>,
  52. unit: CurrencyUnit,
  53. }
  54. impl FakeWallet {
  55. /// Create new [`FakeWallet`]
  56. pub fn new(
  57. fee_reserve: FeeReserve,
  58. payment_states: HashMap<String, MeltQuoteState>,
  59. fail_payment_check: HashSet<String>,
  60. payment_delay: u64,
  61. unit: CurrencyUnit,
  62. ) -> Self {
  63. let (sender, receiver) = tokio::sync::mpsc::channel(8);
  64. Self {
  65. fee_reserve,
  66. sender,
  67. receiver: Arc::new(Mutex::new(Some(receiver))),
  68. payment_states: Arc::new(Mutex::new(payment_states)),
  69. failed_payment_check: Arc::new(Mutex::new(fail_payment_check)),
  70. payment_delay,
  71. wait_invoice_cancel_token: CancellationToken::new(),
  72. wait_invoice_is_active: Arc::new(AtomicBool::new(false)),
  73. incoming_payments: Arc::new(RwLock::new(HashMap::new())),
  74. unit,
  75. }
  76. }
  77. }
  78. /// Struct for signaling what methods should respond via invoice description
  79. #[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)]
  80. pub struct FakeInvoiceDescription {
  81. /// State to be returned from pay invoice state
  82. pub pay_invoice_state: MeltQuoteState,
  83. /// State to be returned by check payment state
  84. pub check_payment_state: MeltQuoteState,
  85. /// Should pay invoice error
  86. pub pay_err: bool,
  87. /// Should check failure
  88. pub check_err: bool,
  89. }
  90. impl Default for FakeInvoiceDescription {
  91. fn default() -> Self {
  92. Self {
  93. pay_invoice_state: MeltQuoteState::Paid,
  94. check_payment_state: MeltQuoteState::Paid,
  95. pay_err: false,
  96. check_err: false,
  97. }
  98. }
  99. }
  100. #[async_trait]
  101. impl MintPayment for FakeWallet {
  102. type Err = payment::Error;
  103. #[instrument(skip_all)]
  104. async fn get_settings(&self) -> Result<Value, Self::Err> {
  105. Ok(serde_json::to_value(Bolt11Settings {
  106. mpp: true,
  107. unit: self.unit.clone(),
  108. invoice_description: true,
  109. amountless: false,
  110. bolt12: true,
  111. })?)
  112. }
  113. #[instrument(skip_all)]
  114. fn is_wait_invoice_active(&self) -> bool {
  115. self.wait_invoice_is_active.load(Ordering::SeqCst)
  116. }
  117. #[instrument(skip_all)]
  118. fn cancel_wait_invoice(&self) {
  119. self.wait_invoice_cancel_token.cancel()
  120. }
  121. #[instrument(skip_all)]
  122. async fn wait_any_incoming_payment(
  123. &self,
  124. ) -> Result<Pin<Box<dyn Stream<Item = WaitPaymentResponse> + Send>>, Self::Err> {
  125. tracing::info!("Starting stream for fake invoices");
  126. let receiver = self
  127. .receiver
  128. .lock()
  129. .await
  130. .take()
  131. .ok_or(Error::NoReceiver)
  132. .unwrap();
  133. let unit = self.unit.clone();
  134. let receiver_stream = ReceiverStream::new(receiver);
  135. Ok(Box::pin(receiver_stream.map(
  136. move |(request_lookup_id, payment_amount)| WaitPaymentResponse {
  137. payment_identifier: request_lookup_id.clone(),
  138. payment_amount,
  139. unit: unit.clone(),
  140. payment_id: request_lookup_id.to_string(),
  141. },
  142. )))
  143. }
  144. #[instrument(skip_all)]
  145. async fn get_payment_quote(
  146. &self,
  147. unit: &CurrencyUnit,
  148. options: OutgoingPaymentOptions,
  149. ) -> Result<PaymentQuoteResponse, Self::Err> {
  150. let (amount_msat, request_lookup_id) = match options {
  151. OutgoingPaymentOptions::Bolt11(bolt11_options) => {
  152. // If we have specific amount options, use those
  153. let amount_msat: u64 = if let Some(melt_options) = bolt11_options.melt_options {
  154. let msats = match melt_options {
  155. MeltOptions::Amountless { amountless } => {
  156. let amount_msat = amountless.amount_msat;
  157. if let Some(invoice_amount) =
  158. bolt11_options.bolt11.amount_milli_satoshis()
  159. {
  160. ensure_cdk!(
  161. invoice_amount == u64::from(amount_msat),
  162. Error::UnknownInvoiceAmount.into()
  163. );
  164. }
  165. amount_msat
  166. }
  167. MeltOptions::Mpp { mpp } => mpp.amount,
  168. };
  169. u64::from(msats)
  170. } else {
  171. // Fall back to invoice amount
  172. bolt11_options
  173. .bolt11
  174. .amount_milli_satoshis()
  175. .ok_or(Error::UnknownInvoiceAmount)?
  176. };
  177. let payment_id =
  178. PaymentIdentifier::PaymentHash(*bolt11_options.bolt11.payment_hash().as_ref());
  179. (amount_msat, payment_id)
  180. }
  181. OutgoingPaymentOptions::Bolt12(bolt12_options) => {
  182. let offer = bolt12_options.offer;
  183. let amount_msat: u64 = if let Some(amount) = bolt12_options.melt_options {
  184. amount.amount_msat().into()
  185. } else {
  186. // Fall back to offer amount
  187. let amount = offer.amount().ok_or(Error::UnknownInvoiceAmount)?;
  188. match amount {
  189. lightning::offers::offer::Amount::Bitcoin { amount_msats } => amount_msats,
  190. _ => return Err(Error::UnknownInvoiceAmount.into()),
  191. }
  192. };
  193. (
  194. amount_msat,
  195. PaymentIdentifier::OfferId(offer.id().to_string()),
  196. )
  197. }
  198. };
  199. let amount = to_unit(amount_msat, &CurrencyUnit::Msat, unit)?;
  200. let relative_fee_reserve =
  201. (self.fee_reserve.percent_fee_reserve * u64::from(amount) as f32) as u64;
  202. let absolute_fee_reserve: u64 = self.fee_reserve.min_fee_reserve.into();
  203. let fee = max(relative_fee_reserve, absolute_fee_reserve);
  204. Ok(PaymentQuoteResponse {
  205. request_lookup_id,
  206. amount,
  207. fee: fee.into(),
  208. state: MeltQuoteState::Unpaid,
  209. options: None,
  210. unit: unit.clone(),
  211. })
  212. }
  213. #[instrument(skip_all)]
  214. async fn make_payment(
  215. &self,
  216. unit: &CurrencyUnit,
  217. options: OutgoingPaymentOptions,
  218. ) -> Result<MakePaymentResponse, Self::Err> {
  219. match options {
  220. OutgoingPaymentOptions::Bolt11(bolt11_options) => {
  221. let bolt11 = bolt11_options.bolt11;
  222. let payment_hash = bolt11.payment_hash().to_string();
  223. let description = bolt11.description().to_string();
  224. let status: Option<FakeInvoiceDescription> =
  225. serde_json::from_str(&description).ok();
  226. let mut payment_states = self.payment_states.lock().await;
  227. let payment_status = status
  228. .clone()
  229. .map(|s| s.pay_invoice_state)
  230. .unwrap_or(MeltQuoteState::Paid);
  231. let checkout_going_status = status
  232. .clone()
  233. .map(|s| s.check_payment_state)
  234. .unwrap_or(MeltQuoteState::Paid);
  235. payment_states.insert(payment_hash.clone(), checkout_going_status);
  236. if let Some(description) = status {
  237. if description.check_err {
  238. let mut fail = self.failed_payment_check.lock().await;
  239. fail.insert(payment_hash.clone());
  240. }
  241. ensure_cdk!(!description.pay_err, Error::UnknownInvoice.into());
  242. }
  243. let amount_msat: u64 = if let Some(melt_options) = bolt11_options.melt_options {
  244. melt_options.amount_msat().into()
  245. } else {
  246. // Fall back to invoice amount
  247. bolt11
  248. .amount_milli_satoshis()
  249. .ok_or(Error::UnknownInvoiceAmount)?
  250. };
  251. let total_spent = to_unit(amount_msat, &CurrencyUnit::Msat, unit)?;
  252. Ok(MakePaymentResponse {
  253. payment_proof: Some("".to_string()),
  254. payment_lookup_id: PaymentIdentifier::PaymentHash(
  255. *bolt11.payment_hash().as_ref(),
  256. ),
  257. status: payment_status,
  258. total_spent: total_spent + 1.into(),
  259. unit: unit.clone(),
  260. })
  261. }
  262. OutgoingPaymentOptions::Bolt12(bolt12_options) => {
  263. let bolt12 = bolt12_options.offer;
  264. let amount_msat: u64 = if let Some(amount) = bolt12_options.melt_options {
  265. amount.amount_msat().into()
  266. } else {
  267. // Fall back to offer amount
  268. let amount = bolt12.amount().ok_or(Error::UnknownInvoiceAmount)?;
  269. match amount {
  270. lightning::offers::offer::Amount::Bitcoin { amount_msats } => amount_msats,
  271. _ => return Err(Error::UnknownInvoiceAmount.into()),
  272. }
  273. };
  274. let total_spent = to_unit(amount_msat, &CurrencyUnit::Msat, unit)?;
  275. Ok(MakePaymentResponse {
  276. payment_proof: Some("".to_string()),
  277. payment_lookup_id: PaymentIdentifier::OfferId(bolt12.id().to_string()),
  278. status: MeltQuoteState::Paid,
  279. total_spent: total_spent + 1.into(),
  280. unit: unit.clone(),
  281. })
  282. }
  283. }
  284. }
  285. #[instrument(skip_all)]
  286. async fn create_incoming_payment_request(
  287. &self,
  288. unit: &CurrencyUnit,
  289. options: IncomingPaymentOptions,
  290. ) -> Result<CreateIncomingPaymentResponse, Self::Err> {
  291. let (payment_hash, request, amount, expiry) = match options {
  292. IncomingPaymentOptions::Bolt12(bolt12_options) => {
  293. let description = bolt12_options.description.unwrap_or_default();
  294. let amount = bolt12_options.amount;
  295. let expiry = bolt12_options.unix_expiry;
  296. let secret_key = SecretKey::new(&mut thread_rng());
  297. let secp_ctx = Secp256k1::new();
  298. let offer_builder = OfferBuilder::new(secret_key.public_key(&secp_ctx))
  299. .description(description.clone());
  300. let offer_builder = match amount {
  301. Some(amount) => {
  302. let amount_msat = to_unit(amount, unit, &CurrencyUnit::Msat)?;
  303. offer_builder.amount_msats(amount_msat.into())
  304. }
  305. None => offer_builder,
  306. };
  307. let offer = offer_builder.build().unwrap();
  308. (
  309. PaymentIdentifier::OfferId(offer.id().to_string()),
  310. offer.to_string(),
  311. amount.unwrap_or(Amount::ZERO),
  312. expiry,
  313. )
  314. }
  315. IncomingPaymentOptions::Bolt11(bolt11_options) => {
  316. let description = bolt11_options.description.unwrap_or_default();
  317. let amount = if unit == &CurrencyUnit::Sat {
  318. to_unit(bolt11_options.amount, unit, &CurrencyUnit::Msat)
  319. .unwrap_or(bolt11_options.amount * Amount::from(1000))
  320. } else {
  321. bolt11_options.amount
  322. };
  323. let expiry = bolt11_options.unix_expiry;
  324. // Since this is fake we just use the amount no matter the unit to create an invoice
  325. let invoice = create_fake_invoice(amount.into(), description.clone());
  326. let payment_hash = invoice.payment_hash();
  327. (
  328. PaymentIdentifier::PaymentHash(*payment_hash.as_ref()),
  329. invoice.to_string(),
  330. amount,
  331. expiry,
  332. )
  333. }
  334. };
  335. let sender = self.sender.clone();
  336. let duration = time::Duration::from_secs(self.payment_delay);
  337. let final_amount = if amount == Amount::ZERO {
  338. let mut rng = thread_rng();
  339. // Generate a random number between 1 and 1000 (inclusive)
  340. let random_number: u64 = rng.gen_range(1..=1000);
  341. random_number.into()
  342. } else {
  343. amount
  344. };
  345. let payment_hash_clone = payment_hash.clone();
  346. let incoming_payment = self.incoming_payments.clone();
  347. let unit = self.unit.clone();
  348. tokio::spawn(async move {
  349. // Wait for the random delay to elapse
  350. time::sleep(duration).await;
  351. let response = WaitPaymentResponse {
  352. payment_identifier: payment_hash_clone.clone(),
  353. payment_amount: final_amount,
  354. unit,
  355. payment_id: payment_hash_clone.to_string(),
  356. };
  357. let mut incoming = incoming_payment.write().await;
  358. incoming
  359. .entry(payment_hash_clone.clone())
  360. .or_insert_with(Vec::new)
  361. .push(response.clone());
  362. // Send the message after waiting for the specified duration
  363. if sender
  364. .send((payment_hash_clone.clone(), final_amount))
  365. .await
  366. .is_err()
  367. {
  368. tracing::error!("Failed to send label: {:?}", payment_hash_clone);
  369. }
  370. });
  371. Ok(CreateIncomingPaymentResponse {
  372. request_lookup_id: payment_hash,
  373. request,
  374. expiry,
  375. })
  376. }
  377. #[instrument(skip_all)]
  378. async fn check_incoming_payment_status(
  379. &self,
  380. request_lookup_id: &PaymentIdentifier,
  381. ) -> Result<Vec<WaitPaymentResponse>, Self::Err> {
  382. Ok(self
  383. .incoming_payments
  384. .read()
  385. .await
  386. .get(request_lookup_id)
  387. .cloned()
  388. .unwrap_or(vec![]))
  389. }
  390. #[instrument(skip_all)]
  391. async fn check_outgoing_payment(
  392. &self,
  393. request_lookup_id: &PaymentIdentifier,
  394. ) -> Result<MakePaymentResponse, Self::Err> {
  395. // For fake wallet if the state is not explicitly set default to paid
  396. let states = self.payment_states.lock().await;
  397. let status = states.get(&request_lookup_id.to_string()).cloned();
  398. let status = status.unwrap_or(MeltQuoteState::Paid);
  399. let fail_payments = self.failed_payment_check.lock().await;
  400. if fail_payments.contains(&request_lookup_id.to_string()) {
  401. return Err(payment::Error::InvoicePaymentPending);
  402. }
  403. Ok(MakePaymentResponse {
  404. payment_proof: Some("".to_string()),
  405. payment_lookup_id: request_lookup_id.clone(),
  406. status,
  407. total_spent: Amount::ZERO,
  408. unit: CurrencyUnit::Msat,
  409. })
  410. }
  411. }
  412. /// Create fake invoice
  413. #[instrument]
  414. pub fn create_fake_invoice(amount_msat: u64, description: String) -> Bolt11Invoice {
  415. let private_key = SecretKey::from_slice(
  416. &[
  417. 0xe1, 0x26, 0xf6, 0x8f, 0x7e, 0xaf, 0xcc, 0x8b, 0x74, 0xf5, 0x4d, 0x26, 0x9f, 0xe2,
  418. 0x06, 0xbe, 0x71, 0x50, 0x00, 0xf9, 0x4d, 0xac, 0x06, 0x7d, 0x1c, 0x04, 0xa8, 0xca,
  419. 0x3b, 0x2d, 0xb7, 0x34,
  420. ][..],
  421. )
  422. .unwrap();
  423. let mut rng = thread_rng();
  424. let mut random_bytes = [0u8; 32];
  425. rng.fill(&mut random_bytes);
  426. let payment_hash = sha256::Hash::from_slice(&random_bytes).unwrap();
  427. let payment_secret = PaymentSecret([42u8; 32]);
  428. InvoiceBuilder::new(Currency::Bitcoin)
  429. .description(description)
  430. .payment_hash(payment_hash)
  431. .payment_secret(payment_secret)
  432. .amount_milli_satoshis(amount_msat)
  433. .current_timestamp()
  434. .min_final_cltv_expiry_delta(144)
  435. .build_signed(|hash| Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key))
  436. .unwrap()
  437. }