fake_wallet.rs 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059
  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. }
  1413. /// Tests that melt automatically performs a swap when proofs don't exactly match
  1414. /// the required amount (quote + fee_reserve + input_fee).
  1415. ///
  1416. /// This test verifies the swap-before-melt optimization:
  1417. /// 1. Mint proofs that will NOT exactly match a melt amount
  1418. /// 2. Create a melt quote for a specific amount
  1419. /// 3. Call melt() - it should automatically swap proofs to get exact denominations
  1420. /// 4. Verify the melt succeeded
  1421. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1422. async fn test_melt_with_swap_for_exact_amount() {
  1423. let wallet = Wallet::new(
  1424. MINT_URL,
  1425. CurrencyUnit::Sat,
  1426. Arc::new(memory::empty().await.unwrap()),
  1427. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1428. None,
  1429. )
  1430. .expect("failed to create new wallet");
  1431. // Mint 100 sats - this will give us proofs in standard denominations
  1432. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  1433. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1434. let proofs = proof_streams
  1435. .next()
  1436. .await
  1437. .expect("payment")
  1438. .expect("no error");
  1439. let initial_balance = wallet.total_balance().await.unwrap();
  1440. assert_eq!(initial_balance, Amount::from(100));
  1441. // Log the proof denominations we received
  1442. let proof_amounts: Vec<u64> = proofs.iter().map(|p| u64::from(p.amount)).collect();
  1443. tracing::info!("Initial proof denominations: {:?}", proof_amounts);
  1444. // Create a melt quote for an amount that likely won't match our proof denominations exactly
  1445. // Using 7 sats (7000 msats) which requires specific denominations
  1446. let fake_description = FakeInvoiceDescription::default();
  1447. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  1448. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  1449. tracing::info!(
  1450. "Melt quote: amount={}, fee_reserve={}",
  1451. melt_quote.amount,
  1452. melt_quote.fee_reserve
  1453. );
  1454. // Call melt() - this should trigger swap-before-melt if proofs don't match exactly
  1455. let melted = wallet.melt(&melt_quote.id).await.unwrap();
  1456. // Verify the melt succeeded
  1457. assert_eq!(melted.amount, Amount::from(7));
  1458. tracing::info!(
  1459. "Melt completed: amount={}, fee_paid={}",
  1460. melted.amount,
  1461. melted.fee_paid
  1462. );
  1463. // Verify final balance is correct (initial - melt_amount - fees)
  1464. let final_balance = wallet.total_balance().await.unwrap();
  1465. tracing::info!(
  1466. "Balance: initial={}, final={}, paid={}",
  1467. initial_balance,
  1468. final_balance,
  1469. melted.amount + melted.fee_paid
  1470. );
  1471. assert!(
  1472. final_balance < initial_balance,
  1473. "Balance should have decreased after melt"
  1474. );
  1475. assert_eq!(
  1476. final_balance,
  1477. initial_balance - melted.amount - melted.fee_paid,
  1478. "Final balance should be initial - amount - fees"
  1479. );
  1480. }
  1481. /// Tests that melt works correctly when proofs already exactly match the required amount.
  1482. /// In this case, no swap should be needed.
  1483. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1484. async fn test_melt_exact_proofs_no_swap_needed() {
  1485. let wallet = Wallet::new(
  1486. MINT_URL,
  1487. CurrencyUnit::Sat,
  1488. Arc::new(memory::empty().await.unwrap()),
  1489. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1490. None,
  1491. )
  1492. .expect("failed to create new wallet");
  1493. // Mint a larger amount to have more denomination options
  1494. let mint_quote = wallet.mint_quote(1000.into(), None).await.unwrap();
  1495. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1496. let _proofs = proof_streams
  1497. .next()
  1498. .await
  1499. .expect("payment")
  1500. .expect("no error");
  1501. let initial_balance = wallet.total_balance().await.unwrap();
  1502. assert_eq!(initial_balance, Amount::from(1000));
  1503. // Create a melt for a power-of-2 amount that's more likely to match existing denominations
  1504. let fake_description = FakeInvoiceDescription::default();
  1505. let invoice = create_fake_invoice(64_000, serde_json::to_string(&fake_description).unwrap()); // 64 sats
  1506. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  1507. // Melt should succeed
  1508. let melted = wallet.melt(&melt_quote.id).await.unwrap();
  1509. assert_eq!(melted.amount, Amount::from(64));
  1510. let final_balance = wallet.total_balance().await.unwrap();
  1511. assert_eq!(
  1512. final_balance,
  1513. initial_balance - melted.amount - melted.fee_paid
  1514. );
  1515. }
  1516. /// Tests the check_all_mint_quotes functionality for Bolt11 quotes
  1517. ///
  1518. /// This test verifies that:
  1519. /// 1. Paid mint quotes are automatically minted when check_all_mint_quotes is called
  1520. /// 2. The total amount returned matches the minted proofs
  1521. /// 3. Quote state is properly updated after minting
  1522. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1523. async fn test_check_all_mint_quotes_bolt11() {
  1524. let wallet = Wallet::new(
  1525. MINT_URL,
  1526. CurrencyUnit::Sat,
  1527. Arc::new(memory::empty().await.unwrap()),
  1528. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1529. None,
  1530. )
  1531. .expect("failed to create new wallet");
  1532. // Create first mint quote and pay it (using proof_stream triggers fake wallet payment)
  1533. let mint_quote_1 = wallet.mint_quote(100.into(), None).await.unwrap();
  1534. // Wait for the payment to be registered (fake wallet auto-pays)
  1535. let mut payment_stream_1 = wallet.payment_stream(&mint_quote_1);
  1536. payment_stream_1
  1537. .next()
  1538. .await
  1539. .expect("payment")
  1540. .expect("no error");
  1541. // Create second mint quote and pay it
  1542. let mint_quote_2 = wallet.mint_quote(50.into(), None).await.unwrap();
  1543. let mut payment_stream_2 = wallet.payment_stream(&mint_quote_2);
  1544. payment_stream_2
  1545. .next()
  1546. .await
  1547. .expect("payment")
  1548. .expect("no error");
  1549. // Verify no proofs have been minted yet
  1550. assert_eq!(wallet.total_balance().await.unwrap(), Amount::ZERO);
  1551. // Call check_all_mint_quotes - this should mint both paid quotes
  1552. let total_minted = wallet.check_all_mint_quotes().await.unwrap();
  1553. // Verify the total amount minted is correct (100 + 50 = 150)
  1554. assert_eq!(total_minted, Amount::from(150));
  1555. // Verify wallet balance matches
  1556. assert_eq!(wallet.total_balance().await.unwrap(), Amount::from(150));
  1557. // Calling check_all_mint_quotes again should return 0 (quotes already minted)
  1558. let second_check = wallet.check_all_mint_quotes().await.unwrap();
  1559. assert_eq!(second_check, Amount::ZERO);
  1560. }
  1561. /// Tests the get_unissued_mint_quotes wallet method
  1562. ///
  1563. /// This test verifies that:
  1564. /// 1. Unpaid quotes are included (wallet needs to check with mint)
  1565. /// 2. Paid but not issued quotes are included
  1566. /// 3. Fully issued quotes are excluded
  1567. /// 4. Only quotes for the current mint URL are returned
  1568. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1569. async fn test_get_unissued_mint_quotes_wallet() {
  1570. let wallet = Wallet::new(
  1571. MINT_URL,
  1572. CurrencyUnit::Sat,
  1573. Arc::new(memory::empty().await.unwrap()),
  1574. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1575. None,
  1576. )
  1577. .expect("failed to create new wallet");
  1578. // Create a quote but don't pay it (stays unpaid)
  1579. let unpaid_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  1580. // Create another quote and pay it but don't mint
  1581. let paid_quote = wallet.mint_quote(50.into(), None).await.unwrap();
  1582. let mut payment_stream = wallet.payment_stream(&paid_quote);
  1583. payment_stream
  1584. .next()
  1585. .await
  1586. .expect("payment")
  1587. .expect("no error");
  1588. // Create a third quote and fully mint it
  1589. let minted_quote = wallet.mint_quote(25.into(), None).await.unwrap();
  1590. let mut proof_stream = wallet.proof_stream(minted_quote.clone(), SplitTarget::default(), None);
  1591. proof_stream
  1592. .next()
  1593. .await
  1594. .expect("payment")
  1595. .expect("no error");
  1596. // Get unissued quotes
  1597. let unissued_quotes = wallet.get_unissued_mint_quotes().await.unwrap();
  1598. // Should have 2 quotes: unpaid and paid-but-not-issued
  1599. // The fully minted quote should be excluded
  1600. assert_eq!(
  1601. unissued_quotes.len(),
  1602. 2,
  1603. "Should have 2 unissued quotes (unpaid and paid-not-issued)"
  1604. );
  1605. let quote_ids: Vec<&str> = unissued_quotes.iter().map(|q| q.id.as_str()).collect();
  1606. assert!(
  1607. quote_ids.contains(&unpaid_quote.id.as_str()),
  1608. "Unpaid quote should be included"
  1609. );
  1610. assert!(
  1611. quote_ids.contains(&paid_quote.id.as_str()),
  1612. "Paid but not issued quote should be included"
  1613. );
  1614. assert!(
  1615. !quote_ids.contains(&minted_quote.id.as_str()),
  1616. "Fully minted quote should NOT be included"
  1617. );
  1618. }
  1619. /// Tests that mint quote state is properly updated after minting
  1620. ///
  1621. /// This test verifies that:
  1622. /// 1. amount_issued is updated after successful minting
  1623. /// 2. Quote state is updated correctly
  1624. /// 3. The quote is stored properly in the localstore
  1625. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1626. async fn test_mint_quote_state_updates_after_minting() {
  1627. let wallet = Wallet::new(
  1628. MINT_URL,
  1629. CurrencyUnit::Sat,
  1630. Arc::new(memory::empty().await.unwrap()),
  1631. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1632. None,
  1633. )
  1634. .expect("failed to create new wallet");
  1635. let mint_amount = Amount::from(100);
  1636. let mint_quote = wallet.mint_quote(mint_amount, None).await.unwrap();
  1637. // Get the quote from localstore before minting
  1638. let quote_before = wallet
  1639. .localstore
  1640. .get_mint_quote(&mint_quote.id)
  1641. .await
  1642. .unwrap()
  1643. .expect("Quote should exist");
  1644. // Verify initial state
  1645. assert_eq!(quote_before.amount_issued, Amount::ZERO);
  1646. // Mint the tokens using wait_and_mint_quote
  1647. let proofs = wallet
  1648. .wait_and_mint_quote(
  1649. mint_quote.clone(),
  1650. SplitTarget::default(),
  1651. None,
  1652. Duration::from_secs(60),
  1653. )
  1654. .await
  1655. .expect("minting should succeed");
  1656. let minted_amount = proofs.total_amount().unwrap();
  1657. assert_eq!(minted_amount, mint_amount);
  1658. // Check the quote is now either removed or updated in the localstore
  1659. // After minting, the quote should be removed from localstore (it's fully issued)
  1660. let quote_after = wallet
  1661. .localstore
  1662. .get_mint_quote(&mint_quote.id)
  1663. .await
  1664. .unwrap();
  1665. // The quote should either be removed or have amount_issued updated
  1666. match quote_after {
  1667. Some(quote) => {
  1668. // If still present, amount_issued should equal the minted amount
  1669. assert_eq!(
  1670. quote.amount_issued, minted_amount,
  1671. "amount_issued should be updated after minting"
  1672. );
  1673. }
  1674. None => {
  1675. // Quote was removed after being fully issued - this is also valid behavior
  1676. }
  1677. }
  1678. // Verify the unissued quotes no longer contains this quote
  1679. let unissued = wallet.get_unissued_mint_quotes().await.unwrap();
  1680. let unissued_ids: Vec<&str> = unissued.iter().map(|q| q.id.as_str()).collect();
  1681. assert!(
  1682. !unissued_ids.contains(&mint_quote.id.as_str()),
  1683. "Fully minted quote should not appear in unissued quotes"
  1684. );
  1685. }