integration_tests_pure.rs 29 KB

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