integration_tests_pure.rs 31 KB

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