integration_tests_pure.rs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  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 (i, key) in public_keys_to_listen.into_iter().enumerate() {
  445. let statuses = msgs.remove(&key).expect("some events");
  446. // Every input pk receives two state updates, as there are only two state transitions
  447. assert_eq!(
  448. statuses,
  449. vec![State::Pending, State::Spent],
  450. "failed to test key {:?} (pos {})",
  451. key,
  452. i,
  453. );
  454. }
  455. assert!(listener.try_recv().is_err(), "no other event is happening");
  456. assert!(msgs.is_empty(), "Only expected key events are received");
  457. }
  458. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  459. async fn test_swap_overpay_underpay_fee() {
  460. setup_tracing();
  461. let mint_bob = create_and_start_test_mint()
  462. .await
  463. .expect("Failed to create test mint");
  464. mint_bob
  465. .rotate_keyset(CurrencyUnit::Sat, 1, 32, 1)
  466. .await
  467. .unwrap();
  468. let wallet_alice = create_test_wallet_for_mint(mint_bob.clone())
  469. .await
  470. .expect("Failed to create test wallet");
  471. // Alice gets 100 sats
  472. fund_wallet(wallet_alice.clone(), 1000, None)
  473. .await
  474. .expect("Failed to fund wallet");
  475. let proofs = wallet_alice
  476. .get_unspent_proofs()
  477. .await
  478. .expect("Could not get proofs");
  479. let keys = mint_bob
  480. .pubkeys()
  481. .await
  482. .unwrap()
  483. .keysets
  484. .first()
  485. .unwrap()
  486. .clone()
  487. .keys;
  488. let keyset_id = Id::from(&keys);
  489. let preswap = PreMintSecrets::random(keyset_id, 9998.into(), &SplitTarget::default()).unwrap();
  490. let swap_request = SwapRequest::new(proofs.clone(), preswap.blinded_messages());
  491. // Attempt to swap overpaying fee
  492. match mint_bob.process_swap_request(swap_request).await {
  493. Ok(_) => panic!("Swap was allowed unbalanced"),
  494. Err(err) => match err {
  495. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  496. _ => {
  497. println!("{:?}", err);
  498. panic!("Wrong error returned")
  499. }
  500. },
  501. }
  502. let preswap = PreMintSecrets::random(keyset_id, 1000.into(), &SplitTarget::default()).unwrap();
  503. let swap_request = SwapRequest::new(proofs.clone(), preswap.blinded_messages());
  504. // Attempt to swap underpaying fee
  505. match mint_bob.process_swap_request(swap_request).await {
  506. Ok(_) => panic!("Swap was allowed unbalanced"),
  507. Err(err) => match err {
  508. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  509. _ => {
  510. println!("{:?}", err);
  511. panic!("Wrong error returned")
  512. }
  513. },
  514. }
  515. }
  516. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  517. async fn test_mint_enforce_fee() {
  518. setup_tracing();
  519. let mint_bob = create_and_start_test_mint()
  520. .await
  521. .expect("Failed to create test mint");
  522. mint_bob
  523. .rotate_keyset(CurrencyUnit::Sat, 1, 32, 1)
  524. .await
  525. .unwrap();
  526. let wallet_alice = create_test_wallet_for_mint(mint_bob.clone())
  527. .await
  528. .expect("Failed to create test wallet");
  529. // Alice gets 100 sats
  530. fund_wallet(
  531. wallet_alice.clone(),
  532. 1010,
  533. Some(SplitTarget::Value(Amount::ONE)),
  534. )
  535. .await
  536. .expect("Failed to fund wallet");
  537. let mut proofs = wallet_alice
  538. .get_unspent_proofs()
  539. .await
  540. .expect("Could not get proofs");
  541. let keys = mint_bob
  542. .pubkeys()
  543. .await
  544. .unwrap()
  545. .keysets
  546. .first()
  547. .unwrap()
  548. .clone()
  549. .keys;
  550. let keyset_id = Id::from(&keys);
  551. let five_proofs: Vec<_> = proofs.drain(..5).collect();
  552. let preswap = PreMintSecrets::random(keyset_id, 5.into(), &SplitTarget::default()).unwrap();
  553. let swap_request = SwapRequest::new(five_proofs.clone(), preswap.blinded_messages());
  554. // Attempt to swap underpaying fee
  555. match mint_bob.process_swap_request(swap_request).await {
  556. Ok(_) => panic!("Swap was allowed unbalanced"),
  557. Err(err) => match err {
  558. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  559. _ => {
  560. println!("{:?}", err);
  561. panic!("Wrong error returned")
  562. }
  563. },
  564. }
  565. let preswap = PreMintSecrets::random(keyset_id, 4.into(), &SplitTarget::default()).unwrap();
  566. let swap_request = SwapRequest::new(five_proofs.clone(), preswap.blinded_messages());
  567. let res = mint_bob.process_swap_request(swap_request).await;
  568. assert!(res.is_ok());
  569. let thousnad_proofs: Vec<_> = proofs.drain(..1001).collect();
  570. let preswap = PreMintSecrets::random(keyset_id, 1000.into(), &SplitTarget::default()).unwrap();
  571. let swap_request = SwapRequest::new(thousnad_proofs.clone(), preswap.blinded_messages());
  572. // Attempt to swap underpaying fee
  573. match mint_bob.process_swap_request(swap_request).await {
  574. Ok(_) => panic!("Swap was allowed unbalanced"),
  575. Err(err) => match err {
  576. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  577. _ => {
  578. println!("{:?}", err);
  579. panic!("Wrong error returned")
  580. }
  581. },
  582. }
  583. let preswap = PreMintSecrets::random(keyset_id, 999.into(), &SplitTarget::default()).unwrap();
  584. let swap_request = SwapRequest::new(thousnad_proofs.clone(), preswap.blinded_messages());
  585. let _ = mint_bob.process_swap_request(swap_request).await.unwrap();
  586. }
  587. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  588. async fn test_mint_change_with_fee_melt() {
  589. setup_tracing();
  590. let mint_bob = create_and_start_test_mint()
  591. .await
  592. .expect("Failed to create test mint");
  593. mint_bob
  594. .rotate_keyset(CurrencyUnit::Sat, 1, 32, 1)
  595. .await
  596. .unwrap();
  597. let wallet_alice = create_test_wallet_for_mint(mint_bob.clone())
  598. .await
  599. .expect("Failed to create test wallet");
  600. // Alice gets 100 sats
  601. fund_wallet(
  602. wallet_alice.clone(),
  603. 100,
  604. Some(SplitTarget::Value(Amount::ONE)),
  605. )
  606. .await
  607. .expect("Failed to fund wallet");
  608. let proofs = wallet_alice
  609. .get_unspent_proofs()
  610. .await
  611. .expect("Could not get proofs");
  612. let fake_invoice = create_fake_invoice(1000, "".to_string());
  613. let melt_quote = wallet_alice
  614. .melt_quote(fake_invoice.to_string(), None)
  615. .await
  616. .unwrap();
  617. let w = wallet_alice
  618. .melt_proofs(&melt_quote.id, proofs)
  619. .await
  620. .unwrap();
  621. assert_eq!(w.change.unwrap().total_amount().unwrap(), 97.into());
  622. }
  623. /// Tests concurrent double-spending attempts by trying to use the same proofs
  624. /// in 3 swap transactions simultaneously using tokio tasks
  625. #[tokio::test(flavor = "multi_thread", worker_threads = 3)]
  626. async fn test_concurrent_double_spend_swap() {
  627. setup_tracing();
  628. let mint_bob = create_and_start_test_mint()
  629. .await
  630. .expect("Failed to create test mint");
  631. let wallet_alice = create_test_wallet_for_mint(mint_bob.clone())
  632. .await
  633. .expect("Failed to create test wallet");
  634. // Alice gets 100 sats
  635. fund_wallet(wallet_alice.clone(), 100, None)
  636. .await
  637. .expect("Failed to fund wallet");
  638. let proofs = wallet_alice
  639. .get_unspent_proofs()
  640. .await
  641. .expect("Could not get proofs");
  642. let keyset_id = get_keyset_id(&mint_bob).await;
  643. // Create 3 identical swap requests with the same proofs
  644. let preswap1 = PreMintSecrets::random(keyset_id, 100.into(), &SplitTarget::default())
  645. .expect("Failed to create preswap");
  646. let swap_request1 = SwapRequest::new(proofs.clone(), preswap1.blinded_messages());
  647. let preswap2 = PreMintSecrets::random(keyset_id, 100.into(), &SplitTarget::default())
  648. .expect("Failed to create preswap");
  649. let swap_request2 = SwapRequest::new(proofs.clone(), preswap2.blinded_messages());
  650. let preswap3 = PreMintSecrets::random(keyset_id, 100.into(), &SplitTarget::default())
  651. .expect("Failed to create preswap");
  652. let swap_request3 = SwapRequest::new(proofs.clone(), preswap3.blinded_messages());
  653. // Spawn 3 concurrent tasks to process the swap requests
  654. let mint_clone1 = mint_bob.clone();
  655. let mint_clone2 = mint_bob.clone();
  656. let mint_clone3 = mint_bob.clone();
  657. let task1 = tokio::spawn(async move { mint_clone1.process_swap_request(swap_request1).await });
  658. let task2 = tokio::spawn(async move { mint_clone2.process_swap_request(swap_request2).await });
  659. let task3 = tokio::spawn(async move { mint_clone3.process_swap_request(swap_request3).await });
  660. // Wait for all tasks to complete
  661. let results = tokio::try_join!(task1, task2, task3).expect("Tasks failed to complete");
  662. // Count successes and failures
  663. let mut success_count = 0;
  664. let mut token_already_spent_count = 0;
  665. for result in [results.0, results.1, results.2] {
  666. match result {
  667. Ok(_) => success_count += 1,
  668. Err(err) => match err {
  669. cdk::Error::TokenAlreadySpent | cdk::Error::TokenPending => {
  670. token_already_spent_count += 1
  671. }
  672. other_err => panic!("Unexpected error: {:?}", other_err),
  673. },
  674. }
  675. }
  676. // Only one swap should succeed, the other two should fail with TokenAlreadySpent
  677. assert_eq!(1, success_count, "Expected exactly one successful swap");
  678. assert_eq!(
  679. 2, token_already_spent_count,
  680. "Expected exactly two TokenAlreadySpent errors"
  681. );
  682. // Verify that all proofs are marked as spent in the mint
  683. let states = mint_bob
  684. .localstore
  685. .get_proofs_states(&proofs.iter().map(|p| p.y().unwrap()).collect::<Vec<_>>())
  686. .await
  687. .expect("Failed to get proof state");
  688. for state in states {
  689. assert_eq!(
  690. State::Spent,
  691. state.expect("Known state"),
  692. "Expected proof to be marked as spent, but got {:?}",
  693. state
  694. );
  695. }
  696. }
  697. /// Tests concurrent double-spending attempts by trying to use the same proofs
  698. /// in 3 melt transactions simultaneously using tokio tasks
  699. #[tokio::test(flavor = "multi_thread", worker_threads = 3)]
  700. async fn test_concurrent_double_spend_melt() {
  701. setup_tracing();
  702. let mint_bob = create_and_start_test_mint()
  703. .await
  704. .expect("Failed to create test mint");
  705. let wallet_alice = create_test_wallet_for_mint(mint_bob.clone())
  706. .await
  707. .expect("Failed to create test wallet");
  708. // Alice gets 100 sats
  709. fund_wallet(wallet_alice.clone(), 100, None)
  710. .await
  711. .expect("Failed to fund wallet");
  712. let proofs = wallet_alice
  713. .get_unspent_proofs()
  714. .await
  715. .expect("Could not get proofs");
  716. // Create a Lightning invoice for the melt
  717. let invoice = create_fake_invoice(1000, "".to_string());
  718. // Create a melt quote
  719. let melt_quote = wallet_alice
  720. .melt_quote(invoice.to_string(), None)
  721. .await
  722. .expect("Failed to create melt quote");
  723. // Get the quote ID and payment request
  724. let quote_id = melt_quote.id.clone();
  725. // Create 3 identical melt requests with the same proofs
  726. let mint_clone1 = mint_bob.clone();
  727. let mint_clone2 = mint_bob.clone();
  728. let mint_clone3 = mint_bob.clone();
  729. let melt_request = MeltBolt11Request::new(quote_id.parse().unwrap(), proofs.clone(), None);
  730. let melt_request2 = melt_request.clone();
  731. let melt_request3 = melt_request.clone();
  732. // Spawn 3 concurrent tasks to process the melt requests
  733. let task1 = tokio::spawn(async move { mint_clone1.melt_bolt11(&melt_request).await });
  734. let task2 = tokio::spawn(async move { mint_clone2.melt_bolt11(&melt_request2).await });
  735. let task3 = tokio::spawn(async move { mint_clone3.melt_bolt11(&melt_request3).await });
  736. // Wait for all tasks to complete
  737. let results = tokio::try_join!(task1, task2, task3).expect("Tasks failed to complete");
  738. // Count successes and failures
  739. let mut success_count = 0;
  740. let mut token_already_spent_count = 0;
  741. for result in [results.0, results.1, results.2] {
  742. match result {
  743. Ok(_) => success_count += 1,
  744. Err(err) => match err {
  745. cdk::Error::TokenAlreadySpent | cdk::Error::TokenPending => {
  746. token_already_spent_count += 1;
  747. println!("Got expected error: {:?}", err);
  748. }
  749. other_err => {
  750. println!("Got unexpected error: {:?}", other_err);
  751. token_already_spent_count += 1;
  752. }
  753. },
  754. }
  755. }
  756. // Only one melt should succeed, the other two should fail
  757. assert_eq!(1, success_count, "Expected exactly one successful melt");
  758. assert_eq!(
  759. 2, token_already_spent_count,
  760. "Expected exactly two TokenAlreadySpent errors"
  761. );
  762. // Verify that all proofs are marked as spent in the mint
  763. let states = mint_bob
  764. .localstore
  765. .get_proofs_states(&proofs.iter().map(|p| p.y().unwrap()).collect::<Vec<_>>())
  766. .await
  767. .expect("Failed to get proof state");
  768. for state in states {
  769. assert_eq!(
  770. State::Spent,
  771. state.expect("Known state"),
  772. "Expected proof to be marked as spent, but got {:?}",
  773. state
  774. );
  775. }
  776. }
  777. async fn get_keyset_id(mint: &Mint) -> Id {
  778. let keys = mint
  779. .pubkeys()
  780. .await
  781. .unwrap()
  782. .keysets
  783. .first()
  784. .unwrap()
  785. .clone()
  786. .keys;
  787. Id::from(&keys)
  788. }