integration_tests_pure.rs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  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, MeltBolt11Request, NotificationPayload, PreMintSecrets, ProofState,
  16. SecretKey, 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
  221. .pubkeys()
  222. .await
  223. .unwrap()
  224. .keysets
  225. .first()
  226. .unwrap()
  227. .clone()
  228. .keys;
  229. let keyset_id = Id::from(&keys);
  230. let preswap = PreMintSecrets::random(
  231. keyset_id,
  232. proofs.total_amount().unwrap(),
  233. &SplitTarget::default(),
  234. )
  235. .unwrap();
  236. let swap_request = SwapRequest::new(proofs.clone(), preswap.blinded_messages());
  237. let swap = mint_bob.process_swap_request(swap_request).await;
  238. assert!(swap.is_ok());
  239. let preswap_two = PreMintSecrets::random(
  240. keyset_id,
  241. proofs.total_amount().unwrap(),
  242. &SplitTarget::default(),
  243. )
  244. .unwrap();
  245. let swap_two_request = SwapRequest::new(proofs, preswap_two.blinded_messages());
  246. match mint_bob.process_swap_request(swap_two_request).await {
  247. Ok(_) => panic!("Proofs double spent"),
  248. Err(err) => match err {
  249. cdk::Error::TokenAlreadySpent => (),
  250. _ => panic!("Wrong error returned"),
  251. },
  252. }
  253. }
  254. /// This attempts to swap for more outputs then inputs.
  255. /// This will work if the mint does not check for outputs amounts overflowing
  256. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  257. async fn test_attempt_to_swap_by_overflowing() {
  258. setup_tracing();
  259. let mint_bob = create_and_start_test_mint()
  260. .await
  261. .expect("Failed to create test mint");
  262. let wallet_alice = create_test_wallet_for_mint(mint_bob.clone())
  263. .await
  264. .expect("Failed to create test wallet");
  265. // Alice gets 64 sats
  266. fund_wallet(wallet_alice.clone(), 64, None)
  267. .await
  268. .expect("Failed to fund wallet");
  269. let proofs = wallet_alice
  270. .get_unspent_proofs()
  271. .await
  272. .expect("Could not get proofs");
  273. let amount = 2_u64.pow(63);
  274. let keys = mint_bob
  275. .pubkeys()
  276. .await
  277. .unwrap()
  278. .keysets
  279. .first()
  280. .unwrap()
  281. .clone()
  282. .keys;
  283. let keyset_id = Id::from(&keys);
  284. let pre_mint_amount =
  285. PreMintSecrets::random(keyset_id, amount.into(), &SplitTarget::default()).unwrap();
  286. let pre_mint_amount_two =
  287. PreMintSecrets::random(keyset_id, amount.into(), &SplitTarget::default()).unwrap();
  288. let mut pre_mint =
  289. PreMintSecrets::random(keyset_id, 1.into(), &SplitTarget::default()).unwrap();
  290. pre_mint.combine(pre_mint_amount);
  291. pre_mint.combine(pre_mint_amount_two);
  292. let swap_request = SwapRequest::new(proofs.clone(), pre_mint.blinded_messages());
  293. match mint_bob.process_swap_request(swap_request).await {
  294. Ok(_) => panic!("Swap occurred with overflow"),
  295. Err(err) => match err {
  296. cdk::Error::NUT03(cdk::nuts::nut03::Error::Amount(_)) => (),
  297. cdk::Error::AmountOverflow => (),
  298. cdk::Error::AmountError(_) => (),
  299. _ => {
  300. println!("{:?}", err);
  301. panic!("Wrong error returned in swap overflow")
  302. }
  303. },
  304. }
  305. }
  306. /// Tests that the mint correctly rejects unbalanced swap requests:
  307. /// 1. Attempts to swap for less than the input amount (95 < 100)
  308. /// 2. Attempts to swap for more than the input amount (101 > 100)
  309. /// 3. Both should fail with TransactionUnbalanced error
  310. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  311. async fn test_swap_unbalanced() {
  312. setup_tracing();
  313. let mint_bob = create_and_start_test_mint()
  314. .await
  315. .expect("Failed to create test mint");
  316. let wallet_alice = create_test_wallet_for_mint(mint_bob.clone())
  317. .await
  318. .expect("Failed to create test wallet");
  319. // Alice gets 100 sats
  320. fund_wallet(wallet_alice.clone(), 100, None)
  321. .await
  322. .expect("Failed to fund wallet");
  323. let proofs = wallet_alice
  324. .get_unspent_proofs()
  325. .await
  326. .expect("Could not get proofs");
  327. let keyset_id = get_keyset_id(&mint_bob).await;
  328. // Try to swap for less than the input amount (95 < 100)
  329. let preswap = PreMintSecrets::random(keyset_id, 95.into(), &SplitTarget::default())
  330. .expect("Failed to create preswap");
  331. let swap_request = SwapRequest::new(proofs.clone(), preswap.blinded_messages());
  332. match mint_bob.process_swap_request(swap_request).await {
  333. Ok(_) => panic!("Swap was allowed unbalanced"),
  334. Err(err) => match err {
  335. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  336. _ => panic!("Wrong error returned"),
  337. },
  338. }
  339. // Try to swap for more than the input amount (101 > 100)
  340. let preswap = PreMintSecrets::random(keyset_id, 101.into(), &SplitTarget::default())
  341. .expect("Failed to create preswap");
  342. let swap_request = SwapRequest::new(proofs.clone(), preswap.blinded_messages());
  343. match mint_bob.process_swap_request(swap_request).await {
  344. Ok(_) => panic!("Swap was allowed unbalanced"),
  345. Err(err) => match err {
  346. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  347. _ => panic!("Wrong error returned"),
  348. },
  349. }
  350. }
  351. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  352. pub async fn test_p2pk_swap() {
  353. setup_tracing();
  354. let mint_bob = create_and_start_test_mint()
  355. .await
  356. .expect("Failed to create test mint");
  357. let wallet_alice = create_test_wallet_for_mint(mint_bob.clone())
  358. .await
  359. .expect("Failed to create test wallet");
  360. // Alice gets 100 sats
  361. fund_wallet(wallet_alice.clone(), 100, None)
  362. .await
  363. .expect("Failed to fund wallet");
  364. let proofs = wallet_alice
  365. .get_unspent_proofs()
  366. .await
  367. .expect("Could not get proofs");
  368. let keyset_id = get_keyset_id(&mint_bob).await;
  369. let secret = SecretKey::generate();
  370. let spending_conditions = SpendingConditions::new_p2pk(secret.public_key(), None);
  371. let pre_swap = PreMintSecrets::with_conditions(
  372. keyset_id,
  373. 100.into(),
  374. &SplitTarget::default(),
  375. &spending_conditions,
  376. )
  377. .unwrap();
  378. let swap_request = SwapRequest::new(proofs.clone(), pre_swap.blinded_messages());
  379. let keys = mint_bob
  380. .pubkeys()
  381. .await
  382. .unwrap()
  383. .keysets
  384. .first()
  385. .cloned()
  386. .unwrap()
  387. .keys;
  388. let post_swap = mint_bob.process_swap_request(swap_request).await.unwrap();
  389. let mut proofs = construct_proofs(
  390. post_swap.signatures,
  391. pre_swap.rs(),
  392. pre_swap.secrets(),
  393. &keys,
  394. )
  395. .unwrap();
  396. let pre_swap = PreMintSecrets::random(keyset_id, 100.into(), &SplitTarget::default()).unwrap();
  397. let swap_request = SwapRequest::new(proofs.clone(), pre_swap.blinded_messages());
  398. // Listen for status updates on all input proof pks
  399. let public_keys_to_listen: Vec<_> = swap_request
  400. .inputs()
  401. .ys()
  402. .unwrap()
  403. .iter()
  404. .map(|pk| pk.to_string())
  405. .collect();
  406. let mut listener = mint_bob
  407. .pubsub_manager
  408. .try_subscribe::<IndexableParams>(
  409. Params {
  410. kind: cdk::nuts::nut17::Kind::ProofState,
  411. filters: public_keys_to_listen.clone(),
  412. id: "test".into(),
  413. }
  414. .into(),
  415. )
  416. .await
  417. .expect("valid subscription");
  418. match mint_bob.process_swap_request(swap_request).await {
  419. Ok(_) => panic!("Proofs spent without sig"),
  420. Err(err) => match err {
  421. cdk::Error::NUT11(cdk::nuts::nut11::Error::SignaturesNotProvided) => (),
  422. _ => {
  423. println!("{:?}", err);
  424. panic!("Wrong error returned")
  425. }
  426. },
  427. }
  428. for proof in &mut proofs {
  429. proof.sign_p2pk(secret.clone()).unwrap();
  430. }
  431. let swap_request = SwapRequest::new(proofs.clone(), pre_swap.blinded_messages());
  432. let attempt_swap = mint_bob.process_swap_request(swap_request).await;
  433. assert!(attempt_swap.is_ok());
  434. sleep(Duration::from_secs(1)).await;
  435. let mut msgs = HashMap::new();
  436. while let Ok((sub_id, msg)) = listener.try_recv() {
  437. assert_eq!(sub_id, "test".into());
  438. match msg {
  439. NotificationPayload::ProofState(ProofState { y, state, .. }) => {
  440. msgs.entry(y.to_string())
  441. .or_insert_with(Vec::new)
  442. .push(state);
  443. }
  444. _ => panic!("Wrong message received"),
  445. }
  446. }
  447. for (i, key) in public_keys_to_listen.into_iter().enumerate() {
  448. let statuses = msgs.remove(&key).expect("some events");
  449. // Every input pk receives two state updates, as there are only two state transitions
  450. assert_eq!(
  451. statuses,
  452. vec![State::Pending, State::Spent],
  453. "failed to test key {:?} (pos {})",
  454. key,
  455. i,
  456. );
  457. }
  458. assert!(listener.try_recv().is_err(), "no other event is happening");
  459. assert!(msgs.is_empty(), "Only expected key events are received");
  460. }
  461. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  462. async fn test_swap_overpay_underpay_fee() {
  463. setup_tracing();
  464. let mint_bob = create_and_start_test_mint()
  465. .await
  466. .expect("Failed to create test mint");
  467. mint_bob
  468. .rotate_keyset(CurrencyUnit::Sat, 1, 32, 1)
  469. .await
  470. .unwrap();
  471. let wallet_alice = create_test_wallet_for_mint(mint_bob.clone())
  472. .await
  473. .expect("Failed to create test wallet");
  474. // Alice gets 100 sats
  475. fund_wallet(wallet_alice.clone(), 1000, None)
  476. .await
  477. .expect("Failed to fund wallet");
  478. let proofs = wallet_alice
  479. .get_unspent_proofs()
  480. .await
  481. .expect("Could not get proofs");
  482. let keys = mint_bob
  483. .pubkeys()
  484. .await
  485. .unwrap()
  486. .keysets
  487. .first()
  488. .unwrap()
  489. .clone()
  490. .keys;
  491. let keyset_id = Id::from(&keys);
  492. let preswap = PreMintSecrets::random(keyset_id, 9998.into(), &SplitTarget::default()).unwrap();
  493. let swap_request = SwapRequest::new(proofs.clone(), preswap.blinded_messages());
  494. // Attempt to swap overpaying fee
  495. match mint_bob.process_swap_request(swap_request).await {
  496. Ok(_) => panic!("Swap was allowed unbalanced"),
  497. Err(err) => match err {
  498. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  499. _ => {
  500. println!("{:?}", err);
  501. panic!("Wrong error returned")
  502. }
  503. },
  504. }
  505. let preswap = PreMintSecrets::random(keyset_id, 1000.into(), &SplitTarget::default()).unwrap();
  506. let swap_request = SwapRequest::new(proofs.clone(), preswap.blinded_messages());
  507. // Attempt to swap underpaying fee
  508. match mint_bob.process_swap_request(swap_request).await {
  509. Ok(_) => panic!("Swap was allowed unbalanced"),
  510. Err(err) => match err {
  511. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  512. _ => {
  513. println!("{:?}", err);
  514. panic!("Wrong error returned")
  515. }
  516. },
  517. }
  518. }
  519. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  520. async fn test_mint_enforce_fee() {
  521. setup_tracing();
  522. let mint_bob = create_and_start_test_mint()
  523. .await
  524. .expect("Failed to create test mint");
  525. mint_bob
  526. .rotate_keyset(CurrencyUnit::Sat, 1, 32, 1)
  527. .await
  528. .unwrap();
  529. let wallet_alice = create_test_wallet_for_mint(mint_bob.clone())
  530. .await
  531. .expect("Failed to create test wallet");
  532. // Alice gets 100 sats
  533. fund_wallet(
  534. wallet_alice.clone(),
  535. 1010,
  536. Some(SplitTarget::Value(Amount::ONE)),
  537. )
  538. .await
  539. .expect("Failed to fund wallet");
  540. let mut proofs = wallet_alice
  541. .get_unspent_proofs()
  542. .await
  543. .expect("Could not get proofs");
  544. let keys = mint_bob
  545. .pubkeys()
  546. .await
  547. .unwrap()
  548. .keysets
  549. .first()
  550. .unwrap()
  551. .clone()
  552. .keys;
  553. let keyset_id = Id::from(&keys);
  554. let five_proofs: Vec<_> = proofs.drain(..5).collect();
  555. let preswap = PreMintSecrets::random(keyset_id, 5.into(), &SplitTarget::default()).unwrap();
  556. let swap_request = SwapRequest::new(five_proofs.clone(), preswap.blinded_messages());
  557. // Attempt to swap underpaying fee
  558. match mint_bob.process_swap_request(swap_request).await {
  559. Ok(_) => panic!("Swap was allowed unbalanced"),
  560. Err(err) => match err {
  561. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  562. _ => {
  563. println!("{:?}", err);
  564. panic!("Wrong error returned")
  565. }
  566. },
  567. }
  568. let preswap = PreMintSecrets::random(keyset_id, 4.into(), &SplitTarget::default()).unwrap();
  569. let swap_request = SwapRequest::new(five_proofs.clone(), preswap.blinded_messages());
  570. let res = mint_bob.process_swap_request(swap_request).await;
  571. assert!(res.is_ok());
  572. let thousnad_proofs: Vec<_> = proofs.drain(..1001).collect();
  573. let preswap = PreMintSecrets::random(keyset_id, 1000.into(), &SplitTarget::default()).unwrap();
  574. let swap_request = SwapRequest::new(thousnad_proofs.clone(), preswap.blinded_messages());
  575. // Attempt to swap underpaying fee
  576. match mint_bob.process_swap_request(swap_request).await {
  577. Ok(_) => panic!("Swap was allowed unbalanced"),
  578. Err(err) => match err {
  579. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  580. _ => {
  581. println!("{:?}", err);
  582. panic!("Wrong error returned")
  583. }
  584. },
  585. }
  586. let preswap = PreMintSecrets::random(keyset_id, 999.into(), &SplitTarget::default()).unwrap();
  587. let swap_request = SwapRequest::new(thousnad_proofs.clone(), preswap.blinded_messages());
  588. let _ = mint_bob.process_swap_request(swap_request).await.unwrap();
  589. }
  590. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  591. async fn test_mint_change_with_fee_melt() {
  592. setup_tracing();
  593. let mint_bob = create_and_start_test_mint()
  594. .await
  595. .expect("Failed to create test mint");
  596. mint_bob
  597. .rotate_keyset(CurrencyUnit::Sat, 1, 32, 1)
  598. .await
  599. .unwrap();
  600. let wallet_alice = create_test_wallet_for_mint(mint_bob.clone())
  601. .await
  602. .expect("Failed to create test wallet");
  603. // Alice gets 100 sats
  604. fund_wallet(
  605. wallet_alice.clone(),
  606. 100,
  607. Some(SplitTarget::Value(Amount::ONE)),
  608. )
  609. .await
  610. .expect("Failed to fund wallet");
  611. let proofs = wallet_alice
  612. .get_unspent_proofs()
  613. .await
  614. .expect("Could not get proofs");
  615. let fake_invoice = create_fake_invoice(1000, "".to_string());
  616. let melt_quote = wallet_alice
  617. .melt_quote(fake_invoice.to_string(), None)
  618. .await
  619. .unwrap();
  620. let w = wallet_alice
  621. .melt_proofs(&melt_quote.id, proofs)
  622. .await
  623. .unwrap();
  624. assert_eq!(w.change.unwrap().total_amount().unwrap(), 97.into());
  625. }
  626. /// Tests concurrent double-spending attempts by trying to use the same proofs
  627. /// in 3 swap transactions simultaneously using tokio tasks
  628. #[tokio::test(flavor = "multi_thread", worker_threads = 3)]
  629. async fn test_concurrent_double_spend_swap() {
  630. setup_tracing();
  631. let mint_bob = create_and_start_test_mint()
  632. .await
  633. .expect("Failed to create test mint");
  634. let wallet_alice = create_test_wallet_for_mint(mint_bob.clone())
  635. .await
  636. .expect("Failed to create test wallet");
  637. // Alice gets 100 sats
  638. fund_wallet(wallet_alice.clone(), 100, None)
  639. .await
  640. .expect("Failed to fund wallet");
  641. let proofs = wallet_alice
  642. .get_unspent_proofs()
  643. .await
  644. .expect("Could not get proofs");
  645. let keyset_id = get_keyset_id(&mint_bob).await;
  646. // Create 3 identical swap requests with the same proofs
  647. let preswap1 = PreMintSecrets::random(keyset_id, 100.into(), &SplitTarget::default())
  648. .expect("Failed to create preswap");
  649. let swap_request1 = SwapRequest::new(proofs.clone(), preswap1.blinded_messages());
  650. let preswap2 = PreMintSecrets::random(keyset_id, 100.into(), &SplitTarget::default())
  651. .expect("Failed to create preswap");
  652. let swap_request2 = SwapRequest::new(proofs.clone(), preswap2.blinded_messages());
  653. let preswap3 = PreMintSecrets::random(keyset_id, 100.into(), &SplitTarget::default())
  654. .expect("Failed to create preswap");
  655. let swap_request3 = SwapRequest::new(proofs.clone(), preswap3.blinded_messages());
  656. // Spawn 3 concurrent tasks to process the swap requests
  657. let mint_clone1 = mint_bob.clone();
  658. let mint_clone2 = mint_bob.clone();
  659. let mint_clone3 = mint_bob.clone();
  660. let task1 = tokio::spawn(async move { mint_clone1.process_swap_request(swap_request1).await });
  661. let task2 = tokio::spawn(async move { mint_clone2.process_swap_request(swap_request2).await });
  662. let task3 = tokio::spawn(async move { mint_clone3.process_swap_request(swap_request3).await });
  663. // Wait for all tasks to complete
  664. let results = tokio::try_join!(task1, task2, task3).expect("Tasks failed to complete");
  665. // Count successes and failures
  666. let mut success_count = 0;
  667. let mut token_already_spent_count = 0;
  668. for result in [results.0, results.1, results.2] {
  669. match result {
  670. Ok(_) => success_count += 1,
  671. Err(err) => match err {
  672. cdk::Error::TokenAlreadySpent | cdk::Error::TokenPending => {
  673. token_already_spent_count += 1
  674. }
  675. other_err => panic!("Unexpected error: {:?}", other_err),
  676. },
  677. }
  678. }
  679. // Only one swap should succeed, the other two should fail with TokenAlreadySpent
  680. assert_eq!(1, success_count, "Expected exactly one successful swap");
  681. assert_eq!(
  682. 2, token_already_spent_count,
  683. "Expected exactly two TokenAlreadySpent errors"
  684. );
  685. // Verify that all proofs are marked as spent in the mint
  686. let states = mint_bob
  687. .localstore
  688. .get_proofs_states(&proofs.iter().map(|p| p.y().unwrap()).collect::<Vec<_>>())
  689. .await
  690. .expect("Failed to get proof state");
  691. for state in states {
  692. assert_eq!(
  693. State::Spent,
  694. state.expect("Known state"),
  695. "Expected proof to be marked as spent, but got {:?}",
  696. state
  697. );
  698. }
  699. }
  700. /// Tests concurrent double-spending attempts by trying to use the same proofs
  701. /// in 3 melt transactions simultaneously using tokio tasks
  702. #[tokio::test(flavor = "multi_thread", worker_threads = 3)]
  703. async fn test_concurrent_double_spend_melt() {
  704. setup_tracing();
  705. let mint_bob = create_and_start_test_mint()
  706. .await
  707. .expect("Failed to create test mint");
  708. let wallet_alice = create_test_wallet_for_mint(mint_bob.clone())
  709. .await
  710. .expect("Failed to create test wallet");
  711. // Alice gets 100 sats
  712. fund_wallet(wallet_alice.clone(), 100, None)
  713. .await
  714. .expect("Failed to fund wallet");
  715. let proofs = wallet_alice
  716. .get_unspent_proofs()
  717. .await
  718. .expect("Could not get proofs");
  719. // Create a Lightning invoice for the melt
  720. let invoice = create_fake_invoice(1000, "".to_string());
  721. // Create a melt quote
  722. let melt_quote = wallet_alice
  723. .melt_quote(invoice.to_string(), None)
  724. .await
  725. .expect("Failed to create melt quote");
  726. // Get the quote ID and payment request
  727. let quote_id = melt_quote.id.clone();
  728. // Create 3 identical melt requests with the same proofs
  729. let mint_clone1 = mint_bob.clone();
  730. let mint_clone2 = mint_bob.clone();
  731. let mint_clone3 = mint_bob.clone();
  732. let melt_request = MeltBolt11Request::new(quote_id.parse().unwrap(), proofs.clone(), None);
  733. let melt_request2 = melt_request.clone();
  734. let melt_request3 = melt_request.clone();
  735. // Spawn 3 concurrent tasks to process the melt requests
  736. let task1 = tokio::spawn(async move { mint_clone1.melt_bolt11(&melt_request).await });
  737. let task2 = tokio::spawn(async move { mint_clone2.melt_bolt11(&melt_request2).await });
  738. let task3 = tokio::spawn(async move { mint_clone3.melt_bolt11(&melt_request3).await });
  739. // Wait for all tasks to complete
  740. let results = tokio::try_join!(task1, task2, task3).expect("Tasks failed to complete");
  741. // Count successes and failures
  742. let mut success_count = 0;
  743. let mut token_already_spent_count = 0;
  744. for result in [results.0, results.1, results.2] {
  745. match result {
  746. Ok(_) => success_count += 1,
  747. Err(err) => match err {
  748. cdk::Error::TokenAlreadySpent | cdk::Error::TokenPending => {
  749. token_already_spent_count += 1;
  750. println!("Got expected error: {:?}", err);
  751. }
  752. other_err => {
  753. println!("Got unexpected error: {:?}", other_err);
  754. token_already_spent_count += 1;
  755. }
  756. },
  757. }
  758. }
  759. // Only one melt should succeed, the other two should fail
  760. assert_eq!(1, success_count, "Expected exactly one successful melt");
  761. assert_eq!(
  762. 2, token_already_spent_count,
  763. "Expected exactly two TokenAlreadySpent errors"
  764. );
  765. // Verify that all proofs are marked as spent in the mint
  766. let states = mint_bob
  767. .localstore
  768. .get_proofs_states(&proofs.iter().map(|p| p.y().unwrap()).collect::<Vec<_>>())
  769. .await
  770. .expect("Failed to get proof state");
  771. for state in states {
  772. assert_eq!(
  773. State::Spent,
  774. state.expect("Known state"),
  775. "Expected proof to be marked as spent, but got {:?}",
  776. state
  777. );
  778. }
  779. }
  780. async fn get_keyset_id(mint: &Mint) -> Id {
  781. let keys = mint
  782. .pubkeys()
  783. .await
  784. .unwrap()
  785. .keysets
  786. .first()
  787. .unwrap()
  788. .clone()
  789. .keys;
  790. Id::from(&keys)
  791. }