integration_tests_pure.rs 29 KB

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