fake_wallet.rs 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392
  1. //! Fake Wallet Integration Tests
  2. //!
  3. //! This file contains tests for the fake wallet backend functionality.
  4. //! The fake wallet simulates Lightning Network behavior for testing purposes,
  5. //! allowing verification of mint behavior in various payment scenarios without
  6. //! requiring a real Lightning node.
  7. //!
  8. //! Test Scenarios:
  9. //! - Pending payment states and proof handling
  10. //! - Payment failure cases and proof state management
  11. //! - Change output verification in melt operations
  12. //! - Witness signature validation
  13. //! - Cross-unit transaction validation
  14. //! - Overflow and balance validation
  15. //! - Duplicate proof detection
  16. use std::sync::Arc;
  17. use bip39::Mnemonic;
  18. use cashu::Amount;
  19. use cdk::amount::SplitTarget;
  20. use cdk::nuts::nut00::ProofsMethods;
  21. use cdk::nuts::{
  22. CurrencyUnit, MeltQuoteState, MeltRequest, MintRequest, PreMintSecrets, Proofs, SecretKey,
  23. State, SwapRequest,
  24. };
  25. use cdk::wallet::types::TransactionDirection;
  26. use cdk::wallet::{HttpClient, MintConnector, Wallet};
  27. use cdk::StreamExt;
  28. use cdk_fake_wallet::{create_fake_invoice, FakeInvoiceDescription};
  29. use cdk_sqlite::wallet::memory;
  30. const MINT_URL: &str = "http://127.0.0.1:8086";
  31. /// Tests that when both pay and check return pending status, input proofs should remain pending
  32. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  33. async fn test_fake_tokens_pending() {
  34. let wallet = Wallet::new(
  35. MINT_URL,
  36. CurrencyUnit::Sat,
  37. Arc::new(memory::empty().await.unwrap()),
  38. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  39. None,
  40. )
  41. .expect("failed to create new wallet");
  42. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  43. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  44. let _proofs = proof_streams
  45. .next()
  46. .await
  47. .expect("payment")
  48. .expect("no error");
  49. let fake_description = FakeInvoiceDescription {
  50. pay_invoice_state: MeltQuoteState::Pending,
  51. check_payment_state: MeltQuoteState::Pending,
  52. pay_err: false,
  53. check_err: false,
  54. };
  55. let invoice = create_fake_invoice(1000, serde_json::to_string(&fake_description).unwrap());
  56. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  57. let melt = wallet.melt(&melt_quote.id).await;
  58. assert!(melt.is_err());
  59. assert!(
  60. wallet
  61. .localstore
  62. .get_proofs(None, None, Some(vec![State::Pending]), None)
  63. .await
  64. .expect("no an error")
  65. .is_empty(),
  66. "Database rollback removes all pending proofs"
  67. );
  68. }
  69. /// Tests that if the pay error fails and the check returns unknown or failed,
  70. /// the input proofs should be unset as spending (returned to unspent state)
  71. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  72. async fn test_fake_melt_payment_fail() {
  73. let wallet = Wallet::new(
  74. MINT_URL,
  75. CurrencyUnit::Sat,
  76. Arc::new(memory::empty().await.unwrap()),
  77. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  78. None,
  79. )
  80. .expect("Failed to create new wallet");
  81. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  82. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  83. let _proofs = proof_streams
  84. .next()
  85. .await
  86. .expect("payment")
  87. .expect("no error");
  88. let fake_description = FakeInvoiceDescription {
  89. pay_invoice_state: MeltQuoteState::Unknown,
  90. check_payment_state: MeltQuoteState::Unknown,
  91. pay_err: true,
  92. check_err: false,
  93. };
  94. let invoice = create_fake_invoice(1000, serde_json::to_string(&fake_description).unwrap());
  95. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  96. // The melt should error at the payment invoice command
  97. let melt = wallet.melt(&melt_quote.id).await;
  98. assert!(melt.is_err());
  99. let fake_description = FakeInvoiceDescription {
  100. pay_invoice_state: MeltQuoteState::Failed,
  101. check_payment_state: MeltQuoteState::Failed,
  102. pay_err: true,
  103. check_err: false,
  104. };
  105. let invoice = create_fake_invoice(1000, serde_json::to_string(&fake_description).unwrap());
  106. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  107. // The melt should error at the payment invoice command
  108. let melt = wallet.melt(&melt_quote.id).await;
  109. assert!(melt.is_err());
  110. // The mint should have unset proofs from pending since payment failed
  111. let all_proof = wallet.get_unspent_proofs().await.unwrap();
  112. let states = wallet.check_proofs_spent(all_proof).await.unwrap();
  113. for state in states {
  114. assert!(state.state == State::Unspent);
  115. }
  116. let wallet_bal = wallet.total_balance().await.unwrap();
  117. assert_eq!(wallet_bal, 100.into());
  118. }
  119. /// Tests that when both the pay_invoice and check_invoice both fail,
  120. /// the proofs should remain in pending state
  121. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  122. async fn test_fake_melt_payment_fail_and_check() {
  123. let wallet = Wallet::new(
  124. MINT_URL,
  125. CurrencyUnit::Sat,
  126. Arc::new(memory::empty().await.unwrap()),
  127. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  128. None,
  129. )
  130. .expect("Failed to create new wallet");
  131. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  132. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  133. let _proofs = proof_streams
  134. .next()
  135. .await
  136. .expect("payment")
  137. .expect("no error");
  138. let fake_description = FakeInvoiceDescription {
  139. pay_invoice_state: MeltQuoteState::Unknown,
  140. check_payment_state: MeltQuoteState::Unknown,
  141. pay_err: true,
  142. check_err: true,
  143. };
  144. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  145. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  146. // The melt should error at the payment invoice command
  147. let melt = wallet.melt(&melt_quote.id).await;
  148. assert!(melt.is_err());
  149. assert!(
  150. wallet
  151. .localstore
  152. .get_proofs(None, None, Some(vec![State::Pending]), None)
  153. .await
  154. .expect("no an error")
  155. .is_empty(),
  156. "Database rollback removes all pending proofs"
  157. );
  158. }
  159. /// Tests that when the ln backend returns a failed status but does not error,
  160. /// the mint should do a second check, then remove proofs from pending state
  161. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  162. async fn test_fake_melt_payment_return_fail_status() {
  163. let wallet = Wallet::new(
  164. MINT_URL,
  165. CurrencyUnit::Sat,
  166. Arc::new(memory::empty().await.unwrap()),
  167. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  168. None,
  169. )
  170. .expect("Failed to create new wallet");
  171. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  172. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  173. let _proofs = proof_streams
  174. .next()
  175. .await
  176. .expect("payment")
  177. .expect("no error");
  178. let fake_description = FakeInvoiceDescription {
  179. pay_invoice_state: MeltQuoteState::Failed,
  180. check_payment_state: MeltQuoteState::Failed,
  181. pay_err: false,
  182. check_err: false,
  183. };
  184. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  185. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  186. // The melt should error at the payment invoice command
  187. let melt = wallet.melt(&melt_quote.id).await;
  188. assert!(melt.is_err());
  189. let fake_description = FakeInvoiceDescription {
  190. pay_invoice_state: MeltQuoteState::Unknown,
  191. check_payment_state: MeltQuoteState::Unknown,
  192. pay_err: false,
  193. check_err: false,
  194. };
  195. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  196. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  197. // The melt should error at the payment invoice command
  198. let melt = wallet.melt(&melt_quote.id).await;
  199. assert!(melt.is_err());
  200. let pending = wallet
  201. .localstore
  202. .get_proofs(None, None, Some(vec![State::Pending]), None)
  203. .await
  204. .unwrap();
  205. assert!(pending.is_empty());
  206. }
  207. /// Tests that when the ln backend returns an error with unknown status,
  208. /// the mint should do a second check, then remove proofs from pending state
  209. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  210. async fn test_fake_melt_payment_error_unknown() {
  211. let wallet = Wallet::new(
  212. MINT_URL,
  213. CurrencyUnit::Sat,
  214. Arc::new(memory::empty().await.unwrap()),
  215. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  216. None,
  217. )
  218. .unwrap();
  219. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  220. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  221. let _proofs = proof_streams
  222. .next()
  223. .await
  224. .expect("payment")
  225. .expect("no error");
  226. let fake_description = FakeInvoiceDescription {
  227. pay_invoice_state: MeltQuoteState::Failed,
  228. check_payment_state: MeltQuoteState::Unknown,
  229. pay_err: true,
  230. check_err: false,
  231. };
  232. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  233. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  234. // The melt should error at the payment invoice command
  235. let melt = wallet.melt(&melt_quote.id).await;
  236. assert_eq!(melt.unwrap_err().to_string(), "Payment failed");
  237. let fake_description = FakeInvoiceDescription {
  238. pay_invoice_state: MeltQuoteState::Unknown,
  239. check_payment_state: MeltQuoteState::Unknown,
  240. pay_err: true,
  241. check_err: false,
  242. };
  243. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  244. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  245. // The melt should error at the payment invoice command
  246. let melt = wallet.melt(&melt_quote.id).await;
  247. assert_eq!(melt.unwrap_err().to_string(), "Payment failed");
  248. let pending = wallet
  249. .localstore
  250. .get_proofs(None, None, Some(vec![State::Pending]), None)
  251. .await
  252. .unwrap();
  253. assert!(pending.is_empty());
  254. }
  255. /// Tests that when the ln backend returns an error but the second check returns paid,
  256. /// proofs should remain in pending state
  257. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  258. async fn test_fake_melt_payment_err_paid() {
  259. let wallet = Wallet::new(
  260. MINT_URL,
  261. CurrencyUnit::Sat,
  262. Arc::new(memory::empty().await.unwrap()),
  263. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  264. None,
  265. )
  266. .expect("Failed to create new wallet");
  267. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  268. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  269. let _proofs = proof_streams
  270. .next()
  271. .await
  272. .expect("payment")
  273. .expect("no error");
  274. let fake_description = FakeInvoiceDescription {
  275. pay_invoice_state: MeltQuoteState::Failed,
  276. check_payment_state: MeltQuoteState::Paid,
  277. pay_err: true,
  278. check_err: false,
  279. };
  280. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  281. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  282. // The melt should error at the payment invoice command
  283. let melt = wallet.melt(&melt_quote.id).await;
  284. assert!(melt.is_err());
  285. assert!(
  286. wallet
  287. .localstore
  288. .get_proofs(None, None, Some(vec![State::Pending]), None)
  289. .await
  290. .expect("no an error")
  291. .is_empty(),
  292. "Database rollback removes all pending proofs"
  293. );
  294. }
  295. /// Tests that change outputs in a melt quote are correctly handled
  296. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  297. async fn test_fake_melt_change_in_quote() {
  298. let wallet = Wallet::new(
  299. MINT_URL,
  300. CurrencyUnit::Sat,
  301. Arc::new(memory::empty().await.unwrap()),
  302. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  303. None,
  304. )
  305. .expect("Failed to create new wallet");
  306. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  307. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  308. let _proofs = proof_streams
  309. .next()
  310. .await
  311. .expect("payment")
  312. .expect("no error");
  313. let transaction = wallet
  314. .list_transactions(Some(TransactionDirection::Incoming))
  315. .await
  316. .unwrap()
  317. .pop()
  318. .expect("No transaction found");
  319. assert_eq!(wallet.mint_url, transaction.mint_url);
  320. assert_eq!(TransactionDirection::Incoming, transaction.direction);
  321. assert_eq!(Amount::from(100), transaction.amount);
  322. assert_eq!(Amount::from(0), transaction.fee);
  323. assert_eq!(CurrencyUnit::Sat, transaction.unit);
  324. let fake_description = FakeInvoiceDescription::default();
  325. let invoice = create_fake_invoice(9000, serde_json::to_string(&fake_description).unwrap());
  326. let proofs = wallet.get_unspent_proofs().await.unwrap();
  327. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  328. let keyset = wallet.fetch_active_keyset().await.unwrap();
  329. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  330. let premint_secrets = PreMintSecrets::random(
  331. keyset.id,
  332. 100.into(),
  333. &SplitTarget::default(),
  334. &fee_and_amounts,
  335. )
  336. .unwrap();
  337. let client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  338. let melt_request = MeltRequest::new(
  339. melt_quote.id.clone(),
  340. proofs.clone(),
  341. Some(premint_secrets.blinded_messages()),
  342. );
  343. let melt_response = client.post_melt(melt_request).await.unwrap();
  344. assert!(melt_response.change.is_some());
  345. let check = wallet.melt_quote_status(&melt_quote.id).await.unwrap();
  346. let mut melt_change = melt_response.change.unwrap();
  347. melt_change.sort_by(|a, b| a.amount.cmp(&b.amount));
  348. let mut check = check.change.unwrap();
  349. check.sort_by(|a, b| a.amount.cmp(&b.amount));
  350. assert_eq!(melt_change, check);
  351. }
  352. /// Tests minting tokens with a valid witness signature
  353. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  354. async fn test_fake_mint_with_witness() {
  355. let wallet = Wallet::new(
  356. MINT_URL,
  357. CurrencyUnit::Sat,
  358. Arc::new(memory::empty().await.unwrap()),
  359. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  360. None,
  361. )
  362. .expect("failed to create new wallet");
  363. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  364. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  365. let proofs = proof_streams
  366. .next()
  367. .await
  368. .expect("payment")
  369. .expect("no error");
  370. let mint_amount = proofs.total_amount().unwrap();
  371. assert!(mint_amount == 100.into());
  372. }
  373. /// Tests that minting without a witness signature fails with the correct error
  374. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  375. async fn test_fake_mint_without_witness() {
  376. let wallet = Wallet::new(
  377. MINT_URL,
  378. CurrencyUnit::Sat,
  379. Arc::new(memory::empty().await.unwrap()),
  380. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  381. None,
  382. )
  383. .expect("failed to create new wallet");
  384. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  385. let mut payment_streams = wallet.payment_stream(&mint_quote);
  386. payment_streams
  387. .next()
  388. .await
  389. .expect("payment")
  390. .expect("no error");
  391. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  392. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  393. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  394. let premint_secrets = PreMintSecrets::random(
  395. active_keyset_id,
  396. 100.into(),
  397. &SplitTarget::default(),
  398. &fee_and_amounts,
  399. )
  400. .unwrap();
  401. let request = MintRequest {
  402. quote: mint_quote.id,
  403. outputs: premint_secrets.blinded_messages(),
  404. signature: None,
  405. };
  406. let response = http_client.post_mint(request.clone()).await;
  407. match response {
  408. Err(cdk::error::Error::SignatureMissingOrInvalid) => {} //pass
  409. Err(err) => panic!("Wrong mint response for minting without witness: {}", err),
  410. Ok(_) => panic!("Minting should not have succeed without a witness"),
  411. }
  412. }
  413. /// Tests that minting with an incorrect witness signature fails with the correct error
  414. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  415. async fn test_fake_mint_with_wrong_witness() {
  416. let wallet = Wallet::new(
  417. MINT_URL,
  418. CurrencyUnit::Sat,
  419. Arc::new(memory::empty().await.unwrap()),
  420. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  421. None,
  422. )
  423. .expect("failed to create new wallet");
  424. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  425. let mut payment_streams = wallet.payment_stream(&mint_quote);
  426. payment_streams
  427. .next()
  428. .await
  429. .expect("payment")
  430. .expect("no error");
  431. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  432. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  433. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  434. let premint_secrets = PreMintSecrets::random(
  435. active_keyset_id,
  436. 100.into(),
  437. &SplitTarget::default(),
  438. &fee_and_amounts,
  439. )
  440. .unwrap();
  441. let mut request = MintRequest {
  442. quote: mint_quote.id,
  443. outputs: premint_secrets.blinded_messages(),
  444. signature: None,
  445. };
  446. let secret_key = SecretKey::generate();
  447. request
  448. .sign(secret_key)
  449. .expect("failed to sign the mint request");
  450. let response = http_client.post_mint(request.clone()).await;
  451. match response {
  452. Err(cdk::error::Error::SignatureMissingOrInvalid) => {} //pass
  453. Err(err) => panic!("Wrong mint response for minting without witness: {}", err),
  454. Ok(_) => panic!("Minting should not have succeed without a witness"),
  455. }
  456. }
  457. /// Tests that attempting to mint more tokens than allowed by the quote fails
  458. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  459. async fn test_fake_mint_inflated() {
  460. let wallet = Wallet::new(
  461. MINT_URL,
  462. CurrencyUnit::Sat,
  463. Arc::new(memory::empty().await.unwrap()),
  464. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  465. None,
  466. )
  467. .expect("failed to create new wallet");
  468. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  469. let mut payment_streams = wallet.payment_stream(&mint_quote);
  470. payment_streams
  471. .next()
  472. .await
  473. .expect("payment")
  474. .expect("no error");
  475. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  476. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  477. let pre_mint = PreMintSecrets::random(
  478. active_keyset_id,
  479. 500.into(),
  480. &SplitTarget::None,
  481. &fee_and_amounts,
  482. )
  483. .unwrap();
  484. let quote_info = wallet
  485. .localstore
  486. .get_mint_quote(&mint_quote.id)
  487. .await
  488. .unwrap()
  489. .expect("there is a quote");
  490. let mut mint_request = MintRequest {
  491. quote: mint_quote.id,
  492. outputs: pre_mint.blinded_messages(),
  493. signature: None,
  494. };
  495. if let Some(secret_key) = quote_info.secret_key {
  496. mint_request
  497. .sign(secret_key)
  498. .expect("failed to sign the mint request");
  499. }
  500. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  501. let response = http_client.post_mint(mint_request.clone()).await;
  502. match response {
  503. Err(err) => match err {
  504. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  505. err => {
  506. panic!("Wrong mint error returned: {}", err);
  507. }
  508. },
  509. Ok(_) => {
  510. panic!("Should not have allowed second payment");
  511. }
  512. }
  513. }
  514. /// Tests that attempting to mint with multiple currency units in the same request fails
  515. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  516. async fn test_fake_mint_multiple_units() {
  517. let wallet = Wallet::new(
  518. MINT_URL,
  519. CurrencyUnit::Sat,
  520. Arc::new(memory::empty().await.unwrap()),
  521. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  522. None,
  523. )
  524. .expect("failed to create new wallet");
  525. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  526. let mut payment_streams = wallet.payment_stream(&mint_quote);
  527. payment_streams
  528. .next()
  529. .await
  530. .expect("payment")
  531. .expect("no error");
  532. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  533. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  534. let pre_mint = PreMintSecrets::random(
  535. active_keyset_id,
  536. 50.into(),
  537. &SplitTarget::None,
  538. &fee_and_amounts,
  539. )
  540. .unwrap();
  541. let wallet_usd = Wallet::new(
  542. MINT_URL,
  543. CurrencyUnit::Usd,
  544. Arc::new(memory::empty().await.unwrap()),
  545. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  546. None,
  547. )
  548. .expect("failed to create new wallet");
  549. let active_keyset_id = wallet_usd.fetch_active_keyset().await.unwrap().id;
  550. let usd_pre_mint = PreMintSecrets::random(
  551. active_keyset_id,
  552. 50.into(),
  553. &SplitTarget::None,
  554. &fee_and_amounts,
  555. )
  556. .unwrap();
  557. let quote_info = wallet
  558. .localstore
  559. .get_mint_quote(&mint_quote.id)
  560. .await
  561. .unwrap()
  562. .expect("there is a quote");
  563. let mut sat_outputs = pre_mint.blinded_messages();
  564. let mut usd_outputs = usd_pre_mint.blinded_messages();
  565. sat_outputs.append(&mut usd_outputs);
  566. let mut mint_request = MintRequest {
  567. quote: mint_quote.id,
  568. outputs: sat_outputs,
  569. signature: None,
  570. };
  571. if let Some(secret_key) = quote_info.secret_key {
  572. mint_request
  573. .sign(secret_key)
  574. .expect("failed to sign the mint request");
  575. }
  576. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  577. let response = http_client.post_mint(mint_request.clone()).await;
  578. match response {
  579. Err(err) => match err {
  580. cdk::Error::MultipleUnits => (),
  581. err => {
  582. panic!("Wrong mint error returned: {}", err);
  583. }
  584. },
  585. Ok(_) => {
  586. panic!("Should not have allowed to mint with multiple units");
  587. }
  588. }
  589. }
  590. /// Tests that attempting to swap tokens with multiple currency units fails
  591. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  592. async fn test_fake_mint_multiple_unit_swap() {
  593. let wallet = Wallet::new(
  594. MINT_URL,
  595. CurrencyUnit::Sat,
  596. Arc::new(memory::empty().await.unwrap()),
  597. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  598. None,
  599. )
  600. .expect("failed to create new wallet");
  601. wallet.refresh_keysets().await.unwrap();
  602. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  603. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  604. let proofs = proof_streams
  605. .next()
  606. .await
  607. .expect("payment")
  608. .expect("no error");
  609. let wallet_usd = Wallet::new(
  610. MINT_URL,
  611. CurrencyUnit::Usd,
  612. Arc::new(memory::empty().await.unwrap()),
  613. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  614. None,
  615. )
  616. .expect("failed to create usd wallet");
  617. wallet_usd.refresh_keysets().await.unwrap();
  618. let mint_quote = wallet_usd.mint_quote(100.into(), None).await.unwrap();
  619. let mut proof_streams =
  620. wallet_usd.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  621. let usd_proofs = proof_streams
  622. .next()
  623. .await
  624. .expect("payment")
  625. .expect("no error");
  626. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  627. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  628. {
  629. let inputs: Proofs = vec![
  630. proofs.first().expect("There is a proof").clone(),
  631. usd_proofs.first().expect("There is a proof").clone(),
  632. ];
  633. let pre_mint = PreMintSecrets::random(
  634. active_keyset_id,
  635. inputs.total_amount().unwrap(),
  636. &SplitTarget::None,
  637. &fee_and_amounts,
  638. )
  639. .unwrap();
  640. let swap_request = SwapRequest::new(inputs, pre_mint.blinded_messages());
  641. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  642. let response = http_client.post_swap(swap_request.clone()).await;
  643. match response {
  644. Err(err) => match err {
  645. cdk::Error::MultipleUnits => (),
  646. err => {
  647. panic!("Wrong mint error returned: {}", err);
  648. }
  649. },
  650. Ok(_) => {
  651. panic!("Should not have allowed to mint with multiple units");
  652. }
  653. }
  654. }
  655. {
  656. let usd_active_keyset_id = wallet_usd.fetch_active_keyset().await.unwrap().id;
  657. let inputs: Proofs = proofs.into_iter().take(2).collect();
  658. let total_inputs = inputs.total_amount().unwrap();
  659. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  660. let half = total_inputs / 2.into();
  661. let usd_pre_mint = PreMintSecrets::random(
  662. usd_active_keyset_id,
  663. half,
  664. &SplitTarget::None,
  665. &fee_and_amounts,
  666. )
  667. .unwrap();
  668. let pre_mint = PreMintSecrets::random(
  669. active_keyset_id,
  670. total_inputs - half,
  671. &SplitTarget::None,
  672. &fee_and_amounts,
  673. )
  674. .unwrap();
  675. let mut usd_outputs = usd_pre_mint.blinded_messages();
  676. let mut sat_outputs = pre_mint.blinded_messages();
  677. usd_outputs.append(&mut sat_outputs);
  678. let swap_request = SwapRequest::new(inputs, usd_outputs);
  679. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  680. let response = http_client.post_swap(swap_request.clone()).await;
  681. match response {
  682. Err(err) => match err {
  683. cdk::Error::MultipleUnits => (),
  684. err => {
  685. panic!("Wrong mint error returned: {}", err);
  686. }
  687. },
  688. Ok(_) => {
  689. panic!("Should not have allowed to mint with multiple units");
  690. }
  691. }
  692. }
  693. }
  694. /// Tests that attempting to melt tokens with multiple currency units fails
  695. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  696. async fn test_fake_mint_multiple_unit_melt() {
  697. let wallet = Wallet::new(
  698. MINT_URL,
  699. CurrencyUnit::Sat,
  700. Arc::new(memory::empty().await.unwrap()),
  701. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  702. None,
  703. )
  704. .expect("failed to create new wallet");
  705. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  706. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  707. let proofs = proof_streams
  708. .next()
  709. .await
  710. .expect("payment")
  711. .expect("no error");
  712. println!("Minted sat");
  713. let wallet_usd = Wallet::new(
  714. MINT_URL,
  715. CurrencyUnit::Usd,
  716. Arc::new(memory::empty().await.unwrap()),
  717. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  718. None,
  719. )
  720. .expect("failed to create new wallet");
  721. let mint_quote = wallet_usd.mint_quote(100.into(), None).await.unwrap();
  722. println!("Minted quote usd");
  723. let mut proof_streams =
  724. wallet_usd.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  725. let usd_proofs = proof_streams
  726. .next()
  727. .await
  728. .expect("payment")
  729. .expect("no error");
  730. {
  731. let inputs: Proofs = vec![
  732. proofs.first().expect("There is a proof").clone(),
  733. usd_proofs.first().expect("There is a proof").clone(),
  734. ];
  735. let input_amount: u64 = inputs.total_amount().unwrap().into();
  736. let invoice = create_fake_invoice((input_amount - 1) * 1000, "".to_string());
  737. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  738. let melt_request = MeltRequest::new(melt_quote.id, inputs, None);
  739. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  740. let response = http_client.post_melt(melt_request.clone()).await;
  741. match response {
  742. Err(err) => match err {
  743. cdk::Error::MultipleUnits => (),
  744. err => {
  745. panic!("Wrong mint error returned: {}", err);
  746. }
  747. },
  748. Ok(_) => {
  749. panic!("Should not have allowed to melt with multiple units");
  750. }
  751. }
  752. }
  753. {
  754. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  755. let inputs: Proofs = vec![proofs.first().expect("There is a proof").clone()];
  756. let input_amount: u64 = inputs.total_amount().unwrap().into();
  757. let invoice = create_fake_invoice((input_amount - 1) * 1000, "".to_string());
  758. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  759. let usd_active_keyset_id = wallet_usd.fetch_active_keyset().await.unwrap().id;
  760. let usd_pre_mint = PreMintSecrets::random(
  761. usd_active_keyset_id,
  762. inputs.total_amount().unwrap() + 100.into(),
  763. &SplitTarget::None,
  764. &fee_and_amounts,
  765. )
  766. .unwrap();
  767. let pre_mint = PreMintSecrets::random(
  768. active_keyset_id,
  769. 100.into(),
  770. &SplitTarget::None,
  771. &fee_and_amounts,
  772. )
  773. .unwrap();
  774. let mut usd_outputs = usd_pre_mint.blinded_messages();
  775. let mut sat_outputs = pre_mint.blinded_messages();
  776. usd_outputs.append(&mut sat_outputs);
  777. let quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  778. let melt_request = MeltRequest::new(quote.id, inputs, Some(usd_outputs));
  779. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  780. let response = http_client.post_melt(melt_request.clone()).await;
  781. match response {
  782. Err(err) => match err {
  783. cdk::Error::MultipleUnits => (),
  784. err => {
  785. panic!("Wrong mint error returned: {}", err);
  786. }
  787. },
  788. Ok(_) => {
  789. panic!("Should not have allowed to melt with multiple units");
  790. }
  791. }
  792. }
  793. }
  794. /// Tests that swapping tokens where input unit doesn't match output unit fails
  795. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  796. async fn test_fake_mint_input_output_mismatch() {
  797. let wallet = Wallet::new(
  798. MINT_URL,
  799. CurrencyUnit::Sat,
  800. Arc::new(memory::empty().await.unwrap()),
  801. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  802. None,
  803. )
  804. .expect("failed to create new wallet");
  805. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  806. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  807. let proofs = proof_streams
  808. .next()
  809. .await
  810. .expect("payment")
  811. .expect("no error");
  812. let wallet_usd = Wallet::new(
  813. MINT_URL,
  814. CurrencyUnit::Usd,
  815. Arc::new(memory::empty().await.unwrap()),
  816. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  817. None,
  818. )
  819. .expect("failed to create new usd wallet");
  820. let usd_active_keyset_id = wallet_usd.fetch_active_keyset().await.unwrap().id;
  821. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  822. let inputs = proofs;
  823. let pre_mint = PreMintSecrets::random(
  824. usd_active_keyset_id,
  825. inputs.total_amount().unwrap(),
  826. &SplitTarget::None,
  827. &fee_and_amounts,
  828. )
  829. .unwrap();
  830. let swap_request = SwapRequest::new(inputs, pre_mint.blinded_messages());
  831. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  832. let response = http_client.post_swap(swap_request.clone()).await;
  833. match response {
  834. Err(err) => match err {
  835. cdk::Error::UnitMismatch => (),
  836. err => panic!("Wrong error returned: {}", err),
  837. },
  838. Ok(_) => {
  839. panic!("Should not have allowed to mint with multiple units");
  840. }
  841. }
  842. }
  843. /// Tests that swapping tokens where output amount is greater than input amount fails
  844. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  845. async fn test_fake_mint_swap_inflated() {
  846. let wallet = Wallet::new(
  847. MINT_URL,
  848. CurrencyUnit::Sat,
  849. Arc::new(memory::empty().await.unwrap()),
  850. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  851. None,
  852. )
  853. .expect("failed to create new wallet");
  854. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  855. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  856. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  857. let proofs = proof_streams
  858. .next()
  859. .await
  860. .expect("payment")
  861. .expect("no error");
  862. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  863. let pre_mint = PreMintSecrets::random(
  864. active_keyset_id,
  865. 101.into(),
  866. &SplitTarget::None,
  867. &fee_and_amounts,
  868. )
  869. .unwrap();
  870. let swap_request = SwapRequest::new(proofs, pre_mint.blinded_messages());
  871. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  872. let response = http_client.post_swap(swap_request.clone()).await;
  873. match response {
  874. Err(err) => match err {
  875. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  876. err => {
  877. panic!("Wrong mint error returned: {}", err);
  878. }
  879. },
  880. Ok(_) => {
  881. panic!("Should not have allowed to mint with multiple units");
  882. }
  883. }
  884. }
  885. /// Tests that tokens cannot be spent again after a failed swap attempt
  886. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  887. async fn test_fake_mint_swap_spend_after_fail() {
  888. let wallet = Wallet::new(
  889. MINT_URL,
  890. CurrencyUnit::Sat,
  891. Arc::new(memory::empty().await.unwrap()),
  892. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  893. None,
  894. )
  895. .expect("failed to create new wallet");
  896. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  897. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  898. let proofs = proof_streams
  899. .next()
  900. .await
  901. .expect("payment")
  902. .expect("no error");
  903. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  904. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  905. let pre_mint = PreMintSecrets::random(
  906. active_keyset_id,
  907. 100.into(),
  908. &SplitTarget::None,
  909. &fee_and_amounts,
  910. )
  911. .unwrap();
  912. let swap_request = SwapRequest::new(proofs.clone(), pre_mint.blinded_messages());
  913. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  914. let response = http_client.post_swap(swap_request.clone()).await;
  915. assert!(response.is_ok());
  916. let pre_mint = PreMintSecrets::random(
  917. active_keyset_id,
  918. 101.into(),
  919. &SplitTarget::None,
  920. &fee_and_amounts,
  921. )
  922. .unwrap();
  923. let swap_request = SwapRequest::new(proofs.clone(), pre_mint.blinded_messages());
  924. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  925. let response = http_client.post_swap(swap_request.clone()).await;
  926. match response {
  927. Err(err) => match err {
  928. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  929. err => panic!("Wrong mint error returned expected TransactionUnbalanced, got: {err}"),
  930. },
  931. Ok(_) => panic!("Should not have allowed swap with unbalanced"),
  932. }
  933. let pre_mint = PreMintSecrets::random(
  934. active_keyset_id,
  935. 100.into(),
  936. &SplitTarget::None,
  937. &fee_and_amounts,
  938. )
  939. .unwrap();
  940. let swap_request = SwapRequest::new(proofs, pre_mint.blinded_messages());
  941. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  942. let response = http_client.post_swap(swap_request.clone()).await;
  943. match response {
  944. Err(err) => match err {
  945. cdk::Error::TokenAlreadySpent => (),
  946. err => {
  947. panic!("Wrong mint error returned: {}", err);
  948. }
  949. },
  950. Ok(_) => {
  951. panic!("Should not have allowed to mint with multiple units");
  952. }
  953. }
  954. }
  955. /// Tests that tokens cannot be melted after a failed swap attempt
  956. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  957. async fn test_fake_mint_melt_spend_after_fail() {
  958. let wallet = Wallet::new(
  959. MINT_URL,
  960. CurrencyUnit::Sat,
  961. Arc::new(memory::empty().await.unwrap()),
  962. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  963. None,
  964. )
  965. .expect("failed to create new wallet");
  966. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  967. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  968. let proofs = proof_streams
  969. .next()
  970. .await
  971. .expect("payment")
  972. .expect("no error");
  973. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  974. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  975. let pre_mint = PreMintSecrets::random(
  976. active_keyset_id,
  977. 100.into(),
  978. &SplitTarget::None,
  979. &fee_and_amounts,
  980. )
  981. .unwrap();
  982. let swap_request = SwapRequest::new(proofs.clone(), pre_mint.blinded_messages());
  983. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  984. let response = http_client.post_swap(swap_request.clone()).await;
  985. assert!(response.is_ok());
  986. let pre_mint = PreMintSecrets::random(
  987. active_keyset_id,
  988. 101.into(),
  989. &SplitTarget::None,
  990. &fee_and_amounts,
  991. )
  992. .unwrap();
  993. let swap_request = SwapRequest::new(proofs.clone(), pre_mint.blinded_messages());
  994. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  995. let response = http_client.post_swap(swap_request.clone()).await;
  996. match response {
  997. Err(err) => match err {
  998. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  999. err => panic!("Wrong mint error returned expected TransactionUnbalanced, got: {err}"),
  1000. },
  1001. Ok(_) => panic!("Should not have allowed swap with unbalanced"),
  1002. }
  1003. let input_amount: u64 = proofs.total_amount().unwrap().into();
  1004. let invoice = create_fake_invoice((input_amount - 1) * 1000, "".to_string());
  1005. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  1006. let melt_request = MeltRequest::new(melt_quote.id, proofs, None);
  1007. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1008. let response = http_client.post_melt(melt_request.clone()).await;
  1009. match response {
  1010. Err(err) => match err {
  1011. cdk::Error::TokenAlreadySpent => (),
  1012. err => {
  1013. panic!("Wrong mint error returned: {}", err);
  1014. }
  1015. },
  1016. Ok(_) => {
  1017. panic!("Should not have allowed to melt with multiple units");
  1018. }
  1019. }
  1020. }
  1021. /// Tests that attempting to swap with duplicate proofs fails
  1022. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1023. async fn test_fake_mint_duplicate_proofs_swap() {
  1024. let wallet = Wallet::new(
  1025. MINT_URL,
  1026. CurrencyUnit::Sat,
  1027. Arc::new(memory::empty().await.unwrap()),
  1028. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1029. None,
  1030. )
  1031. .expect("failed to create new wallet");
  1032. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  1033. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1034. let proofs = proof_streams
  1035. .next()
  1036. .await
  1037. .expect("payment")
  1038. .expect("no error");
  1039. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  1040. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  1041. let inputs = vec![proofs[0].clone(), proofs[0].clone()];
  1042. let pre_mint = PreMintSecrets::random(
  1043. active_keyset_id,
  1044. inputs.total_amount().unwrap(),
  1045. &SplitTarget::None,
  1046. &fee_and_amounts,
  1047. )
  1048. .unwrap();
  1049. let swap_request = SwapRequest::new(inputs.clone(), pre_mint.blinded_messages());
  1050. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1051. let response = http_client.post_swap(swap_request.clone()).await;
  1052. match response {
  1053. Err(err) => match err {
  1054. cdk::Error::DuplicateInputs => (),
  1055. err => {
  1056. panic!(
  1057. "Wrong mint error returned, expected duplicate inputs: {}",
  1058. err
  1059. );
  1060. }
  1061. },
  1062. Ok(_) => {
  1063. panic!("Should not have allowed duplicate inputs");
  1064. }
  1065. }
  1066. let blinded_message = pre_mint.blinded_messages();
  1067. let inputs = vec![proofs[0].clone()];
  1068. let outputs = vec![blinded_message[0].clone(), blinded_message[0].clone()];
  1069. let swap_request = SwapRequest::new(inputs, outputs);
  1070. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1071. let response = http_client.post_swap(swap_request.clone()).await;
  1072. match response {
  1073. Err(err) => match err {
  1074. cdk::Error::DuplicateOutputs => (),
  1075. err => {
  1076. panic!(
  1077. "Wrong mint error returned, expected duplicate outputs: {}",
  1078. err
  1079. );
  1080. }
  1081. },
  1082. Ok(_) => {
  1083. panic!("Should not have allow duplicate inputs");
  1084. }
  1085. }
  1086. }
  1087. /// Tests that attempting to melt with duplicate proofs fails
  1088. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1089. async fn test_fake_mint_duplicate_proofs_melt() {
  1090. let wallet = Wallet::new(
  1091. MINT_URL,
  1092. CurrencyUnit::Sat,
  1093. Arc::new(memory::empty().await.unwrap()),
  1094. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1095. None,
  1096. )
  1097. .expect("failed to create new wallet");
  1098. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  1099. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1100. let proofs = proof_streams
  1101. .next()
  1102. .await
  1103. .expect("payment")
  1104. .expect("no error");
  1105. let inputs = vec![proofs[0].clone(), proofs[0].clone()];
  1106. let invoice = create_fake_invoice(7000, "".to_string());
  1107. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  1108. let melt_request = MeltRequest::new(melt_quote.id, inputs, None);
  1109. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1110. let response = http_client.post_melt(melt_request.clone()).await;
  1111. match response {
  1112. Err(err) => match err {
  1113. cdk::Error::DuplicateInputs => (),
  1114. err => {
  1115. panic!("Wrong mint error returned: {}", err);
  1116. }
  1117. },
  1118. Ok(_) => {
  1119. panic!("Should not have allow duplicate inputs");
  1120. }
  1121. }
  1122. }