integration_tests_pure.rs 31 KB

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