lib.rs 17 KB

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