mint.rs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. //! Mint Tests
  2. //!
  3. //! This file contains tests that focus on the mint's internal functionality without client interaction.
  4. //! These tests verify the mint's behavior in isolation, such as keyset management, database operations,
  5. //! and other mint-specific functionality that doesn't require wallet clients.
  6. //!
  7. //! Test Categories:
  8. //! - Keyset rotation and management
  9. //! - Database transaction handling
  10. //! - Internal state transitions
  11. //! - Fee calculation and enforcement
  12. //! - Proof validation and state management
  13. use std::collections::{HashMap, HashSet};
  14. use std::sync::Arc;
  15. use bip39::Mnemonic;
  16. use cdk::mint::{MintBuilder, MintMeltLimits};
  17. use cdk::nuts::{CurrencyUnit, PaymentMethod};
  18. use cdk::types::{FeeReserve, QuoteTTL};
  19. use cdk_fake_wallet::FakeWallet;
  20. use cdk_sqlite::mint::memory;
  21. pub const MINT_URL: &str = "http://127.0.0.1:8088";
  22. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  23. async fn test_correct_keyset() {
  24. let mnemonic = Mnemonic::generate(12).unwrap();
  25. let fee_reserve = FeeReserve {
  26. min_fee_reserve: 1.into(),
  27. percent_fee_reserve: 1.0,
  28. };
  29. let database = memory::empty().await.expect("valid db instance");
  30. let fake_wallet = FakeWallet::new(
  31. fee_reserve,
  32. HashMap::default(),
  33. HashSet::default(),
  34. 0,
  35. CurrencyUnit::Sat,
  36. );
  37. let localstore = Arc::new(database);
  38. let mut mint_builder = MintBuilder::new(localstore.clone());
  39. mint_builder = mint_builder
  40. .with_name("regtest mint".to_string())
  41. .with_description("regtest mint".to_string());
  42. mint_builder
  43. .add_payment_processor(
  44. CurrencyUnit::Sat,
  45. PaymentMethod::Bolt11,
  46. MintMeltLimits::new(1, 5_000),
  47. Arc::new(fake_wallet),
  48. )
  49. .await
  50. .unwrap();
  51. // .with_seed(mnemonic.to_seed_normalized("").to_vec());
  52. let mint = mint_builder
  53. .build_with_seed(localstore.clone(), &mnemonic.to_seed_normalized(""))
  54. .await
  55. .unwrap();
  56. let quote_ttl = QuoteTTL::new(10000, 10000);
  57. mint.set_quote_ttl(quote_ttl).await.unwrap();
  58. let active = mint.get_active_keysets();
  59. let active = active
  60. .get(&CurrencyUnit::Sat)
  61. .expect("There is a keyset for unit");
  62. let old_keyset_info = mint.get_keyset_info(active).expect("There is keyset");
  63. mint.rotate_keyset(CurrencyUnit::Sat, (0..32).map(|n| 2u64.pow(n)).collect(), 0)
  64. .await
  65. .unwrap();
  66. let active = mint.get_active_keysets();
  67. let active = active
  68. .get(&CurrencyUnit::Sat)
  69. .expect("There is a keyset for unit");
  70. let keyset_info = mint.get_keyset_info(active).expect("There is keyset");
  71. assert_ne!(keyset_info.id, old_keyset_info.id);
  72. mint.rotate_keyset(CurrencyUnit::Sat, (0..32).map(|n| 2u64.pow(n)).collect(), 0)
  73. .await
  74. .unwrap();
  75. let active = mint.get_active_keysets();
  76. let active = active
  77. .get(&CurrencyUnit::Sat)
  78. .expect("There is a keyset for unit");
  79. let new_keyset_info = mint.get_keyset_info(active).expect("There is keyset");
  80. assert_ne!(new_keyset_info.id, keyset_info.id);
  81. }
  82. /// Test concurrent payment processing to verify race condition fix
  83. ///
  84. /// This test simulates the real-world race condition where multiple concurrent
  85. /// payment notifications arrive for the same payment_id. Before the fix, this
  86. /// would cause "Payment ID already exists" errors. After the fix, all but one
  87. /// should gracefully handle the duplicate and return a Duplicate error.
  88. #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
  89. async fn test_concurrent_duplicate_payment_handling() {
  90. use cashu::PaymentMethod;
  91. use cdk::cdk_database::{MintDatabase, MintQuotesDatabase};
  92. use cdk::mint::MintQuote;
  93. use cdk::Amount;
  94. use cdk_common::payment::PaymentIdentifier;
  95. use tokio::task::JoinSet;
  96. // Create a test mint with in-memory database
  97. let mnemonic = Mnemonic::generate(12).unwrap();
  98. let fee_reserve = FeeReserve {
  99. min_fee_reserve: 1.into(),
  100. percent_fee_reserve: 1.0,
  101. };
  102. let database = Arc::new(memory::empty().await.expect("valid db instance"));
  103. let fake_wallet = FakeWallet::new(
  104. fee_reserve,
  105. HashMap::default(),
  106. HashSet::default(),
  107. 0,
  108. CurrencyUnit::Sat,
  109. );
  110. let mut mint_builder = MintBuilder::new(database.clone());
  111. mint_builder = mint_builder
  112. .with_name("concurrent test mint".to_string())
  113. .with_description("testing concurrent payment handling".to_string());
  114. mint_builder
  115. .add_payment_processor(
  116. CurrencyUnit::Sat,
  117. PaymentMethod::Bolt11,
  118. MintMeltLimits::new(1, 5_000),
  119. Arc::new(fake_wallet),
  120. )
  121. .await
  122. .unwrap();
  123. let mint = mint_builder
  124. .build_with_seed(database.clone(), &mnemonic.to_seed_normalized(""))
  125. .await
  126. .unwrap();
  127. let quote_ttl = QuoteTTL::new(10000, 10000);
  128. mint.set_quote_ttl(quote_ttl).await.unwrap();
  129. // Create a mint quote
  130. let current_time = cdk::util::unix_time();
  131. let mint_quote = MintQuote::new(
  132. None,
  133. "concurrent_test_invoice".to_string(),
  134. CurrencyUnit::Sat,
  135. Some(Amount::from(1000)),
  136. current_time + 3600, // expires in 1 hour
  137. PaymentIdentifier::CustomId("test_lookup_id".to_string()),
  138. None,
  139. Amount::ZERO,
  140. Amount::ZERO,
  141. PaymentMethod::Bolt11,
  142. current_time,
  143. vec![],
  144. vec![],
  145. );
  146. // Add the quote to the database
  147. {
  148. let mut tx = MintDatabase::begin_transaction(&*database).await.unwrap();
  149. tx.add_mint_quote(mint_quote.clone()).await.unwrap();
  150. tx.commit().await.unwrap();
  151. }
  152. // Simulate 10 concurrent payment notifications with the SAME payment_id
  153. let payment_id = "duplicate_payment_test_12345";
  154. let mut join_set = JoinSet::new();
  155. for i in 0..10 {
  156. let db_clone = database.clone();
  157. let quote_id = mint_quote.id.clone();
  158. let payment_id_clone = payment_id.to_string();
  159. join_set.spawn(async move {
  160. let mut tx = MintDatabase::begin_transaction(&*db_clone).await.unwrap();
  161. let result = tx
  162. .increment_mint_quote_amount_paid(&quote_id, Amount::from(10), payment_id_clone)
  163. .await;
  164. if result.is_ok() {
  165. tx.commit().await.unwrap();
  166. }
  167. (i, result)
  168. });
  169. }
  170. // Collect results
  171. let mut success_count = 0;
  172. let mut duplicate_errors = 0;
  173. let mut other_errors = Vec::new();
  174. while let Some(result) = join_set.join_next().await {
  175. let (task_id, db_result) = result.unwrap();
  176. match db_result {
  177. Ok(_) => success_count += 1,
  178. Err(e) => {
  179. let err_str = format!("{:?}", e);
  180. if err_str.contains("Duplicate") {
  181. duplicate_errors += 1;
  182. } else {
  183. other_errors.push((task_id, err_str));
  184. }
  185. }
  186. }
  187. }
  188. // Verify results
  189. assert_eq!(
  190. success_count, 1,
  191. "Exactly one task should successfully process the payment (got {})",
  192. success_count
  193. );
  194. assert_eq!(
  195. duplicate_errors, 9,
  196. "Nine tasks should receive Duplicate error (got {})",
  197. duplicate_errors
  198. );
  199. assert!(
  200. other_errors.is_empty(),
  201. "No unexpected errors should occur. Got: {:?}",
  202. other_errors
  203. );
  204. // Verify the quote was incremented exactly once
  205. let final_quote = MintQuotesDatabase::get_mint_quote(&*database, &mint_quote.id)
  206. .await
  207. .unwrap()
  208. .expect("Quote should exist");
  209. assert_eq!(
  210. final_quote.amount_paid(),
  211. Amount::from(10),
  212. "Quote amount should be incremented exactly once"
  213. );
  214. assert_eq!(
  215. final_quote.payments.len(),
  216. 1,
  217. "Should have exactly one payment recorded"
  218. );
  219. assert_eq!(
  220. final_quote.payments[0].payment_id, payment_id,
  221. "Payment ID should match"
  222. );
  223. }