test_swap_flow.rs 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202
  1. //! Comprehensive tests for the current swap flow
  2. //!
  3. //! These tests validate the swap operation's behavior including:
  4. //! - Happy path: successful token swaps
  5. //! - Error handling: validation failures, rollback scenarios
  6. //! - Edge cases: concurrent operations, double-spending
  7. //! - State management: proof states, blinded message tracking
  8. //!
  9. //! The tests focus on the current implementation using ProofWriter and BlindedMessageWriter
  10. //! patterns to ensure proper cleanup and rollback behavior.
  11. use std::collections::HashMap;
  12. use std::sync::Arc;
  13. use cashu::amount::SplitTarget;
  14. use cashu::dhke::construct_proofs;
  15. use cashu::{CurrencyUnit, Id, PreMintSecrets, SecretKey, SpendingConditions, State, SwapRequest};
  16. use cdk::mint::Mint;
  17. use cdk::nuts::nut00::ProofsMethods;
  18. use cdk::Amount;
  19. use cdk_integration_tests::init_pure_tests::*;
  20. /// Helper to get the active keyset ID from a mint
  21. async fn get_keyset_id(mint: &Mint) -> Id {
  22. let keys = mint.pubkeys().keysets.first().unwrap().clone();
  23. keys.verify_id()
  24. .expect("Keyset ID generation is successful");
  25. keys.id
  26. }
  27. /// Tests the complete happy path of a swap operation:
  28. /// 1. Wallet is funded with tokens
  29. /// 2. Blinded messages are added to database
  30. /// 3. Outputs are signed by mint
  31. /// 4. Input proofs are verified
  32. /// 5. Transaction is balanced
  33. /// 6. Proofs are added and marked as spent
  34. /// 7. Blind signatures are saved
  35. /// All steps should succeed and database should be in consistent state.
  36. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  37. async fn test_swap_happy_path() {
  38. setup_tracing();
  39. let mint = create_and_start_test_mint()
  40. .await
  41. .expect("Failed to create test mint");
  42. let wallet = create_test_wallet_for_mint(mint.clone())
  43. .await
  44. .expect("Failed to create test wallet");
  45. // Fund wallet with 100 sats
  46. fund_wallet(wallet.clone(), 100, None)
  47. .await
  48. .expect("Failed to fund wallet");
  49. let proofs = wallet
  50. .get_unspent_proofs()
  51. .await
  52. .expect("Could not get proofs");
  53. let keyset_id = get_keyset_id(&mint).await;
  54. // Check initial amounts after minting
  55. let total_issued = mint.total_issued().await.unwrap();
  56. let total_redeemed = mint.total_redeemed().await.unwrap();
  57. let initial_issued = total_issued
  58. .get(&keyset_id)
  59. .copied()
  60. .unwrap_or(Amount::ZERO);
  61. let initial_redeemed = total_redeemed
  62. .get(&keyset_id)
  63. .copied()
  64. .unwrap_or(Amount::ZERO);
  65. assert_eq!(
  66. initial_issued,
  67. Amount::from(100),
  68. "Should have issued 100 sats"
  69. );
  70. assert_eq!(
  71. initial_redeemed,
  72. Amount::ZERO,
  73. "Should have redeemed 0 sats initially"
  74. );
  75. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  76. // Create swap request for same amount (100 sats)
  77. let preswap = PreMintSecrets::random(
  78. keyset_id,
  79. 100.into(),
  80. &SplitTarget::default(),
  81. &fee_and_amounts,
  82. )
  83. .expect("Failed to create preswap");
  84. let swap_request = SwapRequest::new(proofs.clone(), preswap.blinded_messages());
  85. // Execute swap
  86. let swap_response = mint
  87. .process_swap_request(swap_request)
  88. .await
  89. .expect("Swap should succeed");
  90. // Verify response contains correct number of signatures
  91. assert_eq!(
  92. swap_response.signatures.len(),
  93. preswap.blinded_messages().len(),
  94. "Should receive signature for each blinded message"
  95. );
  96. // Verify input proofs are marked as spent
  97. let states = mint
  98. .localstore()
  99. .get_proofs_states(&proofs.iter().map(|p| p.y().unwrap()).collect::<Vec<_>>())
  100. .await
  101. .expect("Failed to get proof states");
  102. for state in states {
  103. assert_eq!(
  104. State::Spent,
  105. state.expect("State should be known"),
  106. "All input proofs should be marked as spent"
  107. );
  108. }
  109. // Verify blind signatures were saved
  110. let saved_signatures = mint
  111. .localstore()
  112. .get_blind_signatures(
  113. &preswap
  114. .blinded_messages()
  115. .iter()
  116. .map(|bm| bm.blinded_secret)
  117. .collect::<Vec<_>>(),
  118. )
  119. .await
  120. .expect("Failed to get blind signatures");
  121. assert_eq!(
  122. saved_signatures.len(),
  123. swap_response.signatures.len(),
  124. "All signatures should be saved"
  125. );
  126. // Check keyset amounts after swap
  127. // Swap redeems old proofs (100 sats) and issues new proofs (100 sats)
  128. let total_issued = mint.total_issued().await.unwrap();
  129. let total_redeemed = mint.total_redeemed().await.unwrap();
  130. let after_issued = total_issued
  131. .get(&keyset_id)
  132. .copied()
  133. .unwrap_or(Amount::ZERO);
  134. let after_redeemed = total_redeemed
  135. .get(&keyset_id)
  136. .copied()
  137. .unwrap_or(Amount::ZERO);
  138. assert_eq!(
  139. after_issued,
  140. Amount::from(200),
  141. "Should have issued 200 sats total (initial 100 + swap 100)"
  142. );
  143. assert_eq!(
  144. after_redeemed,
  145. Amount::from(100),
  146. "Should have redeemed 100 sats from the swap"
  147. );
  148. }
  149. /// Tests that duplicate blinded messages are rejected:
  150. /// 1. First swap with blinded messages succeeds
  151. /// 2. Second swap attempt with same blinded messages fails
  152. /// 3. BlindedMessageWriter should prevent reuse
  153. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  154. async fn test_swap_duplicate_blinded_messages() {
  155. setup_tracing();
  156. let mint = create_and_start_test_mint()
  157. .await
  158. .expect("Failed to create test mint");
  159. let wallet = create_test_wallet_for_mint(mint.clone())
  160. .await
  161. .expect("Failed to create test wallet");
  162. // Fund wallet with 200 sats (enough for two swaps)
  163. fund_wallet(wallet.clone(), 200, None)
  164. .await
  165. .expect("Failed to fund wallet");
  166. let all_proofs = wallet
  167. .get_unspent_proofs()
  168. .await
  169. .expect("Could not get proofs");
  170. // Split proofs into two sets
  171. let mid = all_proofs.len() / 2;
  172. let proofs1: Vec<_> = all_proofs.iter().take(mid).cloned().collect();
  173. let proofs2: Vec<_> = all_proofs.iter().skip(mid).cloned().collect();
  174. let keyset_id = get_keyset_id(&mint).await;
  175. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  176. // Create blinded messages for first swap
  177. let preswap = PreMintSecrets::random(
  178. keyset_id,
  179. proofs1.total_amount().unwrap(),
  180. &SplitTarget::default(),
  181. &fee_and_amounts,
  182. )
  183. .expect("Failed to create preswap");
  184. let blinded_messages = preswap.blinded_messages();
  185. // First swap should succeed
  186. let swap_request1 = SwapRequest::new(proofs1, blinded_messages.clone());
  187. mint.process_swap_request(swap_request1)
  188. .await
  189. .expect("First swap should succeed");
  190. // Second swap with SAME blinded messages should fail
  191. let swap_request2 = SwapRequest::new(proofs2, blinded_messages.clone());
  192. let result = mint.process_swap_request(swap_request2).await;
  193. assert!(
  194. result.is_err(),
  195. "Second swap with duplicate blinded messages should fail"
  196. );
  197. }
  198. /// Tests that swap correctly rejects double-spending attempts:
  199. /// 1. First swap with proofs succeeds
  200. /// 2. Second swap with same proofs fails with TokenAlreadySpent
  201. /// 3. ProofWriter should detect already-spent proofs
  202. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  203. async fn test_swap_double_spend_detection() {
  204. setup_tracing();
  205. let mint = create_and_start_test_mint()
  206. .await
  207. .expect("Failed to create test mint");
  208. let wallet = create_test_wallet_for_mint(mint.clone())
  209. .await
  210. .expect("Failed to create test wallet");
  211. // Fund wallet with 100 sats
  212. fund_wallet(wallet.clone(), 100, None)
  213. .await
  214. .expect("Failed to fund wallet");
  215. let proofs = wallet
  216. .get_unspent_proofs()
  217. .await
  218. .expect("Could not get proofs");
  219. let keyset_id = get_keyset_id(&mint).await;
  220. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  221. // First swap
  222. let preswap1 = PreMintSecrets::random(
  223. keyset_id,
  224. 100.into(),
  225. &SplitTarget::default(),
  226. &fee_and_amounts,
  227. )
  228. .expect("Failed to create preswap");
  229. let swap_request1 = SwapRequest::new(proofs.clone(), preswap1.blinded_messages());
  230. mint.process_swap_request(swap_request1)
  231. .await
  232. .expect("First swap should succeed");
  233. // Second swap with same proofs should fail
  234. let preswap2 = PreMintSecrets::random(
  235. keyset_id,
  236. 100.into(),
  237. &SplitTarget::default(),
  238. &fee_and_amounts,
  239. )
  240. .expect("Failed to create preswap");
  241. let swap_request2 = SwapRequest::new(proofs.clone(), preswap2.blinded_messages());
  242. let result = mint.process_swap_request(swap_request2).await;
  243. match result {
  244. Err(cdk::Error::TokenAlreadySpent) => {
  245. // Expected error
  246. }
  247. Err(err) => panic!("Wrong error type: {:?}", err),
  248. Ok(_) => panic!("Double spend should not succeed"),
  249. }
  250. }
  251. /// Tests that unbalanced swap requests are rejected:
  252. /// Case 1: Output amount < Input amount (trying to steal from mint)
  253. /// Case 2: Output amount > Input amount (trying to create tokens)
  254. /// Both should fail with TransactionUnbalanced error.
  255. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  256. async fn test_swap_unbalanced_transaction_detection() {
  257. setup_tracing();
  258. let mint = create_and_start_test_mint()
  259. .await
  260. .expect("Failed to create test mint");
  261. let wallet = create_test_wallet_for_mint(mint.clone())
  262. .await
  263. .expect("Failed to create test wallet");
  264. // Fund wallet with 100 sats
  265. fund_wallet(wallet.clone(), 100, None)
  266. .await
  267. .expect("Failed to fund wallet");
  268. let proofs = wallet
  269. .get_unspent_proofs()
  270. .await
  271. .expect("Could not get proofs");
  272. let keyset_id = get_keyset_id(&mint).await;
  273. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  274. // Case 1: Try to swap for LESS (95 < 100) - underpaying
  275. let preswap_less = PreMintSecrets::random(
  276. keyset_id,
  277. 95.into(),
  278. &SplitTarget::default(),
  279. &fee_and_amounts,
  280. )
  281. .expect("Failed to create preswap");
  282. let swap_request_less = SwapRequest::new(proofs.clone(), preswap_less.blinded_messages());
  283. match mint.process_swap_request(swap_request_less).await {
  284. Err(cdk::Error::TransactionUnbalanced(_, _, _)) => {
  285. // Expected error
  286. }
  287. Err(err) => panic!("Wrong error type for underpay: {:?}", err),
  288. Ok(_) => panic!("Unbalanced swap (underpay) should not succeed"),
  289. }
  290. // Case 2: Try to swap for MORE (105 > 100) - overpaying/creating tokens
  291. let preswap_more = PreMintSecrets::random(
  292. keyset_id,
  293. 105.into(),
  294. &SplitTarget::default(),
  295. &fee_and_amounts,
  296. )
  297. .expect("Failed to create preswap");
  298. let swap_request_more = SwapRequest::new(proofs.clone(), preswap_more.blinded_messages());
  299. match mint.process_swap_request(swap_request_more).await {
  300. Err(cdk::Error::TransactionUnbalanced(_, _, _)) => {
  301. // Expected error
  302. }
  303. Err(err) => panic!("Wrong error type for overpay: {:?}", err),
  304. Ok(_) => panic!("Unbalanced swap (overpay) should not succeed"),
  305. }
  306. }
  307. /// Tests P2PK (Pay-to-Public-Key) spending conditions:
  308. /// 1. Create proofs locked to a public key
  309. /// 2. Attempt swap without signature - should fail
  310. /// 3. Attempt swap with valid signature - should succeed
  311. /// Validates NUT-11 signature enforcement.
  312. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  313. async fn test_swap_p2pk_signature_validation() {
  314. setup_tracing();
  315. let mint = create_and_start_test_mint()
  316. .await
  317. .expect("Failed to create test mint");
  318. let wallet = create_test_wallet_for_mint(mint.clone())
  319. .await
  320. .expect("Failed to create test wallet");
  321. // Fund wallet with 100 sats
  322. fund_wallet(wallet.clone(), 100, None)
  323. .await
  324. .expect("Failed to fund wallet");
  325. let input_proofs = wallet
  326. .get_unspent_proofs()
  327. .await
  328. .expect("Could not get proofs");
  329. let keyset_id = get_keyset_id(&mint).await;
  330. let secret_key = SecretKey::generate();
  331. // Create P2PK locked outputs
  332. let spending_conditions = SpendingConditions::new_p2pk(secret_key.public_key(), None);
  333. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  334. let pre_swap = PreMintSecrets::with_conditions(
  335. keyset_id,
  336. 100.into(),
  337. &SplitTarget::default(),
  338. &spending_conditions,
  339. &fee_and_amounts,
  340. )
  341. .expect("Failed to create P2PK preswap");
  342. let swap_request = SwapRequest::new(input_proofs.clone(), pre_swap.blinded_messages());
  343. // First swap to get P2PK locked proofs
  344. let keys = mint.pubkeys().keysets.first().cloned().unwrap().keys;
  345. let post_swap = mint
  346. .process_swap_request(swap_request)
  347. .await
  348. .expect("Initial swap should succeed");
  349. // Construct proofs from swap response
  350. let mut p2pk_proofs = construct_proofs(
  351. post_swap.signatures,
  352. pre_swap.rs(),
  353. pre_swap.secrets(),
  354. &keys,
  355. )
  356. .expect("Failed to construct proofs");
  357. // Try to spend P2PK proofs WITHOUT signature - should fail
  358. let preswap_unsigned = PreMintSecrets::random(
  359. keyset_id,
  360. 100.into(),
  361. &SplitTarget::default(),
  362. &fee_and_amounts,
  363. )
  364. .expect("Failed to create preswap");
  365. let swap_request_unsigned =
  366. SwapRequest::new(p2pk_proofs.clone(), preswap_unsigned.blinded_messages());
  367. match mint.process_swap_request(swap_request_unsigned).await {
  368. Err(cdk::Error::NUT11(cdk::nuts::nut11::Error::SignaturesNotProvided)) => {
  369. // Expected error
  370. }
  371. Err(err) => panic!("Wrong error type: {:?}", err),
  372. Ok(_) => panic!("Unsigned P2PK spend should fail"),
  373. }
  374. // Sign the proofs with correct key
  375. for proof in &mut p2pk_proofs {
  376. proof
  377. .sign_p2pk(secret_key.clone())
  378. .expect("Failed to sign proof");
  379. }
  380. // Try again WITH signature - should succeed
  381. let preswap_signed = PreMintSecrets::random(
  382. keyset_id,
  383. 100.into(),
  384. &SplitTarget::default(),
  385. &fee_and_amounts,
  386. )
  387. .expect("Failed to create preswap");
  388. let swap_request_signed = SwapRequest::new(p2pk_proofs, preswap_signed.blinded_messages());
  389. mint.process_swap_request(swap_request_signed)
  390. .await
  391. .expect("Signed P2PK spend should succeed");
  392. }
  393. /// Tests rollback behavior when duplicate blinded messages are used:
  394. /// This validates that the BlindedMessageWriter prevents reuse of blinded messages.
  395. /// 1. First swap with blinded messages succeeds
  396. /// 2. Second swap with same blinded messages fails
  397. /// 3. The failure should happen early (during blinded message addition)
  398. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  399. async fn test_swap_rollback_on_duplicate_blinded_message() {
  400. setup_tracing();
  401. let mint = create_and_start_test_mint()
  402. .await
  403. .expect("Failed to create test mint");
  404. let wallet = create_test_wallet_for_mint(mint.clone())
  405. .await
  406. .expect("Failed to create test wallet");
  407. // Fund with enough for multiple swaps
  408. fund_wallet(wallet.clone(), 200, None)
  409. .await
  410. .expect("Failed to fund wallet");
  411. let all_proofs = wallet
  412. .get_unspent_proofs()
  413. .await
  414. .expect("Could not get proofs");
  415. let mid = all_proofs.len() / 2;
  416. let proofs1: Vec<_> = all_proofs.iter().take(mid).cloned().collect();
  417. let proofs2: Vec<_> = all_proofs.iter().skip(mid).cloned().collect();
  418. let keyset_id = get_keyset_id(&mint).await;
  419. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  420. // Create shared blinded messages
  421. let preswap = PreMintSecrets::random(
  422. keyset_id,
  423. proofs1.total_amount().unwrap(),
  424. &SplitTarget::default(),
  425. &fee_and_amounts,
  426. )
  427. .expect("Failed to create preswap");
  428. let blinded_messages = preswap.blinded_messages();
  429. // Extract proof2 ys before moving proofs2
  430. let proof2_ys: Vec<_> = proofs2.iter().map(|p| p.y().unwrap()).collect();
  431. // First swap succeeds
  432. let swap1 = SwapRequest::new(proofs1, blinded_messages.clone());
  433. mint.process_swap_request(swap1)
  434. .await
  435. .expect("First swap should succeed");
  436. // Second swap with duplicate blinded messages should fail early
  437. // The BlindedMessageWriter should detect duplicate and prevent the swap
  438. let swap2 = SwapRequest::new(proofs2, blinded_messages.clone());
  439. let result = mint.process_swap_request(swap2).await;
  440. assert!(
  441. result.is_err(),
  442. "Duplicate blinded messages should cause failure"
  443. );
  444. // Verify the second set of proofs are NOT marked as spent
  445. // (since the swap failed before processing them)
  446. let states = mint
  447. .localstore()
  448. .get_proofs_states(&proof2_ys)
  449. .await
  450. .expect("Failed to get proof states");
  451. for state in states {
  452. assert!(
  453. state.is_none(),
  454. "Proofs from failed swap should not be marked as spent"
  455. );
  456. }
  457. }
  458. /// Tests concurrent swap attempts with same proofs:
  459. /// Spawns 3 concurrent tasks trying to swap the same proofs.
  460. /// Only one should succeed, others should fail with TokenAlreadySpent or TokenPending.
  461. /// Validates that concurrent access is properly handled.
  462. #[tokio::test(flavor = "multi_thread", worker_threads = 3)]
  463. async fn test_swap_concurrent_double_spend_prevention() {
  464. setup_tracing();
  465. let mint = create_and_start_test_mint()
  466. .await
  467. .expect("Failed to create test mint");
  468. let wallet = create_test_wallet_for_mint(mint.clone())
  469. .await
  470. .expect("Failed to create test wallet");
  471. // Fund wallet
  472. fund_wallet(wallet.clone(), 100, None)
  473. .await
  474. .expect("Failed to fund wallet");
  475. let proofs = wallet
  476. .get_unspent_proofs()
  477. .await
  478. .expect("Could not get proofs");
  479. let keyset_id = get_keyset_id(&mint).await;
  480. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  481. // Create 3 different swap requests with SAME proofs but different outputs
  482. let preswap1 = PreMintSecrets::random(
  483. keyset_id,
  484. 100.into(),
  485. &SplitTarget::default(),
  486. &fee_and_amounts,
  487. )
  488. .expect("Failed to create preswap 1");
  489. let preswap2 = PreMintSecrets::random(
  490. keyset_id,
  491. 100.into(),
  492. &SplitTarget::default(),
  493. &fee_and_amounts,
  494. )
  495. .expect("Failed to create preswap 2");
  496. let preswap3 = PreMintSecrets::random(
  497. keyset_id,
  498. 100.into(),
  499. &SplitTarget::default(),
  500. &fee_and_amounts,
  501. )
  502. .expect("Failed to create preswap 3");
  503. let swap_request1 = SwapRequest::new(proofs.clone(), preswap1.blinded_messages());
  504. let swap_request2 = SwapRequest::new(proofs.clone(), preswap2.blinded_messages());
  505. let swap_request3 = SwapRequest::new(proofs.clone(), preswap3.blinded_messages());
  506. // Spawn concurrent tasks
  507. let mint1 = mint.clone();
  508. let mint2 = mint.clone();
  509. let mint3 = mint.clone();
  510. let task1 = tokio::spawn(async move { mint1.process_swap_request(swap_request1).await });
  511. let task2 = tokio::spawn(async move { mint2.process_swap_request(swap_request2).await });
  512. let task3 = tokio::spawn(async move { mint3.process_swap_request(swap_request3).await });
  513. // Wait for all tasks
  514. let results = tokio::try_join!(task1, task2, task3).expect("Tasks should complete");
  515. // Count successes and failures
  516. let mut success_count = 0;
  517. let mut failure_count = 0;
  518. for result in [results.0, results.1, results.2] {
  519. match result {
  520. Ok(_) => success_count += 1,
  521. Err(cdk::Error::TokenAlreadySpent) | Err(cdk::Error::TokenPending) => {
  522. failure_count += 1
  523. }
  524. Err(err) => panic!("Unexpected error: {:?}", err),
  525. }
  526. }
  527. assert_eq!(
  528. success_count, 1,
  529. "Exactly one swap should succeed in concurrent scenario"
  530. );
  531. assert_eq!(
  532. failure_count, 2,
  533. "Exactly two swaps should fail in concurrent scenario"
  534. );
  535. // Verify all proofs are marked as spent
  536. let states = mint
  537. .localstore()
  538. .get_proofs_states(&proofs.iter().map(|p| p.y().unwrap()).collect::<Vec<_>>())
  539. .await
  540. .expect("Failed to get proof states");
  541. for state in states {
  542. assert_eq!(
  543. State::Spent,
  544. state.expect("State should be known"),
  545. "All proofs should be marked as spent after concurrent attempts"
  546. );
  547. }
  548. }
  549. /// Tests swap with fees enabled:
  550. /// 1. Create mint with keyset that has fees (1 sat per proof)
  551. /// 2. Fund wallet with many small proofs
  552. /// 3. Attempt swap without paying fee - should fail
  553. /// 4. Attempt swap with correct fee deduction - should succeed
  554. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  555. async fn test_swap_with_fees() {
  556. setup_tracing();
  557. let mint = create_and_start_test_mint()
  558. .await
  559. .expect("Failed to create test mint");
  560. let wallet = create_test_wallet_for_mint(mint.clone())
  561. .await
  562. .expect("Failed to create test wallet");
  563. // Rotate to keyset with 1 sat per proof fee
  564. mint.rotate_keyset(CurrencyUnit::Sat, 32, 1)
  565. .await
  566. .expect("Failed to rotate keyset");
  567. // Fund with 1000 sats as individual 1-sat proofs using the fee-based keyset
  568. // Wait a bit for keyset to be available
  569. tokio::time::sleep(std::time::Duration::from_millis(100)).await;
  570. fund_wallet(wallet.clone(), 1000, Some(SplitTarget::Value(Amount::ONE)))
  571. .await
  572. .expect("Failed to fund wallet");
  573. let proofs = wallet
  574. .get_unspent_proofs()
  575. .await
  576. .expect("Could not get proofs");
  577. // Take 100 proofs (100 sats total, will need to pay fee)
  578. let hundred_proofs: Vec<_> = proofs.iter().take(100).cloned().collect();
  579. // Get the keyset ID from the proofs (which will be the fee-based keyset)
  580. let keyset_id = hundred_proofs[0].keyset_id;
  581. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  582. // Try to swap for 100 outputs (same as input) - should fail due to unpaid fee
  583. let preswap_no_fee = PreMintSecrets::random(
  584. keyset_id,
  585. 100.into(),
  586. &SplitTarget::default(),
  587. &fee_and_amounts,
  588. )
  589. .expect("Failed to create preswap");
  590. let swap_no_fee = SwapRequest::new(hundred_proofs.clone(), preswap_no_fee.blinded_messages());
  591. match mint.process_swap_request(swap_no_fee).await {
  592. Err(cdk::Error::TransactionUnbalanced(_, _, _)) => {
  593. // Expected - didn't pay the fee
  594. }
  595. Err(err) => panic!("Wrong error type: {:?}", err),
  596. Ok(_) => panic!("Should fail when fee not paid"),
  597. }
  598. // Calculate correct fee (1 sat per input proof in this keyset)
  599. let fee = hundred_proofs.len() as u64; // 1 sat per proof = 100 sats fee
  600. let output_amount = 100 - fee;
  601. // Swap with correct fee deduction - should succeed if output_amount > 0
  602. if output_amount > 0 {
  603. let preswap_with_fee = PreMintSecrets::random(
  604. keyset_id,
  605. output_amount.into(),
  606. &SplitTarget::default(),
  607. &fee_and_amounts,
  608. )
  609. .expect("Failed to create preswap with fee");
  610. let swap_with_fee =
  611. SwapRequest::new(hundred_proofs.clone(), preswap_with_fee.blinded_messages());
  612. mint.process_swap_request(swap_with_fee)
  613. .await
  614. .expect("Swap with correct fee should succeed");
  615. }
  616. }
  617. /// Tests that swap correctly handles amount overflow:
  618. /// Attempts to create outputs that would overflow u64 when summed.
  619. /// This should be rejected before any database operations occur.
  620. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  621. async fn test_swap_amount_overflow_protection() {
  622. setup_tracing();
  623. let mint = create_and_start_test_mint()
  624. .await
  625. .expect("Failed to create test mint");
  626. let wallet = create_test_wallet_for_mint(mint.clone())
  627. .await
  628. .expect("Failed to create test wallet");
  629. // Fund wallet
  630. fund_wallet(wallet.clone(), 100, None)
  631. .await
  632. .expect("Failed to fund wallet");
  633. let proofs = wallet
  634. .get_unspent_proofs()
  635. .await
  636. .expect("Could not get proofs");
  637. let keyset_id = get_keyset_id(&mint).await;
  638. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  639. // Try to create outputs that would overflow
  640. // 2^63 + 2^63 + small amount would overflow u64
  641. let large_amount = 2_u64.pow(63);
  642. let pre_mint1 = PreMintSecrets::random(
  643. keyset_id,
  644. large_amount.into(),
  645. &SplitTarget::default(),
  646. &fee_and_amounts,
  647. )
  648. .expect("Failed to create pre_mint1");
  649. let pre_mint2 = PreMintSecrets::random(
  650. keyset_id,
  651. large_amount.into(),
  652. &SplitTarget::default(),
  653. &fee_and_amounts,
  654. )
  655. .expect("Failed to create pre_mint2");
  656. let mut combined_pre_mint = PreMintSecrets::random(
  657. keyset_id,
  658. 1.into(),
  659. &SplitTarget::default(),
  660. &fee_and_amounts,
  661. )
  662. .expect("Failed to create combined_pre_mint");
  663. combined_pre_mint.combine(pre_mint1);
  664. combined_pre_mint.combine(pre_mint2);
  665. let swap_request = SwapRequest::new(proofs, combined_pre_mint.blinded_messages());
  666. // Should fail with overflow/amount error
  667. match mint.process_swap_request(swap_request).await {
  668. Err(cdk::Error::NUT03(cdk::nuts::nut03::Error::Amount(_)))
  669. | Err(cdk::Error::AmountOverflow)
  670. | Err(cdk::Error::AmountError(_))
  671. | Err(cdk::Error::TransactionUnbalanced(_, _, _)) => {
  672. // Any of these errors are acceptable for overflow
  673. }
  674. Err(err) => panic!("Unexpected error type: {:?}", err),
  675. Ok(_) => panic!("Overflow swap should not succeed"),
  676. }
  677. }
  678. /// Tests swap state transitions through pubsub notifications:
  679. /// 1. Subscribe to proof state changes
  680. /// 2. Execute swap
  681. /// 3. Verify Pending then Spent state transitions are received
  682. /// Validates NUT-17 notification behavior.
  683. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  684. async fn test_swap_state_transition_notifications() {
  685. setup_tracing();
  686. let mint = create_and_start_test_mint()
  687. .await
  688. .expect("Failed to create test mint");
  689. let wallet = create_test_wallet_for_mint(mint.clone())
  690. .await
  691. .expect("Failed to create test wallet");
  692. // Fund wallet
  693. fund_wallet(wallet.clone(), 100, None)
  694. .await
  695. .expect("Failed to fund wallet");
  696. let proofs = wallet
  697. .get_unspent_proofs()
  698. .await
  699. .expect("Could not get proofs");
  700. let keyset_id = get_keyset_id(&mint).await;
  701. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  702. let preswap = PreMintSecrets::random(
  703. keyset_id,
  704. 100.into(),
  705. &SplitTarget::default(),
  706. &fee_and_amounts,
  707. )
  708. .expect("Failed to create preswap");
  709. let swap_request = SwapRequest::new(proofs.clone(), preswap.blinded_messages());
  710. // Subscribe to proof state changes
  711. let proof_ys: Vec<String> = proofs.iter().map(|p| p.y().unwrap().to_string()).collect();
  712. let mut listener = mint
  713. .pubsub_manager()
  714. .subscribe(cdk::subscription::Params {
  715. kind: cdk::nuts::nut17::Kind::ProofState,
  716. filters: proof_ys.clone(),
  717. id: Arc::new("test_swap_notifications".into()),
  718. })
  719. .expect("Should subscribe successfully");
  720. // Execute swap
  721. mint.process_swap_request(swap_request)
  722. .await
  723. .expect("Swap should succeed");
  724. // Give pubsub time to deliver messages
  725. tokio::time::sleep(std::time::Duration::from_millis(100)).await;
  726. // Collect all state transition notifications
  727. let mut state_transitions: HashMap<String, Vec<State>> = HashMap::new();
  728. while let Some(msg) = listener.try_recv() {
  729. match msg.into_inner() {
  730. cashu::NotificationPayload::ProofState(cashu::ProofState { y, state, .. }) => {
  731. state_transitions
  732. .entry(y.to_string())
  733. .or_insert_with(Vec::new)
  734. .push(state);
  735. }
  736. _ => panic!("Unexpected notification type"),
  737. }
  738. }
  739. // Verify each proof went through Pending -> Spent transition
  740. for y in proof_ys {
  741. let transitions = state_transitions
  742. .get(&y)
  743. .expect("Should have transitions for proof");
  744. assert_eq!(
  745. transitions,
  746. &vec![State::Pending, State::Spent],
  747. "Proof should transition from Pending to Spent"
  748. );
  749. }
  750. }
  751. /// Tests that swap fails gracefully when proof states cannot be updated:
  752. /// This would test the rollback path where proofs are added but state update fails.
  753. /// In the current implementation, this should trigger rollback of both proofs and blinded messages.
  754. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  755. async fn test_swap_proof_state_consistency() {
  756. setup_tracing();
  757. let mint = create_and_start_test_mint()
  758. .await
  759. .expect("Failed to create test mint");
  760. let wallet = create_test_wallet_for_mint(mint.clone())
  761. .await
  762. .expect("Failed to create test wallet");
  763. // Fund wallet
  764. fund_wallet(wallet.clone(), 100, None)
  765. .await
  766. .expect("Failed to fund wallet");
  767. let proofs = wallet
  768. .get_unspent_proofs()
  769. .await
  770. .expect("Could not get proofs");
  771. let keyset_id = get_keyset_id(&mint).await;
  772. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  773. // Execute successful swap
  774. let preswap = PreMintSecrets::random(
  775. keyset_id,
  776. 100.into(),
  777. &SplitTarget::default(),
  778. &fee_and_amounts,
  779. )
  780. .expect("Failed to create preswap");
  781. let swap_request = SwapRequest::new(proofs.clone(), preswap.blinded_messages());
  782. mint.process_swap_request(swap_request)
  783. .await
  784. .expect("Swap should succeed");
  785. // Verify all proofs have consistent state (Spent)
  786. let proof_ys: Vec<_> = proofs.iter().map(|p| p.y().unwrap()).collect();
  787. let states = mint
  788. .localstore()
  789. .get_proofs_states(&proof_ys)
  790. .await
  791. .expect("Failed to get proof states");
  792. // All states should be Some(Spent) - none should be None or Pending
  793. for (i, state) in states.iter().enumerate() {
  794. match state {
  795. Some(State::Spent) => {
  796. // Expected state
  797. }
  798. Some(other_state) => {
  799. panic!("Proof {} in unexpected state: {:?}", i, other_state)
  800. }
  801. None => {
  802. panic!("Proof {} has no state (should be Spent)", i)
  803. }
  804. }
  805. }
  806. }
  807. /// Tests that wallet correctly increments keyset counters when receiving proofs
  808. /// from multiple keysets and then performing operations with them.
  809. ///
  810. /// This test validates:
  811. /// 1. Wallet can receive proofs from multiple different keysets
  812. /// 2. Counter is correctly incremented for the target keyset during swap
  813. /// 3. Database maintains separate counters for each keyset
  814. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  815. async fn test_wallet_multi_keyset_counter_updates() {
  816. setup_tracing();
  817. let mint = create_and_start_test_mint()
  818. .await
  819. .expect("Failed to create test mint");
  820. let wallet = create_test_wallet_for_mint(mint.clone())
  821. .await
  822. .expect("Failed to create test wallet");
  823. // Fund wallet with initial 100 sats using first keyset
  824. fund_wallet(wallet.clone(), 100, None)
  825. .await
  826. .expect("Failed to fund wallet");
  827. let first_keyset_id = get_keyset_id(&mint).await;
  828. // Rotate to a second keyset
  829. mint.rotate_keyset(CurrencyUnit::Sat, 32, 0)
  830. .await
  831. .expect("Failed to rotate keyset");
  832. // Wait for keyset rotation to propagate
  833. tokio::time::sleep(std::time::Duration::from_millis(100)).await;
  834. // Refresh wallet keysets to know about the new keyset
  835. wallet
  836. .refresh_keysets()
  837. .await
  838. .expect("Failed to refresh wallet keysets");
  839. // Fund wallet again with 100 sats using second keyset
  840. fund_wallet(wallet.clone(), 100, None)
  841. .await
  842. .expect("Failed to fund wallet with second keyset");
  843. let second_keyset_id = mint
  844. .pubkeys()
  845. .keysets
  846. .iter()
  847. .find(|k| k.id != first_keyset_id)
  848. .expect("Should have second keyset")
  849. .id;
  850. // Verify we now have proofs from two different keysets
  851. let all_proofs = wallet
  852. .get_unspent_proofs()
  853. .await
  854. .expect("Could not get proofs");
  855. let keysets_in_use: std::collections::HashSet<_> =
  856. all_proofs.iter().map(|p| p.keyset_id).collect();
  857. assert_eq!(
  858. keysets_in_use.len(),
  859. 2,
  860. "Should have proofs from 2 different keysets"
  861. );
  862. assert!(
  863. keysets_in_use.contains(&first_keyset_id),
  864. "Should have proofs from first keyset"
  865. );
  866. assert!(
  867. keysets_in_use.contains(&second_keyset_id),
  868. "Should have proofs from second keyset"
  869. );
  870. // Get initial total issued and redeemed for both keysets before swap
  871. let total_issued_before = mint.total_issued().await.unwrap();
  872. let total_redeemed_before = mint.total_redeemed().await.unwrap();
  873. let first_keyset_issued_before = total_issued_before
  874. .get(&first_keyset_id)
  875. .copied()
  876. .unwrap_or(Amount::ZERO);
  877. let first_keyset_redeemed_before = total_redeemed_before
  878. .get(&first_keyset_id)
  879. .copied()
  880. .unwrap_or(Amount::ZERO);
  881. let second_keyset_issued_before = total_issued_before
  882. .get(&second_keyset_id)
  883. .copied()
  884. .unwrap_or(Amount::ZERO);
  885. let second_keyset_redeemed_before = total_redeemed_before
  886. .get(&second_keyset_id)
  887. .copied()
  888. .unwrap_or(Amount::ZERO);
  889. tracing::info!(
  890. "Before swap - First keyset: issued={}, redeemed={}",
  891. first_keyset_issued_before,
  892. first_keyset_redeemed_before
  893. );
  894. tracing::info!(
  895. "Before swap - Second keyset: issued={}, redeemed={}",
  896. second_keyset_issued_before,
  897. second_keyset_redeemed_before
  898. );
  899. // Both keysets should have issued 100 sats
  900. assert_eq!(
  901. first_keyset_issued_before,
  902. Amount::from(100),
  903. "First keyset should have issued 100 sats"
  904. );
  905. assert_eq!(
  906. second_keyset_issued_before,
  907. Amount::from(100),
  908. "Second keyset should have issued 100 sats"
  909. );
  910. // Neither should have redeemed anything yet
  911. assert_eq!(
  912. first_keyset_redeemed_before,
  913. Amount::ZERO,
  914. "First keyset should have redeemed 0 sats before swap"
  915. );
  916. assert_eq!(
  917. second_keyset_redeemed_before,
  918. Amount::ZERO,
  919. "Second keyset should have redeemed 0 sats before swap"
  920. );
  921. // Now perform a swap with all proofs - this should only increment the counter
  922. // for the active (second) keyset, not for the first keyset
  923. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  924. let total_amount = all_proofs.total_amount().expect("Should get total amount");
  925. // Create swap using the active (second) keyset
  926. let preswap = PreMintSecrets::random(
  927. second_keyset_id,
  928. total_amount,
  929. &SplitTarget::default(),
  930. &fee_and_amounts,
  931. )
  932. .expect("Failed to create preswap");
  933. let swap_request = SwapRequest::new(all_proofs.clone(), preswap.blinded_messages());
  934. // Execute the swap
  935. let swap_response = mint
  936. .process_swap_request(swap_request)
  937. .await
  938. .expect("Swap should succeed");
  939. // Verify response
  940. assert_eq!(
  941. swap_response.signatures.len(),
  942. preswap.blinded_messages().len(),
  943. "Should receive signature for each blinded message"
  944. );
  945. // All the new proofs should be from the second (active) keyset
  946. let keys = mint
  947. .pubkeys()
  948. .keysets
  949. .iter()
  950. .find(|k| k.id == second_keyset_id)
  951. .expect("Should find second keyset")
  952. .keys
  953. .clone();
  954. let new_proofs = construct_proofs(
  955. swap_response.signatures,
  956. preswap.rs(),
  957. preswap.secrets(),
  958. &keys,
  959. )
  960. .expect("Failed to construct proofs");
  961. // Verify all new proofs use the second keyset
  962. for proof in &new_proofs {
  963. assert_eq!(
  964. proof.keyset_id, second_keyset_id,
  965. "All new proofs should use the active (second) keyset"
  966. );
  967. }
  968. // Verify total issued and redeemed after swap
  969. let total_issued_after = mint.total_issued().await.unwrap();
  970. let total_redeemed_after = mint.total_redeemed().await.unwrap();
  971. let first_keyset_issued_after = total_issued_after
  972. .get(&first_keyset_id)
  973. .copied()
  974. .unwrap_or(Amount::ZERO);
  975. let first_keyset_redeemed_after = total_redeemed_after
  976. .get(&first_keyset_id)
  977. .copied()
  978. .unwrap_or(Amount::ZERO);
  979. let second_keyset_issued_after = total_issued_after
  980. .get(&second_keyset_id)
  981. .copied()
  982. .unwrap_or(Amount::ZERO);
  983. let second_keyset_redeemed_after = total_redeemed_after
  984. .get(&second_keyset_id)
  985. .copied()
  986. .unwrap_or(Amount::ZERO);
  987. tracing::info!(
  988. "After swap - First keyset: issued={}, redeemed={}",
  989. first_keyset_issued_after,
  990. first_keyset_redeemed_after
  991. );
  992. tracing::info!(
  993. "After swap - Second keyset: issued={}, redeemed={}",
  994. second_keyset_issued_after,
  995. second_keyset_redeemed_after
  996. );
  997. // After swap:
  998. // - First keyset: issued stays 100, redeemed increases by 100 (all its proofs were spent in swap)
  999. // - Second keyset: issued increases by 200 (original 100 + new 100 from swap output),
  1000. // redeemed increases by 100 (its proofs from first funding were spent)
  1001. assert_eq!(
  1002. first_keyset_issued_after,
  1003. Amount::from(100),
  1004. "First keyset issued should stay 100 sats (no new issuance)"
  1005. );
  1006. assert_eq!(
  1007. first_keyset_redeemed_after,
  1008. Amount::from(100),
  1009. "First keyset should have redeemed 100 sats (all its proofs spent in swap)"
  1010. );
  1011. assert_eq!(
  1012. second_keyset_issued_after,
  1013. Amount::from(300),
  1014. "Second keyset should have issued 300 sats total (100 initial + 100 the second funding + 100 from swap output from the old keyset)"
  1015. );
  1016. assert_eq!(
  1017. second_keyset_redeemed_after,
  1018. Amount::from(100),
  1019. "Second keyset should have redeemed 100 sats (its proofs from initial funding spent in swap)"
  1020. );
  1021. // The test verifies that:
  1022. // 1. We can have proofs from multiple keysets in a wallet
  1023. // 2. Swap operation processes inputs from any keyset but creates outputs using active keyset
  1024. // 3. The keyset_counter table correctly handles counters for different keysets independently
  1025. // 4. The database upsert logic in increment_keyset_counter works for multiple keysets
  1026. // 5. Total issued and redeemed are tracked correctly per keyset during multi-keyset swaps
  1027. }