test_swap_flow.rs 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703
  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_fake_wallet::create_fake_invoice;
  20. use cdk_integration_tests::init_pure_tests::*;
  21. /// Helper to get the active keyset ID from a mint
  22. async fn get_keyset_id(mint: &Mint) -> Id {
  23. let keys = mint.pubkeys().keysets.first().unwrap().clone();
  24. keys.verify_id()
  25. .expect("Keyset ID generation is successful");
  26. keys.id
  27. }
  28. /// Tests the complete happy path of a swap operation:
  29. /// 1. Wallet is funded with tokens
  30. /// 2. Blinded messages are added to database
  31. /// 3. Outputs are signed by mint
  32. /// 4. Input proofs are verified
  33. /// 5. Transaction is balanced
  34. /// 6. Proofs are added and marked as spent
  35. /// 7. Blind signatures are saved
  36. /// All steps should succeed and database should be in consistent state.
  37. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  38. async fn test_swap_happy_path() {
  39. setup_tracing();
  40. let mint = create_and_start_test_mint()
  41. .await
  42. .expect("Failed to create test mint");
  43. let wallet = create_test_wallet_for_mint(mint.clone())
  44. .await
  45. .expect("Failed to create test wallet");
  46. // Fund wallet with 100 sats
  47. fund_wallet(wallet.clone(), 100, None)
  48. .await
  49. .expect("Failed to fund wallet");
  50. let proofs = wallet
  51. .get_unspent_proofs()
  52. .await
  53. .expect("Could not get proofs");
  54. let keyset_id = get_keyset_id(&mint).await;
  55. // Check initial amounts after minting
  56. let total_issued = mint.total_issued().await.unwrap();
  57. let total_redeemed = mint.total_redeemed().await.unwrap();
  58. let initial_issued = total_issued
  59. .get(&keyset_id)
  60. .copied()
  61. .unwrap_or(Amount::ZERO);
  62. let initial_redeemed = total_redeemed
  63. .get(&keyset_id)
  64. .copied()
  65. .unwrap_or(Amount::ZERO);
  66. assert_eq!(
  67. initial_issued,
  68. Amount::from(100),
  69. "Should have issued 100 sats"
  70. );
  71. assert_eq!(
  72. initial_redeemed,
  73. Amount::ZERO,
  74. "Should have redeemed 0 sats initially"
  75. );
  76. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  77. // Create swap request for same amount (100 sats)
  78. let preswap = PreMintSecrets::random(
  79. keyset_id,
  80. 100.into(),
  81. &SplitTarget::default(),
  82. &fee_and_amounts,
  83. )
  84. .expect("Failed to create preswap");
  85. let swap_request = SwapRequest::new(proofs.clone(), preswap.blinded_messages());
  86. // Execute swap
  87. let swap_response = mint
  88. .process_swap_request(swap_request)
  89. .await
  90. .expect("Swap should succeed");
  91. // Verify response contains correct number of signatures
  92. assert_eq!(
  93. swap_response.signatures.len(),
  94. preswap.blinded_messages().len(),
  95. "Should receive signature for each blinded message"
  96. );
  97. // Verify input proofs are marked as spent
  98. let states = mint
  99. .localstore()
  100. .get_proofs_states(&proofs.iter().map(|p| p.y().unwrap()).collect::<Vec<_>>())
  101. .await
  102. .expect("Failed to get proof states");
  103. for state in states {
  104. assert_eq!(
  105. State::Spent,
  106. state.expect("State should be known"),
  107. "All input proofs should be marked as spent"
  108. );
  109. }
  110. // Verify blind signatures were saved
  111. let saved_signatures = mint
  112. .localstore()
  113. .get_blind_signatures(
  114. &preswap
  115. .blinded_messages()
  116. .iter()
  117. .map(|bm| bm.blinded_secret)
  118. .collect::<Vec<_>>(),
  119. )
  120. .await
  121. .expect("Failed to get blind signatures");
  122. assert_eq!(
  123. saved_signatures.len(),
  124. swap_response.signatures.len(),
  125. "All signatures should be saved"
  126. );
  127. // Check keyset amounts after swap
  128. // Swap redeems old proofs (100 sats) and issues new proofs (100 sats)
  129. let total_issued = mint.total_issued().await.unwrap();
  130. let total_redeemed = mint.total_redeemed().await.unwrap();
  131. let after_issued = total_issued
  132. .get(&keyset_id)
  133. .copied()
  134. .unwrap_or(Amount::ZERO);
  135. let after_redeemed = total_redeemed
  136. .get(&keyset_id)
  137. .copied()
  138. .unwrap_or(Amount::ZERO);
  139. assert_eq!(
  140. after_issued,
  141. Amount::from(200),
  142. "Should have issued 200 sats total (initial 100 + swap 100)"
  143. );
  144. assert_eq!(
  145. after_redeemed,
  146. Amount::from(100),
  147. "Should have redeemed 100 sats from the swap"
  148. );
  149. }
  150. /// Tests that duplicate blinded messages are rejected:
  151. /// 1. First swap with blinded messages succeeds
  152. /// 2. Second swap attempt with same blinded messages fails
  153. /// 3. BlindedMessageWriter should prevent reuse
  154. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  155. async fn test_swap_duplicate_blinded_messages() {
  156. setup_tracing();
  157. let mint = create_and_start_test_mint()
  158. .await
  159. .expect("Failed to create test mint");
  160. let wallet = create_test_wallet_for_mint(mint.clone())
  161. .await
  162. .expect("Failed to create test wallet");
  163. // Fund wallet with 200 sats (enough for two swaps)
  164. fund_wallet(wallet.clone(), 200, None)
  165. .await
  166. .expect("Failed to fund wallet");
  167. let all_proofs = wallet
  168. .get_unspent_proofs()
  169. .await
  170. .expect("Could not get proofs");
  171. // Split proofs into two sets
  172. let mid = all_proofs.len() / 2;
  173. let proofs1: Vec<_> = all_proofs.iter().take(mid).cloned().collect();
  174. let proofs2: Vec<_> = all_proofs.iter().skip(mid).cloned().collect();
  175. let keyset_id = get_keyset_id(&mint).await;
  176. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  177. // Create blinded messages for first swap
  178. let preswap = PreMintSecrets::random(
  179. keyset_id,
  180. proofs1.total_amount().unwrap(),
  181. &SplitTarget::default(),
  182. &fee_and_amounts,
  183. )
  184. .expect("Failed to create preswap");
  185. let blinded_messages = preswap.blinded_messages();
  186. // First swap should succeed
  187. let swap_request1 = SwapRequest::new(proofs1, blinded_messages.clone());
  188. mint.process_swap_request(swap_request1)
  189. .await
  190. .expect("First swap should succeed");
  191. // Second swap with SAME blinded messages should fail
  192. let swap_request2 = SwapRequest::new(proofs2, blinded_messages.clone());
  193. let result = mint.process_swap_request(swap_request2).await;
  194. assert!(
  195. result.is_err(),
  196. "Second swap with duplicate blinded messages should fail"
  197. );
  198. }
  199. /// Tests that swap correctly rejects double-spending attempts:
  200. /// 1. First swap with proofs succeeds
  201. /// 2. Second swap with same proofs fails with TokenAlreadySpent
  202. /// 3. ProofWriter should detect already-spent proofs
  203. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  204. async fn test_swap_double_spend_detection() {
  205. setup_tracing();
  206. let mint = create_and_start_test_mint()
  207. .await
  208. .expect("Failed to create test mint");
  209. let wallet = create_test_wallet_for_mint(mint.clone())
  210. .await
  211. .expect("Failed to create test wallet");
  212. // Fund wallet with 100 sats
  213. fund_wallet(wallet.clone(), 100, None)
  214. .await
  215. .expect("Failed to fund wallet");
  216. let proofs = wallet
  217. .get_unspent_proofs()
  218. .await
  219. .expect("Could not get proofs");
  220. let keyset_id = get_keyset_id(&mint).await;
  221. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  222. // First swap
  223. let preswap1 = PreMintSecrets::random(
  224. keyset_id,
  225. 100.into(),
  226. &SplitTarget::default(),
  227. &fee_and_amounts,
  228. )
  229. .expect("Failed to create preswap");
  230. let swap_request1 = SwapRequest::new(proofs.clone(), preswap1.blinded_messages());
  231. mint.process_swap_request(swap_request1)
  232. .await
  233. .expect("First swap should succeed");
  234. // Second swap with same proofs should fail
  235. let preswap2 = PreMintSecrets::random(
  236. keyset_id,
  237. 100.into(),
  238. &SplitTarget::default(),
  239. &fee_and_amounts,
  240. )
  241. .expect("Failed to create preswap");
  242. let swap_request2 = SwapRequest::new(proofs.clone(), preswap2.blinded_messages());
  243. let result = mint.process_swap_request(swap_request2).await;
  244. match result {
  245. Err(cdk::Error::TokenAlreadySpent) => {
  246. // Expected error
  247. }
  248. Err(err) => panic!("Wrong error type: {:?}", err),
  249. Ok(_) => panic!("Double spend should not succeed"),
  250. }
  251. }
  252. /// Tests that unbalanced swap requests are rejected:
  253. /// Case 1: Output amount < Input amount (trying to steal from mint)
  254. /// Case 2: Output amount > Input amount (trying to create tokens)
  255. /// Both should fail with TransactionUnbalanced error.
  256. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  257. async fn test_swap_unbalanced_transaction_detection() {
  258. setup_tracing();
  259. let mint = create_and_start_test_mint()
  260. .await
  261. .expect("Failed to create test mint");
  262. let wallet = create_test_wallet_for_mint(mint.clone())
  263. .await
  264. .expect("Failed to create test wallet");
  265. // Fund wallet with 100 sats
  266. fund_wallet(wallet.clone(), 100, None)
  267. .await
  268. .expect("Failed to fund wallet");
  269. let proofs = wallet
  270. .get_unspent_proofs()
  271. .await
  272. .expect("Could not get proofs");
  273. let keyset_id = get_keyset_id(&mint).await;
  274. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  275. // Case 1: Try to swap for LESS (95 < 100) - underpaying
  276. let preswap_less = PreMintSecrets::random(
  277. keyset_id,
  278. 95.into(),
  279. &SplitTarget::default(),
  280. &fee_and_amounts,
  281. )
  282. .expect("Failed to create preswap");
  283. let swap_request_less = SwapRequest::new(proofs.clone(), preswap_less.blinded_messages());
  284. match mint.process_swap_request(swap_request_less).await {
  285. Err(cdk::Error::TransactionUnbalanced(_, _, _)) => {
  286. // Expected error
  287. }
  288. Err(err) => panic!("Wrong error type for underpay: {:?}", err),
  289. Ok(_) => panic!("Unbalanced swap (underpay) should not succeed"),
  290. }
  291. // Case 2: Try to swap for MORE (105 > 100) - overpaying/creating tokens
  292. let preswap_more = PreMintSecrets::random(
  293. keyset_id,
  294. 105.into(),
  295. &SplitTarget::default(),
  296. &fee_and_amounts,
  297. )
  298. .expect("Failed to create preswap");
  299. let swap_request_more = SwapRequest::new(proofs.clone(), preswap_more.blinded_messages());
  300. match mint.process_swap_request(swap_request_more).await {
  301. Err(cdk::Error::TransactionUnbalanced(_, _, _)) => {
  302. // Expected error
  303. }
  304. Err(err) => panic!("Wrong error type for overpay: {:?}", err),
  305. Ok(_) => panic!("Unbalanced swap (overpay) should not succeed"),
  306. }
  307. }
  308. /// Tests that swap requests with empty inputs or outputs are rejected:
  309. /// Case 1: Empty outputs (inputs without outputs)
  310. /// Case 2: Empty inputs (outputs without inputs)
  311. /// Both should fail. Currently returns UnitMismatch (11010) instead of
  312. /// TransactionUnbalanced (11002) because there are no keyset IDs to determine units.
  313. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  314. async fn test_swap_empty_inputs_or_outputs() {
  315. setup_tracing();
  316. let mint = create_and_start_test_mint()
  317. .await
  318. .expect("Failed to create test mint");
  319. let wallet = create_test_wallet_for_mint(mint.clone())
  320. .await
  321. .expect("Failed to create test wallet");
  322. // Fund wallet with 100 sats
  323. fund_wallet(wallet.clone(), 100, None)
  324. .await
  325. .expect("Failed to fund wallet");
  326. let proofs = wallet
  327. .get_unspent_proofs()
  328. .await
  329. .expect("Could not get proofs");
  330. // Case 1: Swap request with inputs but empty outputs
  331. // This represents trying to destroy tokens (inputs with no outputs)
  332. let swap_request_empty_outputs = SwapRequest::new(proofs.clone(), vec![]);
  333. match mint.process_swap_request(swap_request_empty_outputs).await {
  334. Err(cdk::Error::TransactionUnbalanced(_, _, _)) => {
  335. // This would be the more appropriate error
  336. }
  337. Err(err) => panic!("Wrong error type for empty outputs: {:?}", err),
  338. Ok(_) => panic!("Swap with empty outputs should not succeed"),
  339. }
  340. // Case 2: Swap request with empty inputs but with outputs
  341. // This represents trying to create tokens from nothing
  342. let keyset_id = get_keyset_id(&mint).await;
  343. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  344. let preswap = PreMintSecrets::random(
  345. keyset_id,
  346. 100.into(),
  347. &SplitTarget::default(),
  348. &fee_and_amounts,
  349. )
  350. .expect("Failed to create preswap");
  351. let swap_request_empty_inputs = SwapRequest::new(vec![], preswap.blinded_messages());
  352. match mint.process_swap_request(swap_request_empty_inputs).await {
  353. Err(cdk::Error::TransactionUnbalanced(_, _, _)) => {
  354. // This would be the more appropriate error
  355. }
  356. Err(err) => panic!("Wrong error type for empty inputs: {:?}", err),
  357. Ok(_) => panic!("Swap with empty inputs should not succeed"),
  358. }
  359. }
  360. /// Tests P2PK (Pay-to-Public-Key) spending conditions:
  361. /// 1. Create proofs locked to a public key
  362. /// 2. Attempt swap without signature - should fail
  363. /// 3. Attempt swap with valid signature - should succeed
  364. /// Validates NUT-11 signature enforcement.
  365. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  366. async fn test_swap_p2pk_signature_validation() {
  367. setup_tracing();
  368. let mint = create_and_start_test_mint()
  369. .await
  370. .expect("Failed to create test mint");
  371. let wallet = create_test_wallet_for_mint(mint.clone())
  372. .await
  373. .expect("Failed to create test wallet");
  374. // Fund wallet with 100 sats
  375. fund_wallet(wallet.clone(), 100, None)
  376. .await
  377. .expect("Failed to fund wallet");
  378. let input_proofs = wallet
  379. .get_unspent_proofs()
  380. .await
  381. .expect("Could not get proofs");
  382. let keyset_id = get_keyset_id(&mint).await;
  383. let secret_key = SecretKey::generate();
  384. // Create P2PK locked outputs
  385. let spending_conditions = SpendingConditions::new_p2pk(secret_key.public_key(), None);
  386. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  387. let pre_swap = PreMintSecrets::with_conditions(
  388. keyset_id,
  389. 100.into(),
  390. &SplitTarget::default(),
  391. &spending_conditions,
  392. &fee_and_amounts,
  393. )
  394. .expect("Failed to create P2PK preswap");
  395. let swap_request = SwapRequest::new(input_proofs.clone(), pre_swap.blinded_messages());
  396. // First swap to get P2PK locked proofs
  397. let keys = mint.pubkeys().keysets.first().cloned().unwrap().keys;
  398. let post_swap = mint
  399. .process_swap_request(swap_request)
  400. .await
  401. .expect("Initial swap should succeed");
  402. // Construct proofs from swap response
  403. let mut p2pk_proofs = construct_proofs(
  404. post_swap.signatures,
  405. pre_swap.rs(),
  406. pre_swap.secrets(),
  407. &keys,
  408. )
  409. .expect("Failed to construct proofs");
  410. // Try to spend P2PK proofs WITHOUT signature - should fail
  411. let preswap_unsigned = PreMintSecrets::random(
  412. keyset_id,
  413. 100.into(),
  414. &SplitTarget::default(),
  415. &fee_and_amounts,
  416. )
  417. .expect("Failed to create preswap");
  418. let swap_request_unsigned =
  419. SwapRequest::new(p2pk_proofs.clone(), preswap_unsigned.blinded_messages());
  420. match mint.process_swap_request(swap_request_unsigned).await {
  421. Err(cdk::Error::NUT11(cdk::nuts::nut11::Error::SignaturesNotProvided)) => {
  422. // Expected error
  423. }
  424. Err(err) => panic!("Wrong error type: {:?}", err),
  425. Ok(_) => panic!("Unsigned P2PK spend should fail"),
  426. }
  427. // Sign the proofs with correct key
  428. for proof in &mut p2pk_proofs {
  429. proof
  430. .sign_p2pk(secret_key.clone())
  431. .expect("Failed to sign proof");
  432. }
  433. // Try again WITH signature - should succeed
  434. let preswap_signed = PreMintSecrets::random(
  435. keyset_id,
  436. 100.into(),
  437. &SplitTarget::default(),
  438. &fee_and_amounts,
  439. )
  440. .expect("Failed to create preswap");
  441. let swap_request_signed = SwapRequest::new(p2pk_proofs, preswap_signed.blinded_messages());
  442. mint.process_swap_request(swap_request_signed)
  443. .await
  444. .expect("Signed P2PK spend should succeed");
  445. }
  446. /// Tests rollback behavior when duplicate blinded messages are used:
  447. /// This validates that the BlindedMessageWriter prevents reuse of blinded messages.
  448. /// 1. First swap with blinded messages succeeds
  449. /// 2. Second swap with same blinded messages fails
  450. /// 3. The failure should happen early (during blinded message addition)
  451. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  452. async fn test_swap_rollback_on_duplicate_blinded_message() {
  453. setup_tracing();
  454. let mint = create_and_start_test_mint()
  455. .await
  456. .expect("Failed to create test mint");
  457. let wallet = create_test_wallet_for_mint(mint.clone())
  458. .await
  459. .expect("Failed to create test wallet");
  460. // Fund with enough for multiple swaps
  461. fund_wallet(wallet.clone(), 200, None)
  462. .await
  463. .expect("Failed to fund wallet");
  464. let all_proofs = wallet
  465. .get_unspent_proofs()
  466. .await
  467. .expect("Could not get proofs");
  468. let mid = all_proofs.len() / 2;
  469. let proofs1: Vec<_> = all_proofs.iter().take(mid).cloned().collect();
  470. let proofs2: Vec<_> = all_proofs.iter().skip(mid).cloned().collect();
  471. let keyset_id = get_keyset_id(&mint).await;
  472. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  473. // Create shared blinded messages
  474. let preswap = PreMintSecrets::random(
  475. keyset_id,
  476. proofs1.total_amount().unwrap(),
  477. &SplitTarget::default(),
  478. &fee_and_amounts,
  479. )
  480. .expect("Failed to create preswap");
  481. let blinded_messages = preswap.blinded_messages();
  482. // Extract proof2 ys before moving proofs2
  483. let proof2_ys: Vec<_> = proofs2.iter().map(|p| p.y().unwrap()).collect();
  484. // First swap succeeds
  485. let swap1 = SwapRequest::new(proofs1, blinded_messages.clone());
  486. mint.process_swap_request(swap1)
  487. .await
  488. .expect("First swap should succeed");
  489. // Second swap with duplicate blinded messages should fail early
  490. // The BlindedMessageWriter should detect duplicate and prevent the swap
  491. let swap2 = SwapRequest::new(proofs2, blinded_messages.clone());
  492. let result = mint.process_swap_request(swap2).await;
  493. assert!(
  494. result.is_err(),
  495. "Duplicate blinded messages should cause failure"
  496. );
  497. // Verify the second set of proofs are NOT marked as spent
  498. // (since the swap failed before processing them)
  499. let states = mint
  500. .localstore()
  501. .get_proofs_states(&proof2_ys)
  502. .await
  503. .expect("Failed to get proof states");
  504. for state in states {
  505. assert!(
  506. state.is_none(),
  507. "Proofs from failed swap should not be marked as spent"
  508. );
  509. }
  510. }
  511. /// Tests concurrent swap attempts with same proofs:
  512. /// Spawns 3 concurrent tasks trying to swap the same proofs.
  513. /// Only one should succeed, others should fail with TokenAlreadySpent or TokenPending.
  514. /// Validates that concurrent access is properly handled.
  515. #[tokio::test(flavor = "multi_thread", worker_threads = 3)]
  516. async fn test_swap_concurrent_double_spend_prevention() {
  517. setup_tracing();
  518. let mint = create_and_start_test_mint()
  519. .await
  520. .expect("Failed to create test mint");
  521. let wallet = create_test_wallet_for_mint(mint.clone())
  522. .await
  523. .expect("Failed to create test wallet");
  524. // Fund wallet
  525. fund_wallet(wallet.clone(), 100, None)
  526. .await
  527. .expect("Failed to fund wallet");
  528. let proofs = wallet
  529. .get_unspent_proofs()
  530. .await
  531. .expect("Could not get proofs");
  532. let keyset_id = get_keyset_id(&mint).await;
  533. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  534. // Create 3 different swap requests with SAME proofs but different outputs
  535. let preswap1 = PreMintSecrets::random(
  536. keyset_id,
  537. 100.into(),
  538. &SplitTarget::default(),
  539. &fee_and_amounts,
  540. )
  541. .expect("Failed to create preswap 1");
  542. let preswap2 = PreMintSecrets::random(
  543. keyset_id,
  544. 100.into(),
  545. &SplitTarget::default(),
  546. &fee_and_amounts,
  547. )
  548. .expect("Failed to create preswap 2");
  549. let preswap3 = PreMintSecrets::random(
  550. keyset_id,
  551. 100.into(),
  552. &SplitTarget::default(),
  553. &fee_and_amounts,
  554. )
  555. .expect("Failed to create preswap 3");
  556. let swap_request1 = SwapRequest::new(proofs.clone(), preswap1.blinded_messages());
  557. let swap_request2 = SwapRequest::new(proofs.clone(), preswap2.blinded_messages());
  558. let swap_request3 = SwapRequest::new(proofs.clone(), preswap3.blinded_messages());
  559. // Spawn concurrent tasks
  560. let mint1 = mint.clone();
  561. let mint2 = mint.clone();
  562. let mint3 = mint.clone();
  563. let task1 = tokio::spawn(async move { mint1.process_swap_request(swap_request1).await });
  564. let task2 = tokio::spawn(async move { mint2.process_swap_request(swap_request2).await });
  565. let task3 = tokio::spawn(async move { mint3.process_swap_request(swap_request3).await });
  566. // Wait for all tasks
  567. let results = tokio::try_join!(task1, task2, task3).expect("Tasks should complete");
  568. // Count successes and failures
  569. let mut success_count = 0;
  570. let mut failure_count = 0;
  571. for result in [results.0, results.1, results.2] {
  572. match result {
  573. Ok(_) => success_count += 1,
  574. Err(cdk::Error::TokenAlreadySpent) | Err(cdk::Error::TokenPending) => {
  575. failure_count += 1
  576. }
  577. Err(err) => panic!("Unexpected error: {:?}", err),
  578. }
  579. }
  580. assert_eq!(
  581. success_count, 1,
  582. "Exactly one swap should succeed in concurrent scenario"
  583. );
  584. assert_eq!(
  585. failure_count, 2,
  586. "Exactly two swaps should fail in concurrent scenario"
  587. );
  588. // Verify all proofs are marked as spent
  589. let states = mint
  590. .localstore()
  591. .get_proofs_states(&proofs.iter().map(|p| p.y().unwrap()).collect::<Vec<_>>())
  592. .await
  593. .expect("Failed to get proof states");
  594. for state in states {
  595. assert_eq!(
  596. State::Spent,
  597. state.expect("State should be known"),
  598. "All proofs should be marked as spent after concurrent attempts"
  599. );
  600. }
  601. }
  602. /// Tests swap with fees enabled:
  603. /// 1. Create mint with keyset that has fees (1 sat per proof)
  604. /// 2. Fund wallet with many small proofs
  605. /// 3. Attempt swap without paying fee - should fail
  606. /// 4. Attempt swap with correct fee deduction - should succeed
  607. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  608. async fn test_swap_with_fees() {
  609. setup_tracing();
  610. let mint = create_and_start_test_mint()
  611. .await
  612. .expect("Failed to create test mint");
  613. let wallet = create_test_wallet_for_mint(mint.clone())
  614. .await
  615. .expect("Failed to create test wallet");
  616. // Rotate to keyset with 1 sat per proof fee
  617. mint.rotate_keyset(
  618. CurrencyUnit::Sat,
  619. cdk_integration_tests::standard_keyset_amounts(32),
  620. 100,
  621. )
  622. .await
  623. .expect("Failed to rotate keyset");
  624. // Fund with 1000 sats as individual 1-sat proofs using the fee-based keyset
  625. // Wait a bit for keyset to be available
  626. tokio::time::sleep(std::time::Duration::from_millis(100)).await;
  627. fund_wallet(wallet.clone(), 1000, Some(SplitTarget::Value(Amount::ONE)))
  628. .await
  629. .expect("Failed to fund wallet");
  630. let proofs = wallet
  631. .get_unspent_proofs()
  632. .await
  633. .expect("Could not get proofs");
  634. // Take 100 proofs (100 sats total, will need to pay fee)
  635. let hundred_proofs: Vec<_> = proofs.iter().take(100).cloned().collect();
  636. // Get the keyset ID from the proofs (which will be the fee-based keyset)
  637. let keyset_id = hundred_proofs[0].keyset_id;
  638. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  639. // Try to swap for 100 outputs (same as input) - should fail due to unpaid fee
  640. let preswap_no_fee = PreMintSecrets::random(
  641. keyset_id,
  642. 100.into(),
  643. &SplitTarget::default(),
  644. &fee_and_amounts,
  645. )
  646. .expect("Failed to create preswap");
  647. let swap_no_fee = SwapRequest::new(hundred_proofs.clone(), preswap_no_fee.blinded_messages());
  648. match mint.process_swap_request(swap_no_fee).await {
  649. Err(cdk::Error::TransactionUnbalanced(_, _, _)) => {
  650. // Expected - didn't pay the fee
  651. }
  652. Err(err) => panic!("Wrong error type: {:?}", err),
  653. Ok(_) => panic!("Should fail when fee not paid"),
  654. }
  655. // Calculate correct fee (1 sat per input proof in this keyset)
  656. let fee = hundred_proofs.len() as u64; // 1 sat per proof = 100 sats fee
  657. let output_amount = 100 - fee;
  658. // Swap with correct fee deduction - should succeed if output_amount > 0
  659. if output_amount > 0 {
  660. let preswap_with_fee = PreMintSecrets::random(
  661. keyset_id,
  662. output_amount.into(),
  663. &SplitTarget::default(),
  664. &fee_and_amounts,
  665. )
  666. .expect("Failed to create preswap with fee");
  667. let swap_with_fee =
  668. SwapRequest::new(hundred_proofs.clone(), preswap_with_fee.blinded_messages());
  669. mint.process_swap_request(swap_with_fee)
  670. .await
  671. .expect("Swap with correct fee should succeed");
  672. }
  673. }
  674. /// Tests melt with fees enabled and swap-before-melt optimization:
  675. /// 1. Create mint with keyset that has fees (1000 ppk = 1 sat per proof)
  676. /// 2. Fund wallet with proofs using default split (optimal denominations)
  677. /// 3. Call melt() - should automatically swap if proofs don't match exactly
  678. /// 4. Verify fee calculations are reasonable
  679. ///
  680. /// Fee calculation:
  681. /// - Initial: 4096 sats in optimal denominations
  682. /// - Melt: 1000 sats, fee_reserve = 20 sats (2%)
  683. /// - inputs_needed = 1020 sats
  684. /// - Target split for 1020: [512, 256, 128, 64, 32, 16, 8, 4] = 8 proofs
  685. /// - target_fee = 8 sats
  686. /// - inputs_total_needed = 1028 sats
  687. ///
  688. /// The wallet uses two-step selection:
  689. /// - Step 1: Try to find exact proofs for inputs_needed (no swap fee)
  690. /// - Step 2: If not exact, select proofs for inputs_total_needed and swap
  691. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  692. async fn test_melt_with_fees_swap_before_melt() {
  693. setup_tracing();
  694. let mint = create_and_start_test_mint()
  695. .await
  696. .expect("Failed to create test mint");
  697. let wallet = create_test_wallet_for_mint(mint.clone())
  698. .await
  699. .expect("Failed to create test wallet");
  700. // Rotate to keyset with 1000 ppk = 1 sat per proof fee
  701. mint.rotate_keyset(
  702. CurrencyUnit::Sat,
  703. cdk_integration_tests::standard_keyset_amounts(32),
  704. 1000, // 1 sat per proof
  705. )
  706. .await
  707. .expect("Failed to rotate keyset");
  708. tokio::time::sleep(std::time::Duration::from_millis(100)).await;
  709. // Fund with default split target to get optimal denominations
  710. // Use larger amount to ensure enough margin for swap fees
  711. let initial_amount = 4096u64;
  712. fund_wallet(wallet.clone(), initial_amount, None)
  713. .await
  714. .expect("Failed to fund wallet");
  715. let initial_balance: u64 = wallet.total_balance().await.unwrap().into();
  716. assert_eq!(initial_balance, initial_amount);
  717. let proofs = wallet.get_unspent_proofs().await.unwrap();
  718. let proof_amounts: Vec<u64> = proofs.iter().map(|p| u64::from(p.amount)).collect();
  719. tracing::info!("Proofs after funding: {:?}", proof_amounts);
  720. let proofs_total: u64 = proof_amounts.iter().sum();
  721. assert_eq!(
  722. proofs_total, initial_amount,
  723. "Total proofs should equal funded amount"
  724. );
  725. // Create melt quote for 1000 sats (1_000_000 msats)
  726. // Fake wallet: fee_reserve = max(1, amount * 2%) = 20 sats
  727. let invoice = create_fake_invoice(1_000_000, "".to_string()); // 1000 sats in msats
  728. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  729. let quote_amount: u64 = melt_quote.amount.into();
  730. let fee_reserve: u64 = melt_quote.fee_reserve.into();
  731. tracing::info!(
  732. "Melt quote: amount={}, fee_reserve={}",
  733. quote_amount,
  734. fee_reserve
  735. );
  736. let initial_proof_count = proofs.len();
  737. tracing::info!(
  738. "Initial state: {} proofs, {} sats",
  739. initial_proof_count,
  740. proofs_total
  741. );
  742. // Perform melt
  743. let melted = wallet.melt(&melt_quote.id).await.unwrap();
  744. let melt_amount: u64 = melted.amount.into();
  745. let ln_fee_paid: u64 = melted.fee_paid.into();
  746. tracing::info!(
  747. "Melt completed: amount={}, ln_fee_paid={}",
  748. melt_amount,
  749. ln_fee_paid
  750. );
  751. assert_eq!(melt_amount, quote_amount, "Melt amount should match quote");
  752. // Get final balance and calculate fees
  753. let final_balance: u64 = wallet.total_balance().await.unwrap().into();
  754. let total_spent = initial_amount - final_balance;
  755. let total_fees = total_spent - melt_amount;
  756. tracing::info!(
  757. "Balance: initial={}, final={}, total_spent={}, melt_amount={}, total_fees={}",
  758. initial_amount,
  759. final_balance,
  760. total_spent,
  761. melt_amount,
  762. total_fees
  763. );
  764. // Calculate input fees (swap + melt)
  765. let input_fees = total_fees - ln_fee_paid;
  766. tracing::info!(
  767. "Fee breakdown: total_fees={}, ln_fee={}, input_fees (swap+melt)={}",
  768. total_fees,
  769. ln_fee_paid,
  770. input_fees
  771. );
  772. // Verify input fees are reasonable
  773. // With swap-before-melt optimization, we use fewer proofs for the melt
  774. // Melt uses ~8 proofs for optimal split of 1028, so input_fee ~= 8
  775. // Swap (if any) also has fees, but the optimization minimizes total fees
  776. assert!(
  777. input_fees > 0,
  778. "Should have some input fees with fee-enabled keyset"
  779. );
  780. assert!(
  781. input_fees <= 20,
  782. "Input fees {} should be reasonable (not too high)",
  783. input_fees
  784. );
  785. // Verify we have change remaining
  786. assert!(final_balance > 0, "Should have change remaining after melt");
  787. tracing::info!(
  788. "Test passed: spent {} sats, fees {} (ln={}, input={}), remaining {}",
  789. total_spent,
  790. total_fees,
  791. ln_fee_paid,
  792. input_fees,
  793. final_balance
  794. );
  795. }
  796. /// Tests the "exact match" early return path in melt_with_metadata.
  797. /// When proofs already exactly match inputs_needed_amount, no swap is required.
  798. ///
  799. /// This tests Step 1 of the two-step selection:
  800. /// - Select proofs for inputs_needed_amount
  801. /// - If exact match, use proofs directly without swap
  802. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  803. async fn test_melt_exact_match_no_swap() {
  804. setup_tracing();
  805. let mint = create_and_start_test_mint()
  806. .await
  807. .expect("Failed to create test mint");
  808. let wallet = create_test_wallet_for_mint(mint.clone())
  809. .await
  810. .expect("Failed to create test wallet");
  811. // Use keyset WITHOUT fees to make exact match easier
  812. // (default keyset has no fees)
  813. // Fund with exactly inputs_needed_amount to trigger the exact match path
  814. // For a 1000 sat melt, fee_reserve = max(1, 1000 * 2%) = 20 sats
  815. // inputs_needed = 1000 + 20 = 1020 sats
  816. let initial_amount = 1020u64;
  817. fund_wallet(wallet.clone(), initial_amount, None)
  818. .await
  819. .expect("Failed to fund wallet");
  820. let initial_balance: u64 = wallet.total_balance().await.unwrap().into();
  821. assert_eq!(initial_balance, initial_amount);
  822. let proofs_before = wallet.get_unspent_proofs().await.unwrap();
  823. tracing::info!(
  824. "Proofs before melt: {:?}",
  825. proofs_before
  826. .iter()
  827. .map(|p| u64::from(p.amount))
  828. .collect::<Vec<_>>()
  829. );
  830. // Create melt quote for 1000 sats
  831. // fee_reserve = max(1, 1000 * 2%) = 20 sats
  832. // inputs_needed = 1000 + 20 = 1020 sats = our exact balance
  833. let invoice = create_fake_invoice(1_000_000, "".to_string());
  834. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  835. let quote_amount: u64 = melt_quote.amount.into();
  836. let fee_reserve: u64 = melt_quote.fee_reserve.into();
  837. let inputs_needed = quote_amount + fee_reserve;
  838. tracing::info!(
  839. "Melt quote: amount={}, fee_reserve={}, inputs_needed={}",
  840. quote_amount,
  841. fee_reserve,
  842. inputs_needed
  843. );
  844. // Perform melt
  845. let melted = wallet.melt(&melt_quote.id).await.unwrap();
  846. let melt_amount: u64 = melted.amount.into();
  847. let ln_fee_paid: u64 = melted.fee_paid.into();
  848. tracing::info!(
  849. "Melt completed: amount={}, ln_fee_paid={}",
  850. melt_amount,
  851. ln_fee_paid
  852. );
  853. assert_eq!(melt_amount, quote_amount, "Melt amount should match quote");
  854. // Get final balance
  855. let final_balance: u64 = wallet.total_balance().await.unwrap().into();
  856. let total_spent = initial_amount - final_balance;
  857. let total_fees = total_spent - melt_amount;
  858. tracing::info!(
  859. "Balance: initial={}, final={}, total_spent={}, total_fees={}",
  860. initial_amount,
  861. final_balance,
  862. total_spent,
  863. total_fees
  864. );
  865. // With no keyset fees and no swap needed, total fees should just be ln_fee
  866. // (no input fees since default keyset has 0 ppk)
  867. assert_eq!(
  868. total_fees, ln_fee_paid,
  869. "Total fees should equal LN fee (no swap or input fees with 0 ppk keyset)"
  870. );
  871. tracing::info!("Test passed: exact match path used, no swap needed");
  872. }
  873. /// Tests melt with small amounts where swap margin is too tight.
  874. /// When fees are high relative to the melt amount, the swap-before-melt
  875. /// optimization may not have enough margin to cover both input and output fees.
  876. /// In this case, the wallet should fall back to using proofs directly.
  877. ///
  878. /// Scenario:
  879. /// - Fund with 8 sats
  880. /// - Melt 5 sats (with 2% fee_reserve = 1 sat min, so inputs_needed = 6)
  881. /// - With 1 sat per proof fee, the swap margin becomes too tight
  882. /// - Should still succeed by falling back to direct melt
  883. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  884. async fn test_melt_small_amount_tight_margin() {
  885. setup_tracing();
  886. let mint = create_and_start_test_mint()
  887. .await
  888. .expect("Failed to create test mint");
  889. let wallet = create_test_wallet_for_mint(mint.clone())
  890. .await
  891. .expect("Failed to create test wallet");
  892. // Rotate to keyset with 1000 ppk = 1 sat per proof fee
  893. mint.rotate_keyset(
  894. CurrencyUnit::Sat,
  895. cdk_integration_tests::standard_keyset_amounts(32),
  896. 1000,
  897. )
  898. .await
  899. .expect("Failed to rotate keyset");
  900. tokio::time::sleep(std::time::Duration::from_millis(100)).await;
  901. // Fund with enough to cover melt + fees, but amounts that will trigger swap
  902. // 32 sats gives us enough margin even with 1 sat/proof fees
  903. let initial_amount = 32;
  904. fund_wallet(wallet.clone(), initial_amount, None)
  905. .await
  906. .expect("Failed to fund wallet");
  907. let initial_balance: u64 = wallet.total_balance().await.unwrap().into();
  908. assert_eq!(initial_balance, initial_amount);
  909. let proofs = wallet.get_unspent_proofs().await.unwrap();
  910. tracing::info!(
  911. "Proofs after funding: {:?}",
  912. proofs
  913. .iter()
  914. .map(|p| u64::from(p.amount))
  915. .collect::<Vec<_>>()
  916. );
  917. // Create melt quote for 5 sats
  918. // fee_reserve = max(1, 5 * 2%) = 1 sat
  919. // inputs_needed = 5 + 1 = 6 sats
  920. let invoice = create_fake_invoice(5_000, "".to_string()); // 5 sats in msats
  921. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  922. let quote_amount: u64 = melt_quote.amount.into();
  923. let fee_reserve: u64 = melt_quote.fee_reserve.into();
  924. tracing::info!(
  925. "Melt quote: amount={}, fee_reserve={}, inputs_needed={}",
  926. quote_amount,
  927. fee_reserve,
  928. quote_amount + fee_reserve
  929. );
  930. // This should succeed even with tight margins
  931. let melted = wallet
  932. .melt(&melt_quote.id)
  933. .await
  934. .expect("Melt should succeed even with tight swap margin");
  935. let melt_amount: u64 = melted.amount.into();
  936. assert_eq!(melt_amount, quote_amount, "Melt amount should match quote");
  937. let final_balance: u64 = wallet.total_balance().await.unwrap().into();
  938. tracing::info!(
  939. "Melt completed: amount={}, fee_paid={}, final_balance={}",
  940. melted.amount,
  941. melted.fee_paid,
  942. final_balance
  943. );
  944. // Verify balance decreased appropriately
  945. assert!(
  946. final_balance < initial_balance,
  947. "Balance should decrease after melt"
  948. );
  949. }
  950. /// Tests melt where swap proofs barely cover swap_amount + input_fee.
  951. ///
  952. /// This is a regression test for a bug where the swap-before-melt was called
  953. /// with include_fees=true, causing it to try to add output fees on top of
  954. /// swap_amount + input_fee. When proofs_to_swap had just barely enough value,
  955. /// this caused InsufficientFunds error.
  956. ///
  957. /// Scenario (from the bug):
  958. /// - Balance: proofs like [4, 2, 1, 1] = 8 sats
  959. /// - Melt: 5 sats + 1 fee_reserve = 6 inputs_needed
  960. /// - target_fee = 1 (for optimal output split)
  961. /// - inputs_total_needed = 7
  962. /// - proofs_to_send = [4, 2] = 6, proofs_to_swap = [1, 1] = 2
  963. /// - swap_amount = 1 sat (7 - 6)
  964. /// - swap input_fee = 1 sat (2 proofs)
  965. /// - Before fix: include_fees=true tried to add output fee, causing failure
  966. /// - After fix: include_fees=false, swap succeeds
  967. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  968. async fn test_melt_swap_tight_margin_regression() {
  969. setup_tracing();
  970. let mint = create_and_start_test_mint()
  971. .await
  972. .expect("Failed to create test mint");
  973. let wallet = create_test_wallet_for_mint(mint.clone())
  974. .await
  975. .expect("Failed to create test wallet");
  976. // Rotate to keyset with 250 ppk = 0.25 sat per proof fee (same as original bug scenario)
  977. // This means 4 proofs = 1 sat fee
  978. mint.rotate_keyset(
  979. CurrencyUnit::Sat,
  980. cdk_integration_tests::standard_keyset_amounts(32),
  981. 250,
  982. )
  983. .await
  984. .expect("Failed to rotate keyset");
  985. tokio::time::sleep(std::time::Duration::from_millis(100)).await;
  986. // Fund with 100 sats using default split to get optimal denominations
  987. // This should give us proofs like [64, 32, 4] or similar power-of-2 split
  988. let initial_amount = 100;
  989. fund_wallet(wallet.clone(), initial_amount, None)
  990. .await
  991. .expect("Failed to fund wallet");
  992. let initial_balance: u64 = wallet.total_balance().await.unwrap().into();
  993. assert_eq!(initial_balance, initial_amount);
  994. let proofs = wallet.get_unspent_proofs().await.unwrap();
  995. let proof_amounts: Vec<u64> = proofs.iter().map(|p| u64::from(p.amount)).collect();
  996. tracing::info!("Proofs after funding: {:?}", proof_amounts);
  997. // Create melt quote for 5 sats (5000 msats)
  998. // fee_reserve = max(1, 5 * 2%) = 1 sat
  999. // inputs_needed = 5 + 1 = 6 sats
  1000. // The optimal split for 6 sats is [4, 2] (2 proofs)
  1001. // target_fee = 1 sat (2 proofs * 0.25, rounded up)
  1002. // inputs_total_needed = 7 sats
  1003. //
  1004. // If we don't have exact [4, 2] proofs, we'll need to swap.
  1005. // The swap path is what triggered the original bug when proofs_to_swap
  1006. // had tight margins and include_fees=true was incorrectly used.
  1007. let invoice = create_fake_invoice(5_000, "".to_string());
  1008. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  1009. let quote_amount: u64 = melt_quote.amount.into();
  1010. let fee_reserve: u64 = melt_quote.fee_reserve.into();
  1011. tracing::info!(
  1012. "Melt quote: amount={}, fee_reserve={}, inputs_needed={}",
  1013. quote_amount,
  1014. fee_reserve,
  1015. quote_amount + fee_reserve
  1016. );
  1017. // This is the key test: melt should succeed even when swap is needed
  1018. // Before the fix, include_fees=true in swap caused InsufficientFunds
  1019. // After the fix, include_fees=false allows the swap to succeed
  1020. let melted = wallet
  1021. .melt(&melt_quote.id)
  1022. .await
  1023. .expect("Melt should succeed with swap-before-melt (regression test)");
  1024. let melt_amount: u64 = melted.amount.into();
  1025. assert_eq!(melt_amount, quote_amount, "Melt amount should match quote");
  1026. let final_balance: u64 = wallet.total_balance().await.unwrap().into();
  1027. tracing::info!(
  1028. "Melt completed: amount={}, fee_paid={}, final_balance={}",
  1029. melted.amount,
  1030. melted.fee_paid,
  1031. final_balance
  1032. );
  1033. // Should have change remaining
  1034. assert!(
  1035. final_balance < initial_balance,
  1036. "Balance should decrease after melt"
  1037. );
  1038. assert!(final_balance > 0, "Should have change remaining");
  1039. }
  1040. /// Tests that swap correctly handles amount overflow:
  1041. /// Attempts to create outputs that would overflow u64 when summed.
  1042. /// This should be rejected before any database operations occur.
  1043. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1044. async fn test_swap_amount_overflow_protection() {
  1045. setup_tracing();
  1046. let mint = create_and_start_test_mint()
  1047. .await
  1048. .expect("Failed to create test mint");
  1049. let wallet = create_test_wallet_for_mint(mint.clone())
  1050. .await
  1051. .expect("Failed to create test wallet");
  1052. // Fund wallet
  1053. fund_wallet(wallet.clone(), 100, None)
  1054. .await
  1055. .expect("Failed to fund wallet");
  1056. let proofs = wallet
  1057. .get_unspent_proofs()
  1058. .await
  1059. .expect("Could not get proofs");
  1060. let keyset_id = get_keyset_id(&mint).await;
  1061. // Try to create outputs that would overflow
  1062. // 2^63 + 2^63 + small amount would overflow u64
  1063. let large_amount = 2_u64.pow(63);
  1064. let pre_mint1 = PreMintSecrets::from_secrets(
  1065. keyset_id,
  1066. vec![large_amount.into()],
  1067. vec![cashu::secret::Secret::generate()],
  1068. )
  1069. .expect("Failed to create pre_mint1");
  1070. let pre_mint2 = PreMintSecrets::from_secrets(
  1071. keyset_id,
  1072. vec![large_amount.into()],
  1073. vec![cashu::secret::Secret::generate()],
  1074. )
  1075. .expect("Failed to create pre_mint2");
  1076. let mut combined_pre_mint = PreMintSecrets::from_secrets(
  1077. keyset_id,
  1078. vec![1.into()],
  1079. vec![cashu::secret::Secret::generate()],
  1080. )
  1081. .expect("Failed to create combined_pre_mint");
  1082. combined_pre_mint.combine(pre_mint1);
  1083. combined_pre_mint.combine(pre_mint2);
  1084. let swap_request = SwapRequest::new(proofs, combined_pre_mint.blinded_messages());
  1085. // Should fail with overflow/amount error
  1086. match mint.process_swap_request(swap_request).await {
  1087. Err(cdk::Error::NUT03(cdk::nuts::nut03::Error::Amount(_)))
  1088. | Err(cdk::Error::AmountOverflow)
  1089. | Err(cdk::Error::AmountError(_))
  1090. | Err(cdk::Error::TransactionUnbalanced(_, _, _)) => {
  1091. // Any of these errors are acceptable for overflow
  1092. }
  1093. Err(err) => panic!("Unexpected error type: {:?}", err),
  1094. Ok(_) => panic!("Overflow swap should not succeed"),
  1095. }
  1096. }
  1097. /// Tests swap state transitions through pubsub notifications:
  1098. /// 1. Subscribe to proof state changes
  1099. /// 2. Execute swap
  1100. /// 3. Verify Pending then Spent state transitions are received
  1101. /// Validates NUT-17 notification behavior.
  1102. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1103. async fn test_swap_state_transition_notifications() {
  1104. setup_tracing();
  1105. let mint = create_and_start_test_mint()
  1106. .await
  1107. .expect("Failed to create test mint");
  1108. let wallet = create_test_wallet_for_mint(mint.clone())
  1109. .await
  1110. .expect("Failed to create test wallet");
  1111. // Fund wallet
  1112. fund_wallet(wallet.clone(), 100, None)
  1113. .await
  1114. .expect("Failed to fund wallet");
  1115. let proofs = wallet
  1116. .get_unspent_proofs()
  1117. .await
  1118. .expect("Could not get proofs");
  1119. let keyset_id = get_keyset_id(&mint).await;
  1120. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  1121. let preswap = PreMintSecrets::random(
  1122. keyset_id,
  1123. 100.into(),
  1124. &SplitTarget::default(),
  1125. &fee_and_amounts,
  1126. )
  1127. .expect("Failed to create preswap");
  1128. let swap_request = SwapRequest::new(proofs.clone(), preswap.blinded_messages());
  1129. // Subscribe to proof state changes
  1130. let proof_ys: Vec<String> = proofs.iter().map(|p| p.y().unwrap().to_string()).collect();
  1131. let mut listener = mint
  1132. .pubsub_manager()
  1133. .subscribe(cdk::subscription::Params {
  1134. kind: cdk::nuts::nut17::Kind::ProofState,
  1135. filters: proof_ys.clone(),
  1136. id: Arc::new("test_swap_notifications".into()),
  1137. })
  1138. .expect("Should subscribe successfully");
  1139. // Execute swap
  1140. mint.process_swap_request(swap_request)
  1141. .await
  1142. .expect("Swap should succeed");
  1143. // Give pubsub time to deliver messages
  1144. tokio::time::sleep(std::time::Duration::from_millis(100)).await;
  1145. // Collect all state transition notifications
  1146. let mut state_transitions: HashMap<String, Vec<State>> = HashMap::new();
  1147. while let Some(msg) = listener.try_recv() {
  1148. match msg.into_inner() {
  1149. cashu::NotificationPayload::ProofState(cashu::ProofState { y, state, .. }) => {
  1150. state_transitions
  1151. .entry(y.to_string())
  1152. .or_default()
  1153. .push(state);
  1154. }
  1155. _ => panic!("Unexpected notification type"),
  1156. }
  1157. }
  1158. // Verify each proof went through Pending -> Spent transition
  1159. for y in proof_ys {
  1160. let transitions = state_transitions
  1161. .get(&y)
  1162. .expect("Should have transitions for proof");
  1163. assert_eq!(
  1164. transitions,
  1165. &vec![State::Pending, State::Spent],
  1166. "Proof should transition from Pending to Spent"
  1167. );
  1168. }
  1169. }
  1170. /// Tests that swap fails gracefully when proof states cannot be updated:
  1171. /// This would test the rollback path where proofs are added but state update fails.
  1172. /// In the current implementation, this should trigger rollback of both proofs and blinded messages.
  1173. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1174. async fn test_swap_proof_state_consistency() {
  1175. setup_tracing();
  1176. let mint = create_and_start_test_mint()
  1177. .await
  1178. .expect("Failed to create test mint");
  1179. let wallet = create_test_wallet_for_mint(mint.clone())
  1180. .await
  1181. .expect("Failed to create test wallet");
  1182. // Fund wallet
  1183. fund_wallet(wallet.clone(), 100, None)
  1184. .await
  1185. .expect("Failed to fund wallet");
  1186. let proofs = wallet
  1187. .get_unspent_proofs()
  1188. .await
  1189. .expect("Could not get proofs");
  1190. let keyset_id = get_keyset_id(&mint).await;
  1191. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  1192. // Execute successful swap
  1193. let preswap = PreMintSecrets::random(
  1194. keyset_id,
  1195. 100.into(),
  1196. &SplitTarget::default(),
  1197. &fee_and_amounts,
  1198. )
  1199. .expect("Failed to create preswap");
  1200. let swap_request = SwapRequest::new(proofs.clone(), preswap.blinded_messages());
  1201. mint.process_swap_request(swap_request)
  1202. .await
  1203. .expect("Swap should succeed");
  1204. // Verify all proofs have consistent state (Spent)
  1205. let proof_ys: Vec<_> = proofs.iter().map(|p| p.y().unwrap()).collect();
  1206. let states = mint
  1207. .localstore()
  1208. .get_proofs_states(&proof_ys)
  1209. .await
  1210. .expect("Failed to get proof states");
  1211. // All states should be Some(Spent) - none should be None or Pending
  1212. for (i, state) in states.iter().enumerate() {
  1213. match state {
  1214. Some(State::Spent) => {
  1215. // Expected state
  1216. }
  1217. Some(other_state) => {
  1218. panic!("Proof {} in unexpected state: {:?}", i, other_state)
  1219. }
  1220. None => {
  1221. panic!("Proof {} has no state (should be Spent)", i)
  1222. }
  1223. }
  1224. }
  1225. }
  1226. /// Tests that wallet correctly increments keyset counters when receiving proofs
  1227. /// from multiple keysets and then performing operations with them.
  1228. ///
  1229. /// This test validates:
  1230. /// 1. Wallet can receive proofs from multiple different keysets
  1231. /// 2. Counter is correctly incremented for the target keyset during swap
  1232. /// 3. Database maintains separate counters for each keyset
  1233. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1234. async fn test_wallet_multi_keyset_counter_updates() {
  1235. setup_tracing();
  1236. let mint = create_and_start_test_mint()
  1237. .await
  1238. .expect("Failed to create test mint");
  1239. let wallet = create_test_wallet_for_mint(mint.clone())
  1240. .await
  1241. .expect("Failed to create test wallet");
  1242. // Fund wallet with initial 100 sats using first keyset
  1243. fund_wallet(wallet.clone(), 100, None)
  1244. .await
  1245. .expect("Failed to fund wallet");
  1246. let first_keyset_id = get_keyset_id(&mint).await;
  1247. // Rotate to a second keyset
  1248. mint.rotate_keyset(
  1249. CurrencyUnit::Sat,
  1250. cdk_integration_tests::standard_keyset_amounts(32),
  1251. 0,
  1252. )
  1253. .await
  1254. .expect("Failed to rotate keyset");
  1255. // Wait for keyset rotation to propagate
  1256. tokio::time::sleep(std::time::Duration::from_millis(100)).await;
  1257. // Refresh wallet keysets to know about the new keyset
  1258. wallet
  1259. .refresh_keysets()
  1260. .await
  1261. .expect("Failed to refresh wallet keysets");
  1262. // Fund wallet again with 100 sats using second keyset
  1263. fund_wallet(wallet.clone(), 100, None)
  1264. .await
  1265. .expect("Failed to fund wallet with second keyset");
  1266. let second_keyset_id = mint
  1267. .pubkeys()
  1268. .keysets
  1269. .iter()
  1270. .find(|k| k.id != first_keyset_id)
  1271. .expect("Should have second keyset")
  1272. .id;
  1273. // Verify we now have proofs from two different keysets
  1274. let all_proofs = wallet
  1275. .get_unspent_proofs()
  1276. .await
  1277. .expect("Could not get proofs");
  1278. let keysets_in_use: std::collections::HashSet<_> =
  1279. all_proofs.iter().map(|p| p.keyset_id).collect();
  1280. assert_eq!(
  1281. keysets_in_use.len(),
  1282. 2,
  1283. "Should have proofs from 2 different keysets"
  1284. );
  1285. assert!(
  1286. keysets_in_use.contains(&first_keyset_id),
  1287. "Should have proofs from first keyset"
  1288. );
  1289. assert!(
  1290. keysets_in_use.contains(&second_keyset_id),
  1291. "Should have proofs from second keyset"
  1292. );
  1293. // Get initial total issued and redeemed for both keysets before swap
  1294. let total_issued_before = mint.total_issued().await.unwrap();
  1295. let total_redeemed_before = mint.total_redeemed().await.unwrap();
  1296. let first_keyset_issued_before = total_issued_before
  1297. .get(&first_keyset_id)
  1298. .copied()
  1299. .unwrap_or(Amount::ZERO);
  1300. let first_keyset_redeemed_before = total_redeemed_before
  1301. .get(&first_keyset_id)
  1302. .copied()
  1303. .unwrap_or(Amount::ZERO);
  1304. let second_keyset_issued_before = total_issued_before
  1305. .get(&second_keyset_id)
  1306. .copied()
  1307. .unwrap_or(Amount::ZERO);
  1308. let second_keyset_redeemed_before = total_redeemed_before
  1309. .get(&second_keyset_id)
  1310. .copied()
  1311. .unwrap_or(Amount::ZERO);
  1312. tracing::info!(
  1313. "Before swap - First keyset: issued={}, redeemed={}",
  1314. first_keyset_issued_before,
  1315. first_keyset_redeemed_before
  1316. );
  1317. tracing::info!(
  1318. "Before swap - Second keyset: issued={}, redeemed={}",
  1319. second_keyset_issued_before,
  1320. second_keyset_redeemed_before
  1321. );
  1322. // Both keysets should have issued 100 sats
  1323. assert_eq!(
  1324. first_keyset_issued_before,
  1325. Amount::from(100),
  1326. "First keyset should have issued 100 sats"
  1327. );
  1328. assert_eq!(
  1329. second_keyset_issued_before,
  1330. Amount::from(100),
  1331. "Second keyset should have issued 100 sats"
  1332. );
  1333. // Neither should have redeemed anything yet
  1334. assert_eq!(
  1335. first_keyset_redeemed_before,
  1336. Amount::ZERO,
  1337. "First keyset should have redeemed 0 sats before swap"
  1338. );
  1339. assert_eq!(
  1340. second_keyset_redeemed_before,
  1341. Amount::ZERO,
  1342. "Second keyset should have redeemed 0 sats before swap"
  1343. );
  1344. // Now perform a swap with all proofs - this should only increment the counter
  1345. // for the active (second) keyset, not for the first keyset
  1346. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  1347. let total_amount = all_proofs.total_amount().expect("Should get total amount");
  1348. // Create swap using the active (second) keyset
  1349. let preswap = PreMintSecrets::random(
  1350. second_keyset_id,
  1351. total_amount,
  1352. &SplitTarget::default(),
  1353. &fee_and_amounts,
  1354. )
  1355. .expect("Failed to create preswap");
  1356. let swap_request = SwapRequest::new(all_proofs.clone(), preswap.blinded_messages());
  1357. // Execute the swap
  1358. let swap_response = mint
  1359. .process_swap_request(swap_request)
  1360. .await
  1361. .expect("Swap should succeed");
  1362. // Verify response
  1363. assert_eq!(
  1364. swap_response.signatures.len(),
  1365. preswap.blinded_messages().len(),
  1366. "Should receive signature for each blinded message"
  1367. );
  1368. // All the new proofs should be from the second (active) keyset
  1369. let keys = mint
  1370. .pubkeys()
  1371. .keysets
  1372. .iter()
  1373. .find(|k| k.id == second_keyset_id)
  1374. .expect("Should find second keyset")
  1375. .keys
  1376. .clone();
  1377. let new_proofs = construct_proofs(
  1378. swap_response.signatures,
  1379. preswap.rs(),
  1380. preswap.secrets(),
  1381. &keys,
  1382. )
  1383. .expect("Failed to construct proofs");
  1384. // Verify all new proofs use the second keyset
  1385. for proof in &new_proofs {
  1386. assert_eq!(
  1387. proof.keyset_id, second_keyset_id,
  1388. "All new proofs should use the active (second) keyset"
  1389. );
  1390. }
  1391. // Verify total issued and redeemed after swap
  1392. let total_issued_after = mint.total_issued().await.unwrap();
  1393. let total_redeemed_after = mint.total_redeemed().await.unwrap();
  1394. let first_keyset_issued_after = total_issued_after
  1395. .get(&first_keyset_id)
  1396. .copied()
  1397. .unwrap_or(Amount::ZERO);
  1398. let first_keyset_redeemed_after = total_redeemed_after
  1399. .get(&first_keyset_id)
  1400. .copied()
  1401. .unwrap_or(Amount::ZERO);
  1402. let second_keyset_issued_after = total_issued_after
  1403. .get(&second_keyset_id)
  1404. .copied()
  1405. .unwrap_or(Amount::ZERO);
  1406. let second_keyset_redeemed_after = total_redeemed_after
  1407. .get(&second_keyset_id)
  1408. .copied()
  1409. .unwrap_or(Amount::ZERO);
  1410. tracing::info!(
  1411. "After swap - First keyset: issued={}, redeemed={}",
  1412. first_keyset_issued_after,
  1413. first_keyset_redeemed_after
  1414. );
  1415. tracing::info!(
  1416. "After swap - Second keyset: issued={}, redeemed={}",
  1417. second_keyset_issued_after,
  1418. second_keyset_redeemed_after
  1419. );
  1420. // After swap:
  1421. // - First keyset: issued stays 100, redeemed increases by 100 (all its proofs were spent in swap)
  1422. // - Second keyset: issued increases by 200 (original 100 + new 100 from swap output),
  1423. // redeemed increases by 100 (its proofs from first funding were spent)
  1424. assert_eq!(
  1425. first_keyset_issued_after,
  1426. Amount::from(100),
  1427. "First keyset issued should stay 100 sats (no new issuance)"
  1428. );
  1429. assert_eq!(
  1430. first_keyset_redeemed_after,
  1431. Amount::from(100),
  1432. "First keyset should have redeemed 100 sats (all its proofs spent in swap)"
  1433. );
  1434. assert_eq!(
  1435. second_keyset_issued_after,
  1436. Amount::from(300),
  1437. "Second keyset should have issued 300 sats total (100 initial + 100 the second funding + 100 from swap output from the old keyset)"
  1438. );
  1439. assert_eq!(
  1440. second_keyset_redeemed_after,
  1441. Amount::from(100),
  1442. "Second keyset should have redeemed 100 sats (its proofs from initial funding spent in swap)"
  1443. );
  1444. // The test verifies that:
  1445. // 1. We can have proofs from multiple keysets in a wallet
  1446. // 2. Swap operation processes inputs from any keyset but creates outputs using active keyset
  1447. // 3. The keyset_counter table correctly handles counters for different keysets independently
  1448. // 4. The database upsert logic in increment_keyset_counter works for multiple keysets
  1449. // 5. Total issued and redeemed are tracked correctly per keyset during multi-keyset swaps
  1450. }