fake_wallet.rs 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736
  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 std::time::Duration;
  18. use bip39::Mnemonic;
  19. use cashu::Amount;
  20. use cdk::amount::SplitTarget;
  21. use cdk::nuts::nut00::ProofsMethods;
  22. use cdk::nuts::{
  23. CurrencyUnit, MeltQuoteState, MeltRequest, MintRequest, PreMintSecrets, Proofs, SecretKey,
  24. State, SwapRequest,
  25. };
  26. use cdk::wallet::types::TransactionDirection;
  27. use cdk::wallet::{HttpClient, MintConnector, Wallet};
  28. use cdk::StreamExt;
  29. use cdk_fake_wallet::{create_fake_invoice, FakeInvoiceDescription};
  30. use cdk_sqlite::wallet::memory;
  31. const MINT_URL: &str = "http://127.0.0.1:8086";
  32. /// Tests that when both pay and check return pending status, input proofs should remain pending
  33. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  34. async fn test_fake_tokens_pending() {
  35. let wallet = Wallet::new(
  36. MINT_URL,
  37. CurrencyUnit::Sat,
  38. Arc::new(memory::empty().await.unwrap()),
  39. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  40. None,
  41. )
  42. .expect("failed to create new wallet");
  43. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  44. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  45. let _proofs = proof_streams
  46. .next()
  47. .await
  48. .expect("payment")
  49. .expect("no error");
  50. let fake_description = FakeInvoiceDescription {
  51. pay_invoice_state: MeltQuoteState::Pending,
  52. check_payment_state: MeltQuoteState::Pending,
  53. pay_err: false,
  54. check_err: false,
  55. };
  56. let invoice = create_fake_invoice(1000, serde_json::to_string(&fake_description).unwrap());
  57. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  58. let melt = wallet.melt(&melt_quote.id).await;
  59. assert!(melt.is_err());
  60. // melt failed, but there is new code to reclaim unspent proofs
  61. assert!(!wallet
  62. .localstore
  63. .get_proofs(None, None, Some(vec![State::Pending]), None)
  64. .await
  65. .unwrap()
  66. .is_empty());
  67. }
  68. /// Tests that if the pay error fails and the check returns unknown or failed,
  69. /// the input proofs should be unset as spending (returned to unspent state)
  70. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  71. async fn test_fake_melt_payment_fail() {
  72. let wallet = Wallet::new(
  73. MINT_URL,
  74. CurrencyUnit::Sat,
  75. Arc::new(memory::empty().await.unwrap()),
  76. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  77. None,
  78. )
  79. .expect("Failed to create new wallet");
  80. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  81. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  82. let _proofs = proof_streams
  83. .next()
  84. .await
  85. .expect("payment")
  86. .expect("no error");
  87. let fake_description = FakeInvoiceDescription {
  88. pay_invoice_state: MeltQuoteState::Unknown,
  89. check_payment_state: MeltQuoteState::Unknown,
  90. pay_err: true,
  91. check_err: false,
  92. };
  93. let invoice = create_fake_invoice(1000, serde_json::to_string(&fake_description).unwrap());
  94. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  95. // The melt should error at the payment invoice command
  96. let melt = wallet.melt(&melt_quote.id).await;
  97. assert!(melt.is_err());
  98. let fake_description = FakeInvoiceDescription {
  99. pay_invoice_state: MeltQuoteState::Failed,
  100. check_payment_state: MeltQuoteState::Failed,
  101. pay_err: true,
  102. check_err: false,
  103. };
  104. let invoice = create_fake_invoice(1000, serde_json::to_string(&fake_description).unwrap());
  105. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  106. // The melt should error at the payment invoice command
  107. let melt = wallet.melt(&melt_quote.id).await;
  108. assert!(melt.is_err());
  109. let wallet_bal = wallet.total_balance().await.unwrap();
  110. assert_eq!(wallet_bal, 98.into());
  111. }
  112. /// Tests that when both the pay_invoice and check_invoice both fail,
  113. /// the proofs should remain in pending state
  114. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  115. async fn test_fake_melt_payment_fail_and_check() {
  116. let wallet = Wallet::new(
  117. MINT_URL,
  118. CurrencyUnit::Sat,
  119. Arc::new(memory::empty().await.unwrap()),
  120. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  121. None,
  122. )
  123. .expect("Failed to create new wallet");
  124. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  125. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  126. let _proofs = proof_streams
  127. .next()
  128. .await
  129. .expect("payment")
  130. .expect("no error");
  131. let fake_description = FakeInvoiceDescription {
  132. pay_invoice_state: MeltQuoteState::Unknown,
  133. check_payment_state: MeltQuoteState::Unknown,
  134. pay_err: true,
  135. check_err: true,
  136. };
  137. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  138. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  139. // The melt should error at the payment invoice command
  140. let melt = wallet.melt(&melt_quote.id).await;
  141. assert!(melt.is_err());
  142. assert!(!wallet
  143. .localstore
  144. .get_proofs(None, None, Some(vec![State::Pending]), None)
  145. .await
  146. .unwrap()
  147. .is_empty());
  148. }
  149. /// Tests that when the ln backend returns a failed status but does not error,
  150. /// the mint should do a second check, then remove proofs from pending state
  151. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  152. async fn test_fake_melt_payment_return_fail_status() {
  153. let wallet = Wallet::new(
  154. MINT_URL,
  155. CurrencyUnit::Sat,
  156. Arc::new(memory::empty().await.unwrap()),
  157. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  158. None,
  159. )
  160. .expect("Failed to create new wallet");
  161. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  162. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  163. let _proofs = proof_streams
  164. .next()
  165. .await
  166. .expect("payment")
  167. .expect("no error");
  168. let fake_description = FakeInvoiceDescription {
  169. pay_invoice_state: MeltQuoteState::Failed,
  170. check_payment_state: MeltQuoteState::Failed,
  171. pay_err: false,
  172. check_err: false,
  173. };
  174. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  175. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  176. // The melt should error at the payment invoice command
  177. let melt = wallet.melt(&melt_quote.id).await;
  178. assert!(melt.is_err());
  179. wallet.check_all_pending_proofs().await.unwrap();
  180. let pending = wallet
  181. .localstore
  182. .get_proofs(None, None, Some(vec![State::Pending]), None)
  183. .await
  184. .unwrap();
  185. assert!(pending.is_empty());
  186. let fake_description = FakeInvoiceDescription {
  187. pay_invoice_state: MeltQuoteState::Unknown,
  188. check_payment_state: MeltQuoteState::Unknown,
  189. pay_err: false,
  190. check_err: false,
  191. };
  192. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  193. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  194. // The melt should error at the payment invoice command
  195. let melt = wallet.melt(&melt_quote.id).await;
  196. assert!(melt.is_err());
  197. wallet.check_all_pending_proofs().await.unwrap();
  198. assert!(!wallet
  199. .localstore
  200. .get_proofs(None, None, Some(vec![State::Pending]), None)
  201. .await
  202. .unwrap()
  203. .is_empty());
  204. }
  205. /// Tests that when the ln backend returns an error with unknown status,
  206. /// the mint should do a second check, then remove proofs from pending state
  207. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  208. async fn test_fake_melt_payment_error_unknown() {
  209. let wallet = Wallet::new(
  210. MINT_URL,
  211. CurrencyUnit::Sat,
  212. Arc::new(memory::empty().await.unwrap()),
  213. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  214. None,
  215. )
  216. .unwrap();
  217. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  218. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  219. let _proofs = proof_streams
  220. .next()
  221. .await
  222. .expect("payment")
  223. .expect("no error");
  224. let fake_description = FakeInvoiceDescription {
  225. pay_invoice_state: MeltQuoteState::Failed,
  226. check_payment_state: MeltQuoteState::Unknown,
  227. pay_err: true,
  228. check_err: false,
  229. };
  230. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  231. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  232. // The melt should error at the payment invoice command
  233. let melt = wallet.melt(&melt_quote.id).await;
  234. assert!(melt.is_err());
  235. let fake_description = FakeInvoiceDescription {
  236. pay_invoice_state: MeltQuoteState::Unknown,
  237. check_payment_state: MeltQuoteState::Unknown,
  238. pay_err: true,
  239. check_err: false,
  240. };
  241. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  242. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  243. // The melt should error at the payment invoice command
  244. let melt = wallet.melt(&melt_quote.id).await;
  245. assert!(melt.is_err());
  246. assert!(!wallet
  247. .localstore
  248. .get_proofs(None, None, Some(vec![State::Pending]), None)
  249. .await
  250. .unwrap()
  251. .is_empty());
  252. }
  253. /// Tests that when the ln backend returns an error but the second check returns paid,
  254. /// proofs should remain in pending state
  255. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  256. async fn test_fake_melt_payment_err_paid() {
  257. let wallet = Wallet::new(
  258. MINT_URL,
  259. CurrencyUnit::Sat,
  260. Arc::new(memory::empty().await.unwrap()),
  261. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  262. None,
  263. )
  264. .expect("Failed to create new wallet");
  265. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  266. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  267. let _proofs = proof_streams
  268. .next()
  269. .await
  270. .expect("payment")
  271. .expect("no error");
  272. let old_balance = wallet.total_balance().await.expect("balance");
  273. let fake_description = FakeInvoiceDescription {
  274. pay_invoice_state: MeltQuoteState::Failed,
  275. check_payment_state: MeltQuoteState::Paid,
  276. pay_err: true,
  277. check_err: false,
  278. };
  279. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  280. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  281. // The melt should error at the payment invoice command
  282. let melt = wallet.melt(&melt_quote.id).await.unwrap();
  283. assert!(melt.fee_paid == Amount::ZERO);
  284. assert!(melt.amount == Amount::from(7));
  285. // melt failed, but there is new code to reclaim unspent proofs
  286. assert_eq!(
  287. old_balance - melt.amount,
  288. wallet.total_balance().await.expect("new balance")
  289. );
  290. assert!(wallet
  291. .localstore
  292. .get_proofs(None, None, Some(vec![State::Pending]), None)
  293. .await
  294. .unwrap()
  295. .is_empty());
  296. }
  297. /// Tests that change outputs in a melt quote are correctly handled
  298. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  299. async fn test_fake_melt_change_in_quote() {
  300. let wallet = Wallet::new(
  301. MINT_URL,
  302. CurrencyUnit::Sat,
  303. Arc::new(memory::empty().await.unwrap()),
  304. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  305. None,
  306. )
  307. .expect("Failed to create new wallet");
  308. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  309. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  310. let _proofs = proof_streams
  311. .next()
  312. .await
  313. .expect("payment")
  314. .expect("no error");
  315. let transaction = wallet
  316. .list_transactions(Some(TransactionDirection::Incoming))
  317. .await
  318. .unwrap()
  319. .pop()
  320. .expect("No transaction found");
  321. assert_eq!(wallet.mint_url, transaction.mint_url);
  322. assert_eq!(TransactionDirection::Incoming, transaction.direction);
  323. assert_eq!(Amount::from(100), transaction.amount);
  324. assert_eq!(Amount::from(0), transaction.fee);
  325. assert_eq!(CurrencyUnit::Sat, transaction.unit);
  326. let fake_description = FakeInvoiceDescription::default();
  327. let invoice = create_fake_invoice(9000, serde_json::to_string(&fake_description).unwrap());
  328. let proofs = wallet.get_unspent_proofs().await.unwrap();
  329. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  330. let keyset = wallet.fetch_active_keyset().await.unwrap();
  331. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  332. let premint_secrets = PreMintSecrets::random(
  333. keyset.id,
  334. 100.into(),
  335. &SplitTarget::default(),
  336. &fee_and_amounts,
  337. )
  338. .unwrap();
  339. let client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  340. let melt_request = MeltRequest::new(
  341. melt_quote.id.clone(),
  342. proofs.clone(),
  343. Some(premint_secrets.blinded_messages()),
  344. );
  345. let melt_response = client.post_melt(melt_request).await.unwrap();
  346. assert!(melt_response.change.is_some());
  347. let check = wallet.melt_quote_status(&melt_quote.id).await.unwrap();
  348. let mut melt_change = melt_response.change.unwrap();
  349. melt_change.sort_by(|a, b| a.amount.cmp(&b.amount));
  350. let mut check = check.change.unwrap();
  351. check.sort_by(|a, b| a.amount.cmp(&b.amount));
  352. assert_eq!(melt_change, check);
  353. }
  354. /// Tests minting tokens with a valid witness signature
  355. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  356. async fn test_fake_mint_with_witness() {
  357. let wallet = Wallet::new(
  358. MINT_URL,
  359. CurrencyUnit::Sat,
  360. Arc::new(memory::empty().await.unwrap()),
  361. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  362. None,
  363. )
  364. .expect("failed to create new wallet");
  365. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  366. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  367. let proofs = proof_streams
  368. .next()
  369. .await
  370. .expect("payment")
  371. .expect("no error");
  372. let mint_amount = proofs.total_amount().unwrap();
  373. assert!(mint_amount == 100.into());
  374. }
  375. /// Tests that minting without a witness signature fails with the correct error
  376. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  377. async fn test_fake_mint_without_witness() {
  378. let wallet = Wallet::new(
  379. MINT_URL,
  380. CurrencyUnit::Sat,
  381. Arc::new(memory::empty().await.unwrap()),
  382. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  383. None,
  384. )
  385. .expect("failed to create new wallet");
  386. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  387. let mut payment_streams = wallet.payment_stream(&mint_quote);
  388. payment_streams
  389. .next()
  390. .await
  391. .expect("payment")
  392. .expect("no error");
  393. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  394. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  395. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  396. let premint_secrets = PreMintSecrets::random(
  397. active_keyset_id,
  398. 100.into(),
  399. &SplitTarget::default(),
  400. &fee_and_amounts,
  401. )
  402. .unwrap();
  403. let request = MintRequest {
  404. quote: mint_quote.id,
  405. outputs: premint_secrets.blinded_messages(),
  406. signature: None,
  407. };
  408. let response = http_client.post_mint(request.clone()).await;
  409. match response {
  410. Err(cdk::error::Error::SignatureMissingOrInvalid) => {} //pass
  411. Err(err) => panic!("Wrong mint response for minting without witness: {}", err),
  412. Ok(_) => panic!("Minting should not have succeed without a witness"),
  413. }
  414. }
  415. /// Tests that minting with an incorrect witness signature fails with the correct error
  416. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  417. async fn test_fake_mint_with_wrong_witness() {
  418. let wallet = Wallet::new(
  419. MINT_URL,
  420. CurrencyUnit::Sat,
  421. Arc::new(memory::empty().await.unwrap()),
  422. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  423. None,
  424. )
  425. .expect("failed to create new wallet");
  426. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  427. let mut payment_streams = wallet.payment_stream(&mint_quote);
  428. payment_streams
  429. .next()
  430. .await
  431. .expect("payment")
  432. .expect("no error");
  433. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  434. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  435. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  436. let premint_secrets = PreMintSecrets::random(
  437. active_keyset_id,
  438. 100.into(),
  439. &SplitTarget::default(),
  440. &fee_and_amounts,
  441. )
  442. .unwrap();
  443. let mut request = MintRequest {
  444. quote: mint_quote.id,
  445. outputs: premint_secrets.blinded_messages(),
  446. signature: None,
  447. };
  448. let secret_key = SecretKey::generate();
  449. request
  450. .sign(secret_key)
  451. .expect("failed to sign the mint request");
  452. let response = http_client.post_mint(request.clone()).await;
  453. match response {
  454. Err(cdk::error::Error::SignatureMissingOrInvalid) => {} //pass
  455. Err(err) => panic!("Wrong mint response for minting without witness: {}", err),
  456. Ok(_) => panic!("Minting should not have succeed without a witness"),
  457. }
  458. }
  459. /// Tests that attempting to mint more tokens than allowed by the quote fails
  460. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  461. async fn test_fake_mint_inflated() {
  462. let wallet = Wallet::new(
  463. MINT_URL,
  464. CurrencyUnit::Sat,
  465. Arc::new(memory::empty().await.unwrap()),
  466. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  467. None,
  468. )
  469. .expect("failed to create new wallet");
  470. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  471. let mut payment_streams = wallet.payment_stream(&mint_quote);
  472. payment_streams
  473. .next()
  474. .await
  475. .expect("payment")
  476. .expect("no error");
  477. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  478. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  479. let pre_mint = PreMintSecrets::random(
  480. active_keyset_id,
  481. 500.into(),
  482. &SplitTarget::None,
  483. &fee_and_amounts,
  484. )
  485. .unwrap();
  486. let quote_info = wallet
  487. .localstore
  488. .get_mint_quote(&mint_quote.id)
  489. .await
  490. .unwrap()
  491. .expect("there is a quote");
  492. let mut mint_request = MintRequest {
  493. quote: mint_quote.id,
  494. outputs: pre_mint.blinded_messages(),
  495. signature: None,
  496. };
  497. if let Some(secret_key) = quote_info.secret_key {
  498. mint_request
  499. .sign(secret_key)
  500. .expect("failed to sign the mint request");
  501. }
  502. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  503. let response = http_client.post_mint(mint_request.clone()).await;
  504. match response {
  505. Err(err) => match err {
  506. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  507. err => {
  508. panic!("Wrong mint error returned: {}", err);
  509. }
  510. },
  511. Ok(_) => {
  512. panic!("Should not have allowed second payment");
  513. }
  514. }
  515. }
  516. /// Tests that attempting to mint with multiple currency units in the same request fails
  517. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  518. async fn test_fake_mint_multiple_units() {
  519. let wallet = Wallet::new(
  520. MINT_URL,
  521. CurrencyUnit::Sat,
  522. Arc::new(memory::empty().await.unwrap()),
  523. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  524. None,
  525. )
  526. .expect("failed to create new wallet");
  527. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  528. let mut payment_streams = wallet.payment_stream(&mint_quote);
  529. payment_streams
  530. .next()
  531. .await
  532. .expect("payment")
  533. .expect("no error");
  534. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  535. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  536. let pre_mint = PreMintSecrets::random(
  537. active_keyset_id,
  538. 50.into(),
  539. &SplitTarget::None,
  540. &fee_and_amounts,
  541. )
  542. .unwrap();
  543. let wallet_usd = Wallet::new(
  544. MINT_URL,
  545. CurrencyUnit::Usd,
  546. Arc::new(memory::empty().await.unwrap()),
  547. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  548. None,
  549. )
  550. .expect("failed to create new wallet");
  551. let active_keyset_id = wallet_usd.fetch_active_keyset().await.unwrap().id;
  552. let usd_pre_mint = PreMintSecrets::random(
  553. active_keyset_id,
  554. 50.into(),
  555. &SplitTarget::None,
  556. &fee_and_amounts,
  557. )
  558. .unwrap();
  559. let quote_info = wallet
  560. .localstore
  561. .get_mint_quote(&mint_quote.id)
  562. .await
  563. .unwrap()
  564. .expect("there is a quote");
  565. let mut sat_outputs = pre_mint.blinded_messages();
  566. let mut usd_outputs = usd_pre_mint.blinded_messages();
  567. sat_outputs.append(&mut usd_outputs);
  568. let mut mint_request = MintRequest {
  569. quote: mint_quote.id,
  570. outputs: sat_outputs,
  571. signature: None,
  572. };
  573. if let Some(secret_key) = quote_info.secret_key {
  574. mint_request
  575. .sign(secret_key)
  576. .expect("failed to sign the mint request");
  577. }
  578. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  579. let response = http_client.post_mint(mint_request.clone()).await;
  580. match response {
  581. Err(err) => match err {
  582. cdk::Error::MultipleUnits => (),
  583. err => {
  584. panic!("Wrong mint error returned: {}", err);
  585. }
  586. },
  587. Ok(_) => {
  588. panic!("Should not have allowed to mint with multiple units");
  589. }
  590. }
  591. }
  592. /// Tests that attempting to swap tokens with multiple currency units fails
  593. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  594. async fn test_fake_mint_multiple_unit_swap() {
  595. let wallet = Wallet::new(
  596. MINT_URL,
  597. CurrencyUnit::Sat,
  598. Arc::new(memory::empty().await.unwrap()),
  599. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  600. None,
  601. )
  602. .expect("failed to create new wallet");
  603. wallet.refresh_keysets().await.unwrap();
  604. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  605. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  606. let proofs = proof_streams
  607. .next()
  608. .await
  609. .expect("payment")
  610. .expect("no error");
  611. let wallet_usd = Wallet::new(
  612. MINT_URL,
  613. CurrencyUnit::Usd,
  614. Arc::new(memory::empty().await.unwrap()),
  615. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  616. None,
  617. )
  618. .expect("failed to create usd wallet");
  619. wallet_usd.refresh_keysets().await.unwrap();
  620. let mint_quote = wallet_usd.mint_quote(100.into(), None).await.unwrap();
  621. let mut proof_streams =
  622. wallet_usd.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  623. let usd_proofs = proof_streams
  624. .next()
  625. .await
  626. .expect("payment")
  627. .expect("no error");
  628. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  629. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  630. {
  631. let inputs: Proofs = vec![
  632. proofs.first().expect("There is a proof").clone(),
  633. usd_proofs.first().expect("There is a proof").clone(),
  634. ];
  635. let pre_mint = PreMintSecrets::random(
  636. active_keyset_id,
  637. inputs.total_amount().unwrap(),
  638. &SplitTarget::None,
  639. &fee_and_amounts,
  640. )
  641. .unwrap();
  642. let swap_request = SwapRequest::new(inputs, pre_mint.blinded_messages());
  643. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  644. let response = http_client.post_swap(swap_request.clone()).await;
  645. match response {
  646. Err(err) => match err {
  647. cdk::Error::MultipleUnits => (),
  648. err => {
  649. panic!("Wrong mint error returned: {}", err);
  650. }
  651. },
  652. Ok(_) => {
  653. panic!("Should not have allowed to mint with multiple units");
  654. }
  655. }
  656. }
  657. {
  658. let usd_active_keyset_id = wallet_usd.fetch_active_keyset().await.unwrap().id;
  659. let inputs: Proofs = proofs.into_iter().take(2).collect();
  660. let total_inputs = inputs.total_amount().unwrap();
  661. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  662. let half = total_inputs / 2.into();
  663. let usd_pre_mint = PreMintSecrets::random(
  664. usd_active_keyset_id,
  665. half,
  666. &SplitTarget::None,
  667. &fee_and_amounts,
  668. )
  669. .unwrap();
  670. let pre_mint = PreMintSecrets::random(
  671. active_keyset_id,
  672. total_inputs - half,
  673. &SplitTarget::None,
  674. &fee_and_amounts,
  675. )
  676. .unwrap();
  677. let mut usd_outputs = usd_pre_mint.blinded_messages();
  678. let mut sat_outputs = pre_mint.blinded_messages();
  679. usd_outputs.append(&mut sat_outputs);
  680. let swap_request = SwapRequest::new(inputs, usd_outputs);
  681. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  682. let response = http_client.post_swap(swap_request.clone()).await;
  683. match response {
  684. Err(err) => match err {
  685. cdk::Error::MultipleUnits => (),
  686. err => {
  687. panic!("Wrong mint error returned: {}", err);
  688. }
  689. },
  690. Ok(_) => {
  691. panic!("Should not have allowed to mint with multiple units");
  692. }
  693. }
  694. }
  695. }
  696. /// Tests that attempting to melt tokens with multiple currency units fails
  697. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  698. async fn test_fake_mint_multiple_unit_melt() {
  699. let wallet = Wallet::new(
  700. MINT_URL,
  701. CurrencyUnit::Sat,
  702. Arc::new(memory::empty().await.unwrap()),
  703. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  704. None,
  705. )
  706. .expect("failed to create new wallet");
  707. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  708. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  709. let mut proofs = proof_streams
  710. .next()
  711. .await
  712. .expect("payment")
  713. .expect("no error");
  714. println!("Minted sat");
  715. let wallet_usd = Wallet::new(
  716. MINT_URL,
  717. CurrencyUnit::Usd,
  718. Arc::new(memory::empty().await.unwrap()),
  719. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  720. None,
  721. )
  722. .expect("failed to create new wallet");
  723. let mint_quote = wallet_usd.mint_quote(100.into(), None).await.unwrap();
  724. println!("Minted quote usd");
  725. let mut proof_streams =
  726. wallet_usd.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  727. let mut usd_proofs = proof_streams
  728. .next()
  729. .await
  730. .expect("payment")
  731. .expect("no error");
  732. usd_proofs.reverse();
  733. proofs.reverse();
  734. {
  735. let inputs: Proofs = vec![
  736. proofs.first().expect("There is a proof").clone(),
  737. usd_proofs.first().expect("There is a proof").clone(),
  738. ];
  739. let input_amount: u64 = inputs.total_amount().unwrap().into();
  740. let invoice = create_fake_invoice((input_amount - 1) * 1000, "".to_string());
  741. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  742. let melt_request = MeltRequest::new(melt_quote.id, inputs, None);
  743. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  744. let response = http_client.post_melt(melt_request.clone()).await;
  745. match response {
  746. Err(err) => match err {
  747. cdk::Error::MultipleUnits => (),
  748. err => {
  749. panic!("Wrong mint error returned: {}", err);
  750. }
  751. },
  752. Ok(_) => {
  753. panic!("Should not have allowed to melt with multiple units");
  754. }
  755. }
  756. }
  757. {
  758. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  759. let inputs: Proofs = vec![proofs.first().expect("There is a proof").clone()];
  760. let input_amount: u64 = inputs.total_amount().unwrap().into();
  761. let invoice = create_fake_invoice((input_amount - 1) * 1000, "".to_string());
  762. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  763. let usd_active_keyset_id = wallet_usd.fetch_active_keyset().await.unwrap().id;
  764. let usd_pre_mint = PreMintSecrets::random(
  765. usd_active_keyset_id,
  766. inputs.total_amount().unwrap() + 100.into(),
  767. &SplitTarget::None,
  768. &fee_and_amounts,
  769. )
  770. .unwrap();
  771. let pre_mint = PreMintSecrets::random(
  772. active_keyset_id,
  773. 100.into(),
  774. &SplitTarget::None,
  775. &fee_and_amounts,
  776. )
  777. .unwrap();
  778. let mut usd_outputs = usd_pre_mint.blinded_messages();
  779. let mut sat_outputs = pre_mint.blinded_messages();
  780. usd_outputs.append(&mut sat_outputs);
  781. let quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  782. let melt_request = MeltRequest::new(quote.id, inputs, Some(usd_outputs));
  783. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  784. let response = http_client.post_melt(melt_request.clone()).await;
  785. match response {
  786. Err(err) => match err {
  787. cdk::Error::MultipleUnits => (),
  788. err => {
  789. panic!("Wrong mint error returned: {}", err);
  790. }
  791. },
  792. Ok(_) => {
  793. panic!("Should not have allowed to melt with multiple units");
  794. }
  795. }
  796. }
  797. }
  798. /// Tests that swapping tokens where input unit doesn't match output unit fails
  799. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  800. async fn test_fake_mint_input_output_mismatch() {
  801. let wallet = Wallet::new(
  802. MINT_URL,
  803. CurrencyUnit::Sat,
  804. Arc::new(memory::empty().await.unwrap()),
  805. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  806. None,
  807. )
  808. .expect("failed to create new wallet");
  809. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  810. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  811. let proofs = proof_streams
  812. .next()
  813. .await
  814. .expect("payment")
  815. .expect("no error");
  816. let wallet_usd = Wallet::new(
  817. MINT_URL,
  818. CurrencyUnit::Usd,
  819. Arc::new(memory::empty().await.unwrap()),
  820. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  821. None,
  822. )
  823. .expect("failed to create new usd wallet");
  824. let usd_active_keyset_id = wallet_usd.fetch_active_keyset().await.unwrap().id;
  825. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  826. let inputs = proofs;
  827. let pre_mint = PreMintSecrets::random(
  828. usd_active_keyset_id,
  829. inputs.total_amount().unwrap(),
  830. &SplitTarget::None,
  831. &fee_and_amounts,
  832. )
  833. .unwrap();
  834. let swap_request = SwapRequest::new(inputs, pre_mint.blinded_messages());
  835. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  836. let response = http_client.post_swap(swap_request.clone()).await;
  837. match response {
  838. Err(err) => match err {
  839. cdk::Error::UnitMismatch => (),
  840. err => panic!("Wrong error returned: {}", err),
  841. },
  842. Ok(_) => {
  843. panic!("Should not have allowed to mint with multiple units");
  844. }
  845. }
  846. }
  847. /// Tests that swapping tokens where output amount is greater than input amount fails
  848. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  849. async fn test_fake_mint_swap_inflated() {
  850. let wallet = Wallet::new(
  851. MINT_URL,
  852. CurrencyUnit::Sat,
  853. Arc::new(memory::empty().await.unwrap()),
  854. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  855. None,
  856. )
  857. .expect("failed to create new wallet");
  858. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  859. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  860. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  861. let proofs = proof_streams
  862. .next()
  863. .await
  864. .expect("payment")
  865. .expect("no error");
  866. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  867. let pre_mint = PreMintSecrets::random(
  868. active_keyset_id,
  869. 101.into(),
  870. &SplitTarget::None,
  871. &fee_and_amounts,
  872. )
  873. .unwrap();
  874. let swap_request = SwapRequest::new(proofs, pre_mint.blinded_messages());
  875. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  876. let response = http_client.post_swap(swap_request.clone()).await;
  877. match response {
  878. Err(err) => match err {
  879. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  880. err => {
  881. panic!("Wrong mint error returned: {}", err);
  882. }
  883. },
  884. Ok(_) => {
  885. panic!("Should not have allowed to mint with multiple units");
  886. }
  887. }
  888. }
  889. /// Tests that tokens cannot be spent again after a failed swap attempt
  890. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  891. async fn test_fake_mint_swap_spend_after_fail() {
  892. let wallet = Wallet::new(
  893. MINT_URL,
  894. CurrencyUnit::Sat,
  895. Arc::new(memory::empty().await.unwrap()),
  896. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  897. None,
  898. )
  899. .expect("failed to create new wallet");
  900. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  901. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  902. let proofs = proof_streams
  903. .next()
  904. .await
  905. .expect("payment")
  906. .expect("no error");
  907. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  908. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  909. let pre_mint = PreMintSecrets::random(
  910. active_keyset_id,
  911. 100.into(),
  912. &SplitTarget::None,
  913. &fee_and_amounts,
  914. )
  915. .unwrap();
  916. let swap_request = SwapRequest::new(proofs.clone(), pre_mint.blinded_messages());
  917. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  918. let response = http_client.post_swap(swap_request.clone()).await;
  919. assert!(response.is_ok());
  920. let pre_mint = PreMintSecrets::random(
  921. active_keyset_id,
  922. 101.into(),
  923. &SplitTarget::None,
  924. &fee_and_amounts,
  925. )
  926. .unwrap();
  927. let swap_request = SwapRequest::new(proofs.clone(), pre_mint.blinded_messages());
  928. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  929. let response = http_client.post_swap(swap_request.clone()).await;
  930. match response {
  931. Err(err) => match err {
  932. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  933. err => panic!("Wrong mint error returned expected TransactionUnbalanced, got: {err}"),
  934. },
  935. Ok(_) => panic!("Should not have allowed swap with unbalanced"),
  936. }
  937. let pre_mint = PreMintSecrets::random(
  938. active_keyset_id,
  939. 100.into(),
  940. &SplitTarget::None,
  941. &fee_and_amounts,
  942. )
  943. .unwrap();
  944. let swap_request = SwapRequest::new(proofs, pre_mint.blinded_messages());
  945. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  946. let response = http_client.post_swap(swap_request.clone()).await;
  947. match response {
  948. Err(err) => match err {
  949. cdk::Error::TokenAlreadySpent => (),
  950. err => {
  951. panic!("Wrong mint error returned: {}", err);
  952. }
  953. },
  954. Ok(_) => {
  955. panic!("Should not have allowed to mint with multiple units");
  956. }
  957. }
  958. }
  959. /// Tests that tokens cannot be melted after a failed swap attempt
  960. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  961. async fn test_fake_mint_melt_spend_after_fail() {
  962. let wallet = Wallet::new(
  963. MINT_URL,
  964. CurrencyUnit::Sat,
  965. Arc::new(memory::empty().await.unwrap()),
  966. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  967. None,
  968. )
  969. .expect("failed to create new wallet");
  970. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  971. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  972. let proofs = proof_streams
  973. .next()
  974. .await
  975. .expect("payment")
  976. .expect("no error");
  977. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  978. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  979. let pre_mint = PreMintSecrets::random(
  980. active_keyset_id,
  981. 100.into(),
  982. &SplitTarget::None,
  983. &fee_and_amounts,
  984. )
  985. .unwrap();
  986. let swap_request = SwapRequest::new(proofs.clone(), pre_mint.blinded_messages());
  987. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  988. let response = http_client.post_swap(swap_request.clone()).await;
  989. assert!(response.is_ok());
  990. let pre_mint = PreMintSecrets::random(
  991. active_keyset_id,
  992. 101.into(),
  993. &SplitTarget::None,
  994. &fee_and_amounts,
  995. )
  996. .unwrap();
  997. let swap_request = SwapRequest::new(proofs.clone(), pre_mint.blinded_messages());
  998. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  999. let response = http_client.post_swap(swap_request.clone()).await;
  1000. match response {
  1001. Err(err) => match err {
  1002. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  1003. err => panic!("Wrong mint error returned expected TransactionUnbalanced, got: {err}"),
  1004. },
  1005. Ok(_) => panic!("Should not have allowed swap with unbalanced"),
  1006. }
  1007. let input_amount: u64 = proofs.total_amount().unwrap().into();
  1008. let invoice = create_fake_invoice((input_amount - 1) * 1000, "".to_string());
  1009. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  1010. let melt_request = MeltRequest::new(melt_quote.id, proofs, None);
  1011. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1012. let response = http_client.post_melt(melt_request.clone()).await;
  1013. match response {
  1014. Err(err) => match err {
  1015. cdk::Error::TokenAlreadySpent => (),
  1016. err => {
  1017. panic!("Wrong mint error returned: {}", err);
  1018. }
  1019. },
  1020. Ok(_) => {
  1021. panic!("Should not have allowed to melt with multiple units");
  1022. }
  1023. }
  1024. }
  1025. /// Tests that attempting to swap with duplicate proofs fails
  1026. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1027. async fn test_fake_mint_duplicate_proofs_swap() {
  1028. let wallet = Wallet::new(
  1029. MINT_URL,
  1030. CurrencyUnit::Sat,
  1031. Arc::new(memory::empty().await.unwrap()),
  1032. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1033. None,
  1034. )
  1035. .expect("failed to create new wallet");
  1036. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  1037. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1038. let proofs = proof_streams
  1039. .next()
  1040. .await
  1041. .expect("payment")
  1042. .expect("no error");
  1043. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  1044. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  1045. let inputs = vec![proofs[0].clone(), proofs[0].clone()];
  1046. let pre_mint = PreMintSecrets::random(
  1047. active_keyset_id,
  1048. inputs.total_amount().unwrap(),
  1049. &SplitTarget::None,
  1050. &fee_and_amounts,
  1051. )
  1052. .unwrap();
  1053. let swap_request = SwapRequest::new(inputs.clone(), pre_mint.blinded_messages());
  1054. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1055. let response = http_client.post_swap(swap_request.clone()).await;
  1056. match response {
  1057. Err(err) => match err {
  1058. cdk::Error::DuplicateInputs => (),
  1059. err => {
  1060. panic!(
  1061. "Wrong mint error returned, expected duplicate inputs: {}",
  1062. err
  1063. );
  1064. }
  1065. },
  1066. Ok(_) => {
  1067. panic!("Should not have allowed duplicate inputs");
  1068. }
  1069. }
  1070. let blinded_message = pre_mint.blinded_messages();
  1071. let inputs = vec![proofs[0].clone()];
  1072. let outputs = vec![blinded_message[0].clone(), blinded_message[0].clone()];
  1073. let swap_request = SwapRequest::new(inputs, outputs);
  1074. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1075. let response = http_client.post_swap(swap_request.clone()).await;
  1076. match response {
  1077. Err(err) => match err {
  1078. cdk::Error::DuplicateOutputs => (),
  1079. err => {
  1080. panic!(
  1081. "Wrong mint error returned, expected duplicate outputs: {}",
  1082. err
  1083. );
  1084. }
  1085. },
  1086. Ok(_) => {
  1087. panic!("Should not have allow duplicate inputs");
  1088. }
  1089. }
  1090. }
  1091. /// Tests that attempting to melt with duplicate proofs fails
  1092. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1093. async fn test_fake_mint_duplicate_proofs_melt() {
  1094. let wallet = Wallet::new(
  1095. MINT_URL,
  1096. CurrencyUnit::Sat,
  1097. Arc::new(memory::empty().await.unwrap()),
  1098. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1099. None,
  1100. )
  1101. .expect("failed to create new wallet");
  1102. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  1103. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1104. let proofs = proof_streams
  1105. .next()
  1106. .await
  1107. .expect("payment")
  1108. .expect("no error");
  1109. let inputs = vec![proofs[0].clone(), proofs[0].clone()];
  1110. let invoice = create_fake_invoice(7000, "".to_string());
  1111. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  1112. let melt_request = MeltRequest::new(melt_quote.id, inputs, None);
  1113. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1114. let response = http_client.post_melt(melt_request.clone()).await;
  1115. match response {
  1116. Err(err) => match err {
  1117. cdk::Error::DuplicateInputs => (),
  1118. err => {
  1119. panic!("Wrong mint error returned: {}", err);
  1120. }
  1121. },
  1122. Ok(_) => {
  1123. panic!("Should not have allow duplicate inputs");
  1124. }
  1125. }
  1126. }
  1127. /// Tests that wallet automatically recovers proofs after a failed melt operation
  1128. /// by swapping them to new proofs, preventing loss of funds
  1129. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1130. async fn test_wallet_proof_recovery_after_failed_melt() {
  1131. let wallet = Wallet::new(
  1132. MINT_URL,
  1133. CurrencyUnit::Sat,
  1134. Arc::new(memory::empty().await.unwrap()),
  1135. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1136. None,
  1137. )
  1138. .expect("failed to create new wallet");
  1139. // Mint 100 sats
  1140. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  1141. let _roof_streams = wallet
  1142. .wait_and_mint_quote(
  1143. mint_quote.clone(),
  1144. SplitTarget::default(),
  1145. None,
  1146. Duration::from_secs(1000),
  1147. )
  1148. .await;
  1149. assert_eq!(wallet.total_balance().await.unwrap(), Amount::from(100));
  1150. // Create a melt quote that will fail
  1151. let fake_description = FakeInvoiceDescription {
  1152. pay_invoice_state: MeltQuoteState::Unknown,
  1153. check_payment_state: MeltQuoteState::Unpaid,
  1154. pay_err: true,
  1155. check_err: false,
  1156. };
  1157. let invoice = create_fake_invoice(1000, serde_json::to_string(&fake_description).unwrap());
  1158. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  1159. // Attempt to melt - this should fail but trigger proof recovery
  1160. let melt_result = wallet.melt(&melt_quote.id).await;
  1161. assert!(melt_result.is_err(), "Melt should have failed");
  1162. // Verify wallet still has balance (proofs recovered)
  1163. assert_eq!(
  1164. wallet.total_balance().await.unwrap(),
  1165. Amount::from(100),
  1166. "Balance should be recovered"
  1167. );
  1168. // Verify we can still spend the recovered proofs
  1169. let valid_invoice = create_fake_invoice(7000, "".to_string());
  1170. let valid_melt_quote = wallet
  1171. .melt_quote(valid_invoice.to_string(), None)
  1172. .await
  1173. .unwrap();
  1174. let successful_melt = wallet.melt(&valid_melt_quote.id).await;
  1175. assert!(
  1176. successful_melt.is_ok(),
  1177. "Should be able to spend recovered proofs"
  1178. );
  1179. }
  1180. /// Tests that concurrent melt attempts for the same invoice result in exactly one success
  1181. ///
  1182. /// This test verifies the race condition protection: when multiple melt quotes exist for the
  1183. /// same invoice and all are attempted concurrently, only one should succeed due to
  1184. /// the FOR UPDATE locking on quotes with the same request_lookup_id.
  1185. #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
  1186. async fn test_concurrent_melt_same_invoice() {
  1187. const NUM_WALLETS: usize = 4;
  1188. // Create multiple wallets to simulate concurrent requests
  1189. let mut wallets = Vec::with_capacity(NUM_WALLETS);
  1190. for i in 0..NUM_WALLETS {
  1191. let wallet = Arc::new(
  1192. Wallet::new(
  1193. MINT_URL,
  1194. CurrencyUnit::Sat,
  1195. Arc::new(memory::empty().await.unwrap()),
  1196. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1197. None,
  1198. )
  1199. .expect(&format!("failed to create wallet {}", i)),
  1200. );
  1201. wallets.push(wallet);
  1202. }
  1203. // Mint proofs for all wallets
  1204. for (i, wallet) in wallets.iter().enumerate() {
  1205. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  1206. let mut proof_streams =
  1207. wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1208. proof_streams
  1209. .next()
  1210. .await
  1211. .expect(&format!("payment for wallet {}", i))
  1212. .expect("no error");
  1213. }
  1214. // Create a single invoice that all wallets will try to pay
  1215. let fake_description = FakeInvoiceDescription::default();
  1216. let invoice = create_fake_invoice(9000, serde_json::to_string(&fake_description).unwrap());
  1217. // All wallets create melt quotes for the same invoice
  1218. let mut melt_quotes = Vec::with_capacity(NUM_WALLETS);
  1219. for wallet in &wallets {
  1220. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  1221. melt_quotes.push(melt_quote);
  1222. }
  1223. // Verify all quotes have the same request (same invoice = same lookup_id)
  1224. for quote in &melt_quotes[1..] {
  1225. assert_eq!(
  1226. melt_quotes[0].request, quote.request,
  1227. "All quotes should be for the same invoice"
  1228. );
  1229. }
  1230. // Attempt all melts concurrently
  1231. let mut handles = Vec::with_capacity(NUM_WALLETS);
  1232. for (wallet, quote) in wallets.iter().zip(melt_quotes.iter()) {
  1233. let wallet_clone = Arc::clone(wallet);
  1234. let quote_id = quote.id.clone();
  1235. handles.push(tokio::spawn(
  1236. async move { wallet_clone.melt(&quote_id).await },
  1237. ));
  1238. }
  1239. // Collect results
  1240. let mut results = Vec::with_capacity(NUM_WALLETS);
  1241. for handle in handles {
  1242. results.push(handle.await.expect("task panicked"));
  1243. }
  1244. // Count successes and failures
  1245. let success_count = results.iter().filter(|r| r.is_ok()).count();
  1246. let failure_count = results.iter().filter(|r| r.is_err()).count();
  1247. assert_eq!(
  1248. success_count, 1,
  1249. "Expected exactly one successful melt, got {}. Results: {:?}",
  1250. success_count, results
  1251. );
  1252. assert_eq!(
  1253. failure_count,
  1254. NUM_WALLETS - 1,
  1255. "Expected {} failed melts, got {}",
  1256. NUM_WALLETS - 1,
  1257. failure_count
  1258. );
  1259. // Verify all failures were due to duplicate detection
  1260. for result in &results {
  1261. if let Err(err) = result {
  1262. let err_str = err.to_string().to_lowercase();
  1263. assert!(
  1264. err_str.contains("duplicate")
  1265. || err_str.contains("already paid")
  1266. || err_str.contains("pending"),
  1267. "Expected duplicate/already paid/pending error, got: {}",
  1268. err
  1269. );
  1270. }
  1271. }
  1272. }
  1273. /// Tests that wallet automatically recovers proofs after a failed swap operation
  1274. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1275. async fn test_wallet_proof_recovery_after_failed_swap() {
  1276. let wallet = Wallet::new(
  1277. MINT_URL,
  1278. CurrencyUnit::Sat,
  1279. Arc::new(memory::empty().await.unwrap()),
  1280. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1281. None,
  1282. )
  1283. .expect("failed to create new wallet");
  1284. // Mint 100 sats
  1285. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  1286. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1287. let initial_proofs = proof_streams
  1288. .next()
  1289. .await
  1290. .expect("payment")
  1291. .expect("no error");
  1292. let initial_ys: Vec<_> = initial_proofs.iter().map(|p| p.y().unwrap()).collect();
  1293. assert_eq!(wallet.total_balance().await.unwrap(), Amount::from(100));
  1294. let unspent_proofs = wallet.get_unspent_proofs().await.unwrap();
  1295. // Create an invalid swap by manually constructing a request that will fail
  1296. // We'll use the wallet's swap with invalid parameters to trigger a failure
  1297. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  1298. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  1299. // Create invalid swap request (requesting more than we have)
  1300. let preswap = PreMintSecrets::random(
  1301. active_keyset_id,
  1302. 1000.into(), // More than the 100 we have
  1303. &SplitTarget::default(),
  1304. &fee_and_amounts,
  1305. )
  1306. .unwrap();
  1307. let swap_request = SwapRequest::new(unspent_proofs.clone(), preswap.blinded_messages());
  1308. // Use HTTP client directly to bypass wallet's validation and trigger recovery
  1309. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1310. let response = http_client.post_swap(swap_request).await;
  1311. assert!(response.is_err(), "Swap should have failed");
  1312. // Note: The HTTP client doesn't trigger the wallet's try_proof_operation wrapper
  1313. // So we need to test through the wallet's own methods
  1314. // After the failed HTTP request, the proofs are still in the wallet's database
  1315. // Verify balance is still available after the failed operation
  1316. assert_eq!(
  1317. wallet.total_balance().await.unwrap(),
  1318. Amount::from(100),
  1319. "Balance should still be available"
  1320. );
  1321. // Verify we can perform a successful swap operation
  1322. let successful_swap = wallet
  1323. .swap(None, SplitTarget::None, unspent_proofs, None, false)
  1324. .await;
  1325. assert!(
  1326. successful_swap.is_ok(),
  1327. "Should be able to swap after failed operation"
  1328. );
  1329. // Verify the proofs were swapped to new ones
  1330. let final_proofs = wallet.get_unspent_proofs().await.unwrap();
  1331. let final_ys: Vec<_> = final_proofs.iter().map(|p| p.y().unwrap()).collect();
  1332. // The Ys should be different after the successful swap
  1333. assert!(
  1334. initial_ys.iter().any(|y| !final_ys.contains(y)),
  1335. "Proofs should have been swapped to new ones"
  1336. );
  1337. }
  1338. /// Tests that melt_proofs works correctly with proofs that are not already in the wallet's database.
  1339. /// This is similar to the receive flow where proofs come from an external source.
  1340. ///
  1341. /// Flow:
  1342. /// 1. Wallet A mints proofs (proofs ARE in Wallet A's database)
  1343. /// 2. Wallet B creates a melt quote
  1344. /// 3. Wallet B calls melt_proofs with proofs from Wallet A (proofs are NOT in Wallet B's database)
  1345. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1346. async fn test_melt_proofs_external() {
  1347. // Create sender wallet (Wallet A) and mint some proofs
  1348. let wallet_sender = Wallet::new(
  1349. MINT_URL,
  1350. CurrencyUnit::Sat,
  1351. Arc::new(memory::empty().await.unwrap()),
  1352. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1353. None,
  1354. )
  1355. .expect("failed to create sender wallet");
  1356. let mint_quote = wallet_sender.mint_quote(100.into(), None).await.unwrap();
  1357. let mut proof_streams =
  1358. wallet_sender.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1359. let proofs = proof_streams
  1360. .next()
  1361. .await
  1362. .expect("payment")
  1363. .expect("no error");
  1364. assert_eq!(proofs.total_amount().unwrap(), Amount::from(100));
  1365. // Create receiver/melter wallet (Wallet B) with a separate database
  1366. // These proofs are NOT in Wallet B's database
  1367. let wallet_melter = Wallet::new(
  1368. MINT_URL,
  1369. CurrencyUnit::Sat,
  1370. Arc::new(memory::empty().await.unwrap()),
  1371. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1372. None,
  1373. )
  1374. .expect("failed to create melter wallet");
  1375. // Verify proofs are not in the melter wallet's database
  1376. let melter_proofs = wallet_melter.get_unspent_proofs().await.unwrap();
  1377. assert!(
  1378. melter_proofs.is_empty(),
  1379. "Melter wallet should have no proofs initially"
  1380. );
  1381. // Create a fake invoice for melting
  1382. let fake_description = FakeInvoiceDescription::default();
  1383. let invoice = create_fake_invoice(9000, serde_json::to_string(&fake_description).unwrap());
  1384. // Wallet B creates a melt quote
  1385. let melt_quote = wallet_melter
  1386. .melt_quote(invoice.to_string(), None)
  1387. .await
  1388. .unwrap();
  1389. // Wallet B calls melt_proofs with external proofs (from Wallet A)
  1390. // These proofs are NOT in wallet_melter's database
  1391. let melted = wallet_melter
  1392. .melt_proofs(&melt_quote.id, proofs.clone())
  1393. .await
  1394. .unwrap();
  1395. // Verify the melt succeeded
  1396. assert_eq!(melted.amount, Amount::from(9));
  1397. assert_eq!(melted.fee_paid, 1.into());
  1398. // Verify change was returned (100 input - 9 melt amount = 91 change, minus fee reserve)
  1399. assert!(melted.change.is_some());
  1400. let change_amount = melted.change.unwrap().total_amount().unwrap();
  1401. assert!(change_amount > Amount::ZERO, "Should have received change");
  1402. // Verify the melter wallet now has the change proofs
  1403. let melter_balance = wallet_melter.total_balance().await.unwrap();
  1404. assert_eq!(melter_balance, change_amount);
  1405. // Verify a transaction was recorded
  1406. let transactions = wallet_melter
  1407. .list_transactions(Some(TransactionDirection::Outgoing))
  1408. .await
  1409. .unwrap();
  1410. assert_eq!(transactions.len(), 1);
  1411. assert_eq!(transactions[0].amount, Amount::from(9));
  1412. }