integration_tests_pure.rs 29 KB

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