integration_tests_pure.rs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890
  1. //! This file contains integration tests for the Cashu Development Kit (CDK)
  2. //!
  3. //! These tests verify the interaction between mint and wallet components, simulating real-world usage scenarios.
  4. //! They test the complete flow of operations including wallet funding, token swapping, sending tokens between wallets,
  5. //! and other operations that require client-mint interaction.
  6. use std::assert_eq;
  7. use std::collections::{HashMap, HashSet};
  8. use std::hash::RandomState;
  9. use std::str::FromStr;
  10. use std::time::Duration;
  11. use cashu::amount::SplitTarget;
  12. use cashu::dhke::construct_proofs;
  13. use cashu::mint_url::MintUrl;
  14. use cashu::{
  15. CurrencyUnit, Id, MeltRequest, NotificationPayload, PreMintSecrets, ProofState, SecretKey,
  16. SpendingConditions, State, SwapRequest,
  17. };
  18. use cdk::mint::Mint;
  19. use cdk::nuts::nut00::ProofsMethods;
  20. use cdk::subscription::{IndexableParams, Params};
  21. use cdk::wallet::types::{TransactionDirection, TransactionId};
  22. use cdk::wallet::{ReceiveOptions, SendMemo, SendOptions};
  23. use cdk::Amount;
  24. use cdk_fake_wallet::create_fake_invoice;
  25. use cdk_integration_tests::init_pure_tests::*;
  26. use tokio::time::sleep;
  27. /// Tests the token swap and send functionality:
  28. /// 1. Alice gets funded with 64 sats
  29. /// 2. Alice prepares to send 40 sats (which requires internal swapping)
  30. /// 3. Alice sends the token
  31. /// 4. Carol receives the token and has the correct balance
  32. #[tokio::test]
  33. async fn test_swap_to_send() {
  34. setup_tracing();
  35. let mint_bob = create_and_start_test_mint()
  36. .await
  37. .expect("Failed to create test mint");
  38. let wallet_alice = create_test_wallet_for_mint(mint_bob.clone())
  39. .await
  40. .expect("Failed to create test wallet");
  41. // Alice gets 64 sats
  42. fund_wallet(wallet_alice.clone(), 64, None)
  43. .await
  44. .expect("Failed to fund wallet");
  45. let balance_alice = wallet_alice
  46. .total_balance()
  47. .await
  48. .expect("Failed to get balance");
  49. assert_eq!(Amount::from(64), balance_alice);
  50. // Alice wants to send 40 sats, which internally swaps
  51. let prepared_send = wallet_alice
  52. .prepare_send(Amount::from(40), SendOptions::default())
  53. .await
  54. .expect("Failed to prepare send");
  55. assert_eq!(
  56. HashSet::<_, RandomState>::from_iter(
  57. prepared_send.proofs().ys().expect("Failed to get ys")
  58. ),
  59. HashSet::from_iter(
  60. wallet_alice
  61. .get_reserved_proofs()
  62. .await
  63. .expect("Failed to get reserved proofs")
  64. .ys()
  65. .expect("Failed to get ys")
  66. )
  67. );
  68. let token = prepared_send
  69. .confirm(Some(SendMemo::for_token("test_swapt_to_send")))
  70. .await
  71. .expect("Failed to send token");
  72. let keysets_info = wallet_alice.get_mint_keysets().await.unwrap();
  73. let token_proofs = token.proofs(&keysets_info).unwrap();
  74. assert_eq!(
  75. Amount::from(40),
  76. token_proofs
  77. .total_amount()
  78. .expect("Failed to get total amount")
  79. );
  80. assert_eq!(
  81. Amount::from(24),
  82. wallet_alice
  83. .total_balance()
  84. .await
  85. .expect("Failed to get balance")
  86. );
  87. assert_eq!(
  88. HashSet::<_, RandomState>::from_iter(token_proofs.ys().expect("Failed to get ys")),
  89. HashSet::from_iter(
  90. wallet_alice
  91. .get_pending_spent_proofs()
  92. .await
  93. .expect("Failed to get pending spent proofs")
  94. .ys()
  95. .expect("Failed to get ys")
  96. )
  97. );
  98. let transaction_id =
  99. TransactionId::from_proofs(token_proofs.clone()).expect("Failed to get tx id");
  100. let transaction = wallet_alice
  101. .get_transaction(transaction_id)
  102. .await
  103. .expect("Failed to get transaction")
  104. .expect("Transaction not found");
  105. assert_eq!(wallet_alice.mint_url, transaction.mint_url);
  106. assert_eq!(TransactionDirection::Outgoing, transaction.direction);
  107. assert_eq!(Amount::from(40), transaction.amount);
  108. assert_eq!(Amount::from(0), transaction.fee);
  109. assert_eq!(CurrencyUnit::Sat, transaction.unit);
  110. assert_eq!(token_proofs.ys().unwrap(), transaction.ys);
  111. // Alice sends cashu, Carol receives
  112. let wallet_carol = create_test_wallet_for_mint(mint_bob.clone())
  113. .await
  114. .expect("Failed to create Carol's wallet");
  115. let received_amount = wallet_carol
  116. .receive_proofs(
  117. token_proofs.clone(),
  118. ReceiveOptions::default(),
  119. token.memo().clone(),
  120. )
  121. .await
  122. .expect("Failed to receive proofs");
  123. assert_eq!(Amount::from(40), received_amount);
  124. assert_eq!(
  125. Amount::from(40),
  126. wallet_carol
  127. .total_balance()
  128. .await
  129. .expect("Failed to get Carol's balance")
  130. );
  131. let transaction = wallet_carol
  132. .get_transaction(transaction_id)
  133. .await
  134. .expect("Failed to get transaction")
  135. .expect("Transaction not found");
  136. assert_eq!(wallet_carol.mint_url, transaction.mint_url);
  137. assert_eq!(TransactionDirection::Incoming, transaction.direction);
  138. assert_eq!(Amount::from(40), transaction.amount);
  139. assert_eq!(Amount::from(0), transaction.fee);
  140. assert_eq!(CurrencyUnit::Sat, transaction.unit);
  141. assert_eq!(token_proofs.ys().unwrap(), transaction.ys);
  142. assert_eq!(token.memo().clone(), transaction.memo);
  143. }
  144. /// Tests the NUT-06 functionality (mint discovery):
  145. /// 1. Alice gets funded with 64 sats
  146. /// 2. Verifies the initial mint URL is in the mint info
  147. /// 3. Updates the mint URL to a new value
  148. /// 4. Verifies the wallet balance is maintained after changing the mint URL
  149. #[tokio::test]
  150. async fn test_mint_nut06() {
  151. setup_tracing();
  152. let mint_bob = create_and_start_test_mint()
  153. .await
  154. .expect("Failed to create test mint");
  155. let mut wallet_alice = create_test_wallet_for_mint(mint_bob.clone())
  156. .await
  157. .expect("Failed to create test wallet");
  158. // Alice gets 64 sats
  159. fund_wallet(wallet_alice.clone(), 64, None)
  160. .await
  161. .expect("Failed to fund wallet");
  162. let balance_alice = wallet_alice
  163. .total_balance()
  164. .await
  165. .expect("Failed to get balance");
  166. assert_eq!(Amount::from(64), balance_alice);
  167. let transaction = wallet_alice
  168. .list_transactions(None)
  169. .await
  170. .expect("Failed to list transactions")
  171. .pop()
  172. .expect("No transactions found");
  173. assert_eq!(wallet_alice.mint_url, transaction.mint_url);
  174. assert_eq!(TransactionDirection::Incoming, transaction.direction);
  175. assert_eq!(Amount::from(64), transaction.amount);
  176. assert_eq!(Amount::from(0), transaction.fee);
  177. assert_eq!(CurrencyUnit::Sat, transaction.unit);
  178. let initial_mint_url = wallet_alice.mint_url.clone();
  179. let mint_info_before = wallet_alice
  180. .get_mint_info()
  181. .await
  182. .expect("Failed to get mint info")
  183. .unwrap();
  184. assert!(mint_info_before
  185. .urls
  186. .unwrap()
  187. .contains(&initial_mint_url.to_string()));
  188. // Wallet updates mint URL
  189. let new_mint_url = MintUrl::from_str("https://new-mint-url").expect("Failed to parse mint URL");
  190. wallet_alice
  191. .update_mint_url(new_mint_url.clone())
  192. .await
  193. .expect("Failed to update mint URL");
  194. // Check balance after mint URL was updated
  195. let balance_alice_after = wallet_alice
  196. .total_balance()
  197. .await
  198. .expect("Failed to get balance after URL update");
  199. assert_eq!(Amount::from(64), balance_alice_after);
  200. }
  201. /// Attempt to double spend proofs on swap
  202. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  203. async fn test_mint_double_spend() {
  204. setup_tracing();
  205. let mint_bob = create_and_start_test_mint()
  206. .await
  207. .expect("Failed to create test mint");
  208. let wallet_alice = create_test_wallet_for_mint(mint_bob.clone())
  209. .await
  210. .expect("Failed to create test wallet");
  211. // Alice gets 64 sats
  212. fund_wallet(wallet_alice.clone(), 64, None)
  213. .await
  214. .expect("Failed to fund wallet");
  215. let proofs = wallet_alice
  216. .get_unspent_proofs()
  217. .await
  218. .expect("Could not get proofs");
  219. let keys = mint_bob.pubkeys().keysets.first().unwrap().clone();
  220. let keyset_id = keys.id;
  221. let preswap = PreMintSecrets::random(
  222. keyset_id,
  223. proofs.total_amount().unwrap(),
  224. &SplitTarget::default(),
  225. )
  226. .unwrap();
  227. let swap_request = SwapRequest::new(proofs.clone(), preswap.blinded_messages());
  228. let swap = mint_bob.process_swap_request(swap_request).await;
  229. assert!(swap.is_ok());
  230. let preswap_two = PreMintSecrets::random(
  231. keyset_id,
  232. proofs.total_amount().unwrap(),
  233. &SplitTarget::default(),
  234. )
  235. .unwrap();
  236. let swap_two_request = SwapRequest::new(proofs, preswap_two.blinded_messages());
  237. match mint_bob.process_swap_request(swap_two_request).await {
  238. Ok(_) => panic!("Proofs double spent"),
  239. Err(err) => match err {
  240. cdk::Error::TokenAlreadySpent => (),
  241. _ => panic!("Wrong error returned"),
  242. },
  243. }
  244. }
  245. /// This attempts to swap for more outputs then inputs.
  246. /// This will work if the mint does not check for outputs amounts overflowing
  247. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  248. async fn test_attempt_to_swap_by_overflowing() {
  249. setup_tracing();
  250. let mint_bob = create_and_start_test_mint()
  251. .await
  252. .expect("Failed to create test mint");
  253. let wallet_alice = create_test_wallet_for_mint(mint_bob.clone())
  254. .await
  255. .expect("Failed to create test wallet");
  256. // Alice gets 64 sats
  257. fund_wallet(wallet_alice.clone(), 64, None)
  258. .await
  259. .expect("Failed to fund wallet");
  260. let proofs = wallet_alice
  261. .get_unspent_proofs()
  262. .await
  263. .expect("Could not get proofs");
  264. let amount = 2_u64.pow(63);
  265. let keys = mint_bob.pubkeys().keysets.first().unwrap().clone();
  266. let keyset_id = keys.id;
  267. let pre_mint_amount =
  268. PreMintSecrets::random(keyset_id, amount.into(), &SplitTarget::default()).unwrap();
  269. let pre_mint_amount_two =
  270. PreMintSecrets::random(keyset_id, amount.into(), &SplitTarget::default()).unwrap();
  271. let mut pre_mint =
  272. PreMintSecrets::random(keyset_id, 1.into(), &SplitTarget::default()).unwrap();
  273. pre_mint.combine(pre_mint_amount);
  274. pre_mint.combine(pre_mint_amount_two);
  275. let swap_request = SwapRequest::new(proofs.clone(), pre_mint.blinded_messages());
  276. match mint_bob.process_swap_request(swap_request).await {
  277. Ok(_) => panic!("Swap occurred with overflow"),
  278. Err(err) => match err {
  279. cdk::Error::NUT03(cdk::nuts::nut03::Error::Amount(_)) => (),
  280. cdk::Error::AmountOverflow => (),
  281. cdk::Error::AmountError(_) => (),
  282. _ => {
  283. println!("{:?}", err);
  284. panic!("Wrong error returned in swap overflow")
  285. }
  286. },
  287. }
  288. }
  289. /// Tests that the mint correctly rejects unbalanced swap requests:
  290. /// 1. Attempts to swap for less than the input amount (95 < 100)
  291. /// 2. Attempts to swap for more than the input amount (101 > 100)
  292. /// 3. Both should fail with TransactionUnbalanced error
  293. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  294. async fn test_swap_unbalanced() {
  295. setup_tracing();
  296. let mint_bob = create_and_start_test_mint()
  297. .await
  298. .expect("Failed to create test mint");
  299. let wallet_alice = create_test_wallet_for_mint(mint_bob.clone())
  300. .await
  301. .expect("Failed to create test wallet");
  302. // Alice gets 100 sats
  303. fund_wallet(wallet_alice.clone(), 100, None)
  304. .await
  305. .expect("Failed to fund wallet");
  306. let proofs = wallet_alice
  307. .get_unspent_proofs()
  308. .await
  309. .expect("Could not get proofs");
  310. let keyset_id = get_keyset_id(&mint_bob).await;
  311. // Try to swap for less than the input amount (95 < 100)
  312. let preswap = PreMintSecrets::random(keyset_id, 95.into(), &SplitTarget::default())
  313. .expect("Failed to create preswap");
  314. let swap_request = SwapRequest::new(proofs.clone(), preswap.blinded_messages());
  315. match mint_bob.process_swap_request(swap_request).await {
  316. Ok(_) => panic!("Swap was allowed unbalanced"),
  317. Err(err) => match err {
  318. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  319. _ => panic!("Wrong error returned"),
  320. },
  321. }
  322. // Try to swap for more than the input amount (101 > 100)
  323. let preswap = PreMintSecrets::random(keyset_id, 101.into(), &SplitTarget::default())
  324. .expect("Failed to create preswap");
  325. let swap_request = SwapRequest::new(proofs.clone(), preswap.blinded_messages());
  326. match mint_bob.process_swap_request(swap_request).await {
  327. Ok(_) => panic!("Swap was allowed unbalanced"),
  328. Err(err) => match err {
  329. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  330. _ => panic!("Wrong error returned"),
  331. },
  332. }
  333. }
  334. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  335. pub async fn test_p2pk_swap() {
  336. setup_tracing();
  337. let mint_bob = create_and_start_test_mint()
  338. .await
  339. .expect("Failed to create test mint");
  340. let wallet_alice = create_test_wallet_for_mint(mint_bob.clone())
  341. .await
  342. .expect("Failed to create test wallet");
  343. // Alice gets 100 sats
  344. fund_wallet(wallet_alice.clone(), 100, None)
  345. .await
  346. .expect("Failed to fund wallet");
  347. let proofs = wallet_alice
  348. .get_unspent_proofs()
  349. .await
  350. .expect("Could not get proofs");
  351. let keyset_id = get_keyset_id(&mint_bob).await;
  352. let secret = SecretKey::generate();
  353. let spending_conditions = SpendingConditions::new_p2pk(secret.public_key(), None);
  354. let pre_swap = PreMintSecrets::with_conditions(
  355. keyset_id,
  356. 100.into(),
  357. &SplitTarget::default(),
  358. &spending_conditions,
  359. )
  360. .unwrap();
  361. let swap_request = SwapRequest::new(proofs.clone(), pre_swap.blinded_messages());
  362. let keys = mint_bob.pubkeys().keysets.first().cloned().unwrap().keys;
  363. let post_swap = mint_bob.process_swap_request(swap_request).await.unwrap();
  364. let mut proofs = construct_proofs(
  365. post_swap.signatures,
  366. pre_swap.rs(),
  367. pre_swap.secrets(),
  368. &keys,
  369. )
  370. .unwrap();
  371. let pre_swap = PreMintSecrets::random(keyset_id, 100.into(), &SplitTarget::default()).unwrap();
  372. let swap_request = SwapRequest::new(proofs.clone(), pre_swap.blinded_messages());
  373. // Listen for status updates on all input proof pks
  374. let public_keys_to_listen: Vec<_> = swap_request
  375. .inputs()
  376. .ys()
  377. .unwrap()
  378. .iter()
  379. .map(|pk| pk.to_string())
  380. .collect();
  381. let mut listener = mint_bob
  382. .pubsub_manager()
  383. .try_subscribe::<IndexableParams>(
  384. Params {
  385. kind: cdk::nuts::nut17::Kind::ProofState,
  386. filters: public_keys_to_listen.clone(),
  387. id: "test".into(),
  388. }
  389. .into(),
  390. )
  391. .await
  392. .expect("valid subscription");
  393. match mint_bob.process_swap_request(swap_request).await {
  394. Ok(_) => panic!("Proofs spent without sig"),
  395. Err(err) => match err {
  396. cdk::Error::NUT11(cdk::nuts::nut11::Error::SignaturesNotProvided) => (),
  397. _ => {
  398. println!("{:?}", err);
  399. panic!("Wrong error returned")
  400. }
  401. },
  402. }
  403. for proof in &mut proofs {
  404. proof.sign_p2pk(secret.clone()).unwrap();
  405. }
  406. let swap_request = SwapRequest::new(proofs.clone(), pre_swap.blinded_messages());
  407. let attempt_swap = mint_bob.process_swap_request(swap_request).await;
  408. assert!(attempt_swap.is_ok());
  409. sleep(Duration::from_secs(1)).await;
  410. let mut msgs = HashMap::new();
  411. while let Ok((sub_id, msg)) = listener.try_recv() {
  412. assert_eq!(sub_id, "test".into());
  413. match msg {
  414. NotificationPayload::ProofState(ProofState { y, state, .. }) => {
  415. msgs.entry(y.to_string())
  416. .or_insert_with(Vec::new)
  417. .push(state);
  418. }
  419. _ => panic!("Wrong message received"),
  420. }
  421. }
  422. for (i, key) in public_keys_to_listen.into_iter().enumerate() {
  423. let statuses = msgs.remove(&key).expect("some events");
  424. // Every input pk receives two state updates, as there are only two state transitions
  425. assert_eq!(
  426. statuses,
  427. vec![State::Pending, State::Spent],
  428. "failed to test key {:?} (pos {})",
  429. key,
  430. i,
  431. );
  432. }
  433. assert!(listener.try_recv().is_err(), "no other event is happening");
  434. assert!(msgs.is_empty(), "Only expected key events are received");
  435. }
  436. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  437. async fn test_swap_overpay_underpay_fee() {
  438. setup_tracing();
  439. let mint_bob = create_and_start_test_mint()
  440. .await
  441. .expect("Failed to create test mint");
  442. mint_bob
  443. .rotate_keyset(CurrencyUnit::Sat, 32, 1)
  444. .await
  445. .unwrap();
  446. let wallet_alice = create_test_wallet_for_mint(mint_bob.clone())
  447. .await
  448. .expect("Failed to create test wallet");
  449. // Alice gets 100 sats
  450. fund_wallet(wallet_alice.clone(), 1000, None)
  451. .await
  452. .expect("Failed to fund wallet");
  453. let proofs = wallet_alice
  454. .get_unspent_proofs()
  455. .await
  456. .expect("Could not get proofs");
  457. let keys = mint_bob.pubkeys().keysets.first().unwrap().clone().keys;
  458. let keyset_id = Id::v1_from_keys(&keys);
  459. let preswap = PreMintSecrets::random(keyset_id, 9998.into(), &SplitTarget::default()).unwrap();
  460. let swap_request = SwapRequest::new(proofs.clone(), preswap.blinded_messages());
  461. // Attempt to swap overpaying fee
  462. match mint_bob.process_swap_request(swap_request).await {
  463. Ok(_) => panic!("Swap was allowed unbalanced"),
  464. Err(err) => match err {
  465. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  466. _ => {
  467. println!("{:?}", err);
  468. panic!("Wrong error returned")
  469. }
  470. },
  471. }
  472. let preswap = PreMintSecrets::random(keyset_id, 1000.into(), &SplitTarget::default()).unwrap();
  473. let swap_request = SwapRequest::new(proofs.clone(), preswap.blinded_messages());
  474. // Attempt to swap underpaying fee
  475. match mint_bob.process_swap_request(swap_request).await {
  476. Ok(_) => panic!("Swap was allowed unbalanced"),
  477. Err(err) => match err {
  478. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  479. _ => {
  480. println!("{:?}", err);
  481. panic!("Wrong error returned")
  482. }
  483. },
  484. }
  485. }
  486. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  487. async fn test_mint_enforce_fee() {
  488. setup_tracing();
  489. let mint_bob = create_and_start_test_mint()
  490. .await
  491. .expect("Failed to create test mint");
  492. mint_bob
  493. .rotate_keyset(CurrencyUnit::Sat, 32, 1)
  494. .await
  495. .unwrap();
  496. let wallet_alice = create_test_wallet_for_mint(mint_bob.clone())
  497. .await
  498. .expect("Failed to create test wallet");
  499. // Alice gets 100 sats
  500. fund_wallet(
  501. wallet_alice.clone(),
  502. 1010,
  503. Some(SplitTarget::Value(Amount::ONE)),
  504. )
  505. .await
  506. .expect("Failed to fund wallet");
  507. let mut proofs = wallet_alice
  508. .get_unspent_proofs()
  509. .await
  510. .expect("Could not get proofs");
  511. let keys = mint_bob.pubkeys().keysets.first().unwrap().clone();
  512. let keyset_id = keys.id;
  513. let five_proofs: Vec<_> = proofs.drain(..5).collect();
  514. let preswap = PreMintSecrets::random(keyset_id, 5.into(), &SplitTarget::default()).unwrap();
  515. let swap_request = SwapRequest::new(five_proofs.clone(), preswap.blinded_messages());
  516. // Attempt to swap underpaying fee
  517. match mint_bob.process_swap_request(swap_request).await {
  518. Ok(_) => panic!("Swap was allowed unbalanced"),
  519. Err(err) => match err {
  520. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  521. _ => {
  522. println!("{:?}", err);
  523. panic!("Wrong error returned")
  524. }
  525. },
  526. }
  527. let preswap = PreMintSecrets::random(keyset_id, 4.into(), &SplitTarget::default()).unwrap();
  528. let swap_request = SwapRequest::new(five_proofs.clone(), preswap.blinded_messages());
  529. let res = mint_bob.process_swap_request(swap_request).await;
  530. assert!(res.is_ok());
  531. let thousnad_proofs: Vec<_> = proofs.drain(..1001).collect();
  532. let preswap = PreMintSecrets::random(keyset_id, 1000.into(), &SplitTarget::default()).unwrap();
  533. let swap_request = SwapRequest::new(thousnad_proofs.clone(), preswap.blinded_messages());
  534. // Attempt to swap underpaying fee
  535. match mint_bob.process_swap_request(swap_request).await {
  536. Ok(_) => panic!("Swap was allowed unbalanced"),
  537. Err(err) => match err {
  538. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  539. _ => {
  540. println!("{:?}", err);
  541. panic!("Wrong error returned")
  542. }
  543. },
  544. }
  545. let preswap = PreMintSecrets::random(keyset_id, 999.into(), &SplitTarget::default()).unwrap();
  546. let swap_request = SwapRequest::new(thousnad_proofs.clone(), preswap.blinded_messages());
  547. let _ = mint_bob.process_swap_request(swap_request).await.unwrap();
  548. }
  549. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  550. async fn test_mint_change_with_fee_melt() {
  551. setup_tracing();
  552. let mint_bob = create_and_start_test_mint()
  553. .await
  554. .expect("Failed to create test mint");
  555. mint_bob
  556. .rotate_keyset(CurrencyUnit::Sat, 32, 1)
  557. .await
  558. .unwrap();
  559. let wallet_alice = create_test_wallet_for_mint(mint_bob.clone())
  560. .await
  561. .expect("Failed to create test wallet");
  562. // Alice gets 100 sats
  563. fund_wallet(
  564. wallet_alice.clone(),
  565. 100,
  566. Some(SplitTarget::Value(Amount::ONE)),
  567. )
  568. .await
  569. .expect("Failed to fund wallet");
  570. let proofs = wallet_alice
  571. .get_unspent_proofs()
  572. .await
  573. .expect("Could not get proofs");
  574. let fake_invoice = create_fake_invoice(1000, "".to_string());
  575. let melt_quote = wallet_alice
  576. .melt_quote(fake_invoice.to_string(), None)
  577. .await
  578. .unwrap();
  579. let w = wallet_alice
  580. .melt_proofs(&melt_quote.id, proofs)
  581. .await
  582. .unwrap();
  583. assert_eq!(w.change.unwrap().total_amount().unwrap(), 97.into());
  584. }
  585. /// Tests concurrent double-spending attempts by trying to use the same proofs
  586. /// in 3 swap transactions simultaneously using tokio tasks
  587. #[tokio::test(flavor = "multi_thread", worker_threads = 3)]
  588. async fn test_concurrent_double_spend_swap() {
  589. setup_tracing();
  590. let mint_bob = create_and_start_test_mint()
  591. .await
  592. .expect("Failed to create test mint");
  593. let wallet_alice = create_test_wallet_for_mint(mint_bob.clone())
  594. .await
  595. .expect("Failed to create test wallet");
  596. // Alice gets 100 sats
  597. fund_wallet(wallet_alice.clone(), 100, None)
  598. .await
  599. .expect("Failed to fund wallet");
  600. let proofs = wallet_alice
  601. .get_unspent_proofs()
  602. .await
  603. .expect("Could not get proofs");
  604. let keyset_id = get_keyset_id(&mint_bob).await;
  605. // Create 3 identical swap requests with the same proofs
  606. let preswap1 = PreMintSecrets::random(keyset_id, 100.into(), &SplitTarget::default())
  607. .expect("Failed to create preswap");
  608. let swap_request1 = SwapRequest::new(proofs.clone(), preswap1.blinded_messages());
  609. let preswap2 = PreMintSecrets::random(keyset_id, 100.into(), &SplitTarget::default())
  610. .expect("Failed to create preswap");
  611. let swap_request2 = SwapRequest::new(proofs.clone(), preswap2.blinded_messages());
  612. let preswap3 = PreMintSecrets::random(keyset_id, 100.into(), &SplitTarget::default())
  613. .expect("Failed to create preswap");
  614. let swap_request3 = SwapRequest::new(proofs.clone(), preswap3.blinded_messages());
  615. // Spawn 3 concurrent tasks to process the swap requests
  616. let mint_clone1 = mint_bob.clone();
  617. let mint_clone2 = mint_bob.clone();
  618. let mint_clone3 = mint_bob.clone();
  619. let task1 = tokio::spawn(async move { mint_clone1.process_swap_request(swap_request1).await });
  620. let task2 = tokio::spawn(async move { mint_clone2.process_swap_request(swap_request2).await });
  621. let task3 = tokio::spawn(async move { mint_clone3.process_swap_request(swap_request3).await });
  622. // Wait for all tasks to complete
  623. let results = tokio::try_join!(task1, task2, task3).expect("Tasks failed to complete");
  624. // Count successes and failures
  625. let mut success_count = 0;
  626. let mut token_already_spent_count = 0;
  627. for result in [results.0, results.1, results.2] {
  628. match result {
  629. Ok(_) => success_count += 1,
  630. Err(err) => match err {
  631. cdk::Error::TokenAlreadySpent | cdk::Error::TokenPending => {
  632. token_already_spent_count += 1
  633. }
  634. other_err => panic!("Unexpected error: {:?}", other_err),
  635. },
  636. }
  637. }
  638. // Only one swap should succeed, the other two should fail with TokenAlreadySpent
  639. assert_eq!(1, success_count, "Expected exactly one successful swap");
  640. assert_eq!(
  641. 2, token_already_spent_count,
  642. "Expected exactly two TokenAlreadySpent errors"
  643. );
  644. // Verify that all proofs are marked as spent in the mint
  645. let states = mint_bob
  646. .localstore()
  647. .get_proofs_states(&proofs.iter().map(|p| p.y().unwrap()).collect::<Vec<_>>())
  648. .await
  649. .expect("Failed to get proof state");
  650. for state in states {
  651. assert_eq!(
  652. State::Spent,
  653. state.expect("Known state"),
  654. "Expected proof to be marked as spent, but got {:?}",
  655. state
  656. );
  657. }
  658. }
  659. /// Tests concurrent double-spending attempts by trying to use the same proofs
  660. /// in 3 melt transactions simultaneously using tokio tasks
  661. #[tokio::test(flavor = "multi_thread", worker_threads = 3)]
  662. async fn test_concurrent_double_spend_melt() {
  663. setup_tracing();
  664. let mint_bob = create_and_start_test_mint()
  665. .await
  666. .expect("Failed to create test mint");
  667. let wallet_alice = create_test_wallet_for_mint(mint_bob.clone())
  668. .await
  669. .expect("Failed to create test wallet");
  670. // Alice gets 100 sats
  671. fund_wallet(wallet_alice.clone(), 100, None)
  672. .await
  673. .expect("Failed to fund wallet");
  674. let proofs = wallet_alice
  675. .get_unspent_proofs()
  676. .await
  677. .expect("Could not get proofs");
  678. // Create a Lightning invoice for the melt
  679. let invoice = create_fake_invoice(1000, "".to_string());
  680. // Create a melt quote
  681. let melt_quote = wallet_alice
  682. .melt_quote(invoice.to_string(), None)
  683. .await
  684. .expect("Failed to create melt quote");
  685. // Get the quote ID and payment request
  686. let quote_id = melt_quote.id.clone();
  687. // Create 3 identical melt requests with the same proofs
  688. let mint_clone1 = mint_bob.clone();
  689. let mint_clone2 = mint_bob.clone();
  690. let mint_clone3 = mint_bob.clone();
  691. let melt_request = MeltRequest::new(quote_id.parse().unwrap(), proofs.clone(), None);
  692. let melt_request2 = melt_request.clone();
  693. let melt_request3 = melt_request.clone();
  694. // Spawn 3 concurrent tasks to process the melt requests
  695. let task1 = tokio::spawn(async move { mint_clone1.melt(&melt_request).await });
  696. let task2 = tokio::spawn(async move { mint_clone2.melt(&melt_request2).await });
  697. let task3 = tokio::spawn(async move { mint_clone3.melt(&melt_request3).await });
  698. // Wait for all tasks to complete
  699. let results = tokio::try_join!(task1, task2, task3).expect("Tasks failed to complete");
  700. // Count successes and failures
  701. let mut success_count = 0;
  702. let mut token_already_spent_count = 0;
  703. for result in [results.0, results.1, results.2] {
  704. match result {
  705. Ok(_) => success_count += 1,
  706. Err(err) => match err {
  707. cdk::Error::TokenAlreadySpent | cdk::Error::TokenPending => {
  708. token_already_spent_count += 1;
  709. println!("Got expected error: {:?}", err);
  710. }
  711. other_err => {
  712. println!("Got unexpected error: {:?}", other_err);
  713. token_already_spent_count += 1;
  714. }
  715. },
  716. }
  717. }
  718. // Only one melt should succeed, the other two should fail
  719. assert_eq!(1, success_count, "Expected exactly one successful melt");
  720. assert_eq!(
  721. 2, token_already_spent_count,
  722. "Expected exactly two TokenAlreadySpent errors"
  723. );
  724. // Verify that all proofs are marked as spent in the mint
  725. let states = mint_bob
  726. .localstore()
  727. .get_proofs_states(&proofs.iter().map(|p| p.y().unwrap()).collect::<Vec<_>>())
  728. .await
  729. .expect("Failed to get proof state");
  730. for state in states {
  731. assert_eq!(
  732. State::Spent,
  733. state.expect("Known state"),
  734. "Expected proof to be marked as spent, but got {:?}",
  735. state
  736. );
  737. }
  738. }
  739. async fn get_keyset_id(mint: &Mint) -> Id {
  740. let keys = mint.pubkeys().keysets.first().unwrap().clone();
  741. keys.verify_id()
  742. .expect("Keyset ID generation is successful");
  743. keys.id
  744. }