mint.rs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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, 32, 0).await.unwrap();
  64. let active = mint.get_active_keysets();
  65. let active = active
  66. .get(&CurrencyUnit::Sat)
  67. .expect("There is a keyset for unit");
  68. let keyset_info = mint.get_keyset_info(active).expect("There is keyset");
  69. assert_ne!(keyset_info.id, old_keyset_info.id);
  70. mint.rotate_keyset(CurrencyUnit::Sat, 32, 0).await.unwrap();
  71. let active = mint.get_active_keysets();
  72. let active = active
  73. .get(&CurrencyUnit::Sat)
  74. .expect("There is a keyset for unit");
  75. let new_keyset_info = mint.get_keyset_info(active).expect("There is keyset");
  76. assert_ne!(new_keyset_info.id, keyset_info.id);
  77. }
  78. /// Test concurrent payment processing to verify race condition fix
  79. ///
  80. /// This test simulates the real-world race condition where multiple concurrent
  81. /// payment notifications arrive for the same payment_id. Before the fix, this
  82. /// would cause "Payment ID already exists" errors. After the fix, all but one
  83. /// should gracefully handle the duplicate and return a Duplicate error.
  84. #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
  85. async fn test_concurrent_duplicate_payment_handling() {
  86. use cashu::PaymentMethod;
  87. use cdk::cdk_database::{MintDatabase, MintQuotesDatabase};
  88. use cdk::mint::MintQuote;
  89. use cdk::Amount;
  90. use cdk_common::payment::PaymentIdentifier;
  91. use tokio::task::JoinSet;
  92. // Create a test mint with in-memory database
  93. let mnemonic = Mnemonic::generate(12).unwrap();
  94. let fee_reserve = FeeReserve {
  95. min_fee_reserve: 1.into(),
  96. percent_fee_reserve: 1.0,
  97. };
  98. let database = Arc::new(memory::empty().await.expect("valid db instance"));
  99. let fake_wallet = FakeWallet::new(
  100. fee_reserve,
  101. HashMap::default(),
  102. HashSet::default(),
  103. 0,
  104. CurrencyUnit::Sat,
  105. );
  106. let mut mint_builder = MintBuilder::new(database.clone());
  107. mint_builder = mint_builder
  108. .with_name("concurrent test mint".to_string())
  109. .with_description("testing concurrent payment handling".to_string());
  110. mint_builder
  111. .add_payment_processor(
  112. CurrencyUnit::Sat,
  113. PaymentMethod::Bolt11,
  114. MintMeltLimits::new(1, 5_000),
  115. Arc::new(fake_wallet),
  116. )
  117. .await
  118. .unwrap();
  119. let mint = mint_builder
  120. .build_with_seed(database.clone(), &mnemonic.to_seed_normalized(""))
  121. .await
  122. .unwrap();
  123. let quote_ttl = QuoteTTL::new(10000, 10000);
  124. mint.set_quote_ttl(quote_ttl).await.unwrap();
  125. // Create a mint quote
  126. let current_time = cdk::util::unix_time();
  127. let mint_quote = MintQuote::new(
  128. None,
  129. "concurrent_test_invoice".to_string(),
  130. CurrencyUnit::Sat,
  131. Some(Amount::from(1000)),
  132. current_time + 3600, // expires in 1 hour
  133. PaymentIdentifier::CustomId("test_lookup_id".to_string()),
  134. None,
  135. Amount::ZERO,
  136. Amount::ZERO,
  137. PaymentMethod::Bolt11,
  138. current_time,
  139. vec![],
  140. vec![],
  141. );
  142. // Add the quote to the database
  143. {
  144. let mut tx = MintDatabase::begin_transaction(&*database).await.unwrap();
  145. tx.add_mint_quote(mint_quote.clone()).await.unwrap();
  146. tx.commit().await.unwrap();
  147. }
  148. // Simulate 10 concurrent payment notifications with the SAME payment_id
  149. let payment_id = "duplicate_payment_test_12345";
  150. let mut join_set = JoinSet::new();
  151. for i in 0..10 {
  152. let db_clone = database.clone();
  153. let quote_id = mint_quote.id.clone();
  154. let payment_id_clone = payment_id.to_string();
  155. join_set.spawn(async move {
  156. let mut tx = MintDatabase::begin_transaction(&*db_clone).await.unwrap();
  157. let result = tx
  158. .increment_mint_quote_amount_paid(&quote_id, Amount::from(10), payment_id_clone)
  159. .await;
  160. if result.is_ok() {
  161. tx.commit().await.unwrap();
  162. }
  163. (i, result)
  164. });
  165. }
  166. // Collect results
  167. let mut success_count = 0;
  168. let mut duplicate_errors = 0;
  169. let mut other_errors = Vec::new();
  170. while let Some(result) = join_set.join_next().await {
  171. let (task_id, db_result) = result.unwrap();
  172. match db_result {
  173. Ok(_) => success_count += 1,
  174. Err(e) => {
  175. let err_str = format!("{:?}", e);
  176. if err_str.contains("Duplicate") {
  177. duplicate_errors += 1;
  178. } else {
  179. other_errors.push((task_id, err_str));
  180. }
  181. }
  182. }
  183. }
  184. // Verify results
  185. assert_eq!(
  186. success_count, 1,
  187. "Exactly one task should successfully process the payment (got {})",
  188. success_count
  189. );
  190. assert_eq!(
  191. duplicate_errors, 9,
  192. "Nine tasks should receive Duplicate error (got {})",
  193. duplicate_errors
  194. );
  195. assert!(
  196. other_errors.is_empty(),
  197. "No unexpected errors should occur. Got: {:?}",
  198. other_errors
  199. );
  200. // Verify the quote was incremented exactly once
  201. let final_quote = MintQuotesDatabase::get_mint_quote(&*database, &mint_quote.id)
  202. .await
  203. .unwrap()
  204. .expect("Quote should exist");
  205. assert_eq!(
  206. final_quote.amount_paid(),
  207. Amount::from(10),
  208. "Quote amount should be incremented exactly once"
  209. );
  210. assert_eq!(
  211. final_quote.payments.len(),
  212. 1,
  213. "Should have exactly one payment recorded"
  214. );
  215. assert_eq!(
  216. final_quote.payments[0].payment_id, payment_id,
  217. "Payment ID should match"
  218. );
  219. }