fake_wallet.rs 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096
  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::{KnownMethod, ProofsMethods};
  22. use cdk::nuts::{
  23. CurrencyUnit, MeltQuoteState, MeltRequest, MintRequest, PaymentMethod, PreMintSecrets, Proofs,
  24. SecretKey, 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, 100.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
  346. .post_melt(&PaymentMethod::Known(KnownMethod::Bolt11), melt_request)
  347. .await
  348. .unwrap();
  349. assert!(melt_response.change.is_some());
  350. let check = wallet.melt_quote_status(&melt_quote.id).await.unwrap();
  351. let mut melt_change = melt_response.change.unwrap();
  352. melt_change.sort_by(|a, b| a.amount.cmp(&b.amount));
  353. let mut check = check.change.unwrap();
  354. check.sort_by(|a, b| a.amount.cmp(&b.amount));
  355. assert_eq!(melt_change, check);
  356. }
  357. /// Tests minting tokens with a valid witness signature
  358. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  359. async fn test_fake_mint_with_witness() {
  360. let wallet = Wallet::new(
  361. MINT_URL,
  362. CurrencyUnit::Sat,
  363. Arc::new(memory::empty().await.unwrap()),
  364. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  365. None,
  366. )
  367. .expect("failed to create new wallet");
  368. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  369. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  370. let proofs = proof_streams
  371. .next()
  372. .await
  373. .expect("payment")
  374. .expect("no error");
  375. let mint_amount = proofs.total_amount().unwrap();
  376. assert!(mint_amount == 100.into());
  377. }
  378. /// Tests that minting without a witness signature fails with the correct error
  379. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  380. async fn test_fake_mint_without_witness() {
  381. let wallet = Wallet::new(
  382. MINT_URL,
  383. CurrencyUnit::Sat,
  384. Arc::new(memory::empty().await.unwrap()),
  385. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  386. None,
  387. )
  388. .expect("failed to create new wallet");
  389. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  390. let mut payment_streams = wallet.payment_stream(&mint_quote);
  391. payment_streams
  392. .next()
  393. .await
  394. .expect("payment")
  395. .expect("no error");
  396. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  397. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  398. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  399. let premint_secrets = PreMintSecrets::random(
  400. active_keyset_id,
  401. 100.into(),
  402. &SplitTarget::default(),
  403. &fee_and_amounts,
  404. )
  405. .unwrap();
  406. let request = MintRequest {
  407. quote: mint_quote.id,
  408. outputs: premint_secrets.blinded_messages(),
  409. signature: None,
  410. };
  411. let response = http_client
  412. .post_mint(&PaymentMethod::Known(KnownMethod::Bolt11), request.clone())
  413. .await;
  414. match response {
  415. Err(cdk::error::Error::SignatureMissingOrInvalid) => {} //pass
  416. Err(err) => panic!("Wrong mint response for minting without witness: {}", err),
  417. Ok(_) => panic!("Minting should not have succeed without a witness"),
  418. }
  419. }
  420. /// Tests that minting with an incorrect witness signature fails with the correct error
  421. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  422. async fn test_fake_mint_with_wrong_witness() {
  423. let wallet = Wallet::new(
  424. MINT_URL,
  425. CurrencyUnit::Sat,
  426. Arc::new(memory::empty().await.unwrap()),
  427. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  428. None,
  429. )
  430. .expect("failed to create new wallet");
  431. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  432. let mut payment_streams = wallet.payment_stream(&mint_quote);
  433. payment_streams
  434. .next()
  435. .await
  436. .expect("payment")
  437. .expect("no error");
  438. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  439. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  440. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  441. let premint_secrets = PreMintSecrets::random(
  442. active_keyset_id,
  443. 100.into(),
  444. &SplitTarget::default(),
  445. &fee_and_amounts,
  446. )
  447. .unwrap();
  448. let mut request = MintRequest {
  449. quote: mint_quote.id,
  450. outputs: premint_secrets.blinded_messages(),
  451. signature: None,
  452. };
  453. let secret_key = SecretKey::generate();
  454. request
  455. .sign(secret_key)
  456. .expect("failed to sign the mint request");
  457. let response = http_client
  458. .post_mint(&PaymentMethod::Known(KnownMethod::Bolt11), request.clone())
  459. .await;
  460. match response {
  461. Err(cdk::error::Error::SignatureMissingOrInvalid) => {} //pass
  462. Err(err) => panic!("Wrong mint response for minting without witness: {}", err),
  463. Ok(_) => panic!("Minting should not have succeed without a witness"),
  464. }
  465. }
  466. /// Tests that attempting to mint more tokens than allowed by the quote fails
  467. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  468. async fn test_fake_mint_inflated() {
  469. let wallet = Wallet::new(
  470. MINT_URL,
  471. CurrencyUnit::Sat,
  472. Arc::new(memory::empty().await.unwrap()),
  473. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  474. None,
  475. )
  476. .expect("failed to create new wallet");
  477. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  478. let mut payment_streams = wallet.payment_stream(&mint_quote);
  479. payment_streams
  480. .next()
  481. .await
  482. .expect("payment")
  483. .expect("no error");
  484. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  485. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  486. let pre_mint = PreMintSecrets::random(
  487. active_keyset_id,
  488. 500.into(),
  489. &SplitTarget::None,
  490. &fee_and_amounts,
  491. )
  492. .unwrap();
  493. let quote_info = wallet
  494. .localstore
  495. .get_mint_quote(&mint_quote.id)
  496. .await
  497. .unwrap()
  498. .expect("there is a quote");
  499. let mut mint_request = MintRequest {
  500. quote: mint_quote.id,
  501. outputs: pre_mint.blinded_messages(),
  502. signature: None,
  503. };
  504. if let Some(secret_key) = quote_info.secret_key {
  505. mint_request
  506. .sign(secret_key)
  507. .expect("failed to sign the mint request");
  508. }
  509. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  510. let response = http_client
  511. .post_mint(
  512. &PaymentMethod::Known(KnownMethod::Bolt11),
  513. mint_request.clone(),
  514. )
  515. .await;
  516. match response {
  517. Err(err) => match err {
  518. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  519. err => {
  520. panic!("Wrong mint error returned: {}", err);
  521. }
  522. },
  523. Ok(_) => {
  524. panic!("Should not have allowed second payment");
  525. }
  526. }
  527. }
  528. /// Tests that attempting to mint with multiple currency units in the same request fails
  529. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  530. async fn test_fake_mint_multiple_units() {
  531. let wallet = Wallet::new(
  532. MINT_URL,
  533. CurrencyUnit::Sat,
  534. Arc::new(memory::empty().await.unwrap()),
  535. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  536. None,
  537. )
  538. .expect("failed to create new wallet");
  539. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  540. let mut payment_streams = wallet.payment_stream(&mint_quote);
  541. payment_streams
  542. .next()
  543. .await
  544. .expect("payment")
  545. .expect("no error");
  546. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  547. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  548. let pre_mint = PreMintSecrets::random(
  549. active_keyset_id,
  550. 50.into(),
  551. &SplitTarget::None,
  552. &fee_and_amounts,
  553. )
  554. .unwrap();
  555. let wallet_usd = Wallet::new(
  556. MINT_URL,
  557. CurrencyUnit::Usd,
  558. Arc::new(memory::empty().await.unwrap()),
  559. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  560. None,
  561. )
  562. .expect("failed to create new wallet");
  563. let active_keyset_id = wallet_usd.fetch_active_keyset().await.unwrap().id;
  564. let usd_pre_mint = PreMintSecrets::random(
  565. active_keyset_id,
  566. 50.into(),
  567. &SplitTarget::None,
  568. &fee_and_amounts,
  569. )
  570. .unwrap();
  571. let quote_info = wallet
  572. .localstore
  573. .get_mint_quote(&mint_quote.id)
  574. .await
  575. .unwrap()
  576. .expect("there is a quote");
  577. let mut sat_outputs = pre_mint.blinded_messages();
  578. let mut usd_outputs = usd_pre_mint.blinded_messages();
  579. sat_outputs.append(&mut usd_outputs);
  580. let mut mint_request = MintRequest {
  581. quote: mint_quote.id,
  582. outputs: sat_outputs,
  583. signature: None,
  584. };
  585. if let Some(secret_key) = quote_info.secret_key {
  586. mint_request
  587. .sign(secret_key)
  588. .expect("failed to sign the mint request");
  589. }
  590. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  591. let response = http_client
  592. .post_mint(
  593. &PaymentMethod::Known(KnownMethod::Bolt11),
  594. mint_request.clone(),
  595. )
  596. .await;
  597. match response {
  598. Err(err) => match err {
  599. cdk::Error::MultipleUnits => (),
  600. err => {
  601. panic!("Wrong mint error returned: {}", err);
  602. }
  603. },
  604. Ok(_) => {
  605. panic!("Should not have allowed to mint with multiple units");
  606. }
  607. }
  608. }
  609. /// Tests that attempting to swap tokens with multiple currency units fails
  610. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  611. async fn test_fake_mint_multiple_unit_swap() {
  612. let wallet = Wallet::new(
  613. MINT_URL,
  614. CurrencyUnit::Sat,
  615. Arc::new(memory::empty().await.unwrap()),
  616. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  617. None,
  618. )
  619. .expect("failed to create new wallet");
  620. wallet.refresh_keysets().await.unwrap();
  621. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  622. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  623. let proofs = proof_streams
  624. .next()
  625. .await
  626. .expect("payment")
  627. .expect("no error");
  628. let wallet_usd = Wallet::new(
  629. MINT_URL,
  630. CurrencyUnit::Usd,
  631. Arc::new(memory::empty().await.unwrap()),
  632. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  633. None,
  634. )
  635. .expect("failed to create usd wallet");
  636. wallet_usd.refresh_keysets().await.unwrap();
  637. let mint_quote = wallet_usd.mint_quote(100.into(), None).await.unwrap();
  638. let mut proof_streams =
  639. wallet_usd.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  640. let usd_proofs = proof_streams
  641. .next()
  642. .await
  643. .expect("payment")
  644. .expect("no error");
  645. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  646. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  647. {
  648. let inputs: Proofs = vec![
  649. proofs.first().expect("There is a proof").clone(),
  650. usd_proofs.first().expect("There is a proof").clone(),
  651. ];
  652. let pre_mint = PreMintSecrets::random(
  653. active_keyset_id,
  654. inputs.total_amount().unwrap(),
  655. &SplitTarget::None,
  656. &fee_and_amounts,
  657. )
  658. .unwrap();
  659. let swap_request = SwapRequest::new(inputs, pre_mint.blinded_messages());
  660. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  661. let response = http_client.post_swap(swap_request.clone()).await;
  662. match response {
  663. Err(err) => match err {
  664. cdk::Error::MultipleUnits => (),
  665. err => {
  666. panic!("Wrong mint error returned: {}", err);
  667. }
  668. },
  669. Ok(_) => {
  670. panic!("Should not have allowed to mint with multiple units");
  671. }
  672. }
  673. }
  674. {
  675. let usd_active_keyset_id = wallet_usd.fetch_active_keyset().await.unwrap().id;
  676. let inputs: Proofs = proofs.into_iter().take(2).collect();
  677. let total_inputs = inputs.total_amount().unwrap();
  678. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  679. let half = total_inputs / 2.into();
  680. let usd_pre_mint = PreMintSecrets::random(
  681. usd_active_keyset_id,
  682. half,
  683. &SplitTarget::None,
  684. &fee_and_amounts,
  685. )
  686. .unwrap();
  687. let pre_mint = PreMintSecrets::random(
  688. active_keyset_id,
  689. total_inputs - half,
  690. &SplitTarget::None,
  691. &fee_and_amounts,
  692. )
  693. .unwrap();
  694. let mut usd_outputs = usd_pre_mint.blinded_messages();
  695. let mut sat_outputs = pre_mint.blinded_messages();
  696. usd_outputs.append(&mut sat_outputs);
  697. let swap_request = SwapRequest::new(inputs, usd_outputs);
  698. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  699. let response = http_client.post_swap(swap_request.clone()).await;
  700. match response {
  701. Err(err) => match err {
  702. cdk::Error::MultipleUnits => (),
  703. err => {
  704. panic!("Wrong mint error returned: {}", err);
  705. }
  706. },
  707. Ok(_) => {
  708. panic!("Should not have allowed to mint with multiple units");
  709. }
  710. }
  711. }
  712. }
  713. /// Tests that attempting to melt tokens with multiple currency units fails
  714. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  715. async fn test_fake_mint_multiple_unit_melt() {
  716. let wallet = Wallet::new(
  717. MINT_URL,
  718. CurrencyUnit::Sat,
  719. Arc::new(memory::empty().await.unwrap()),
  720. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  721. None,
  722. )
  723. .expect("failed to create new wallet");
  724. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  725. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  726. let mut proofs = proof_streams
  727. .next()
  728. .await
  729. .expect("payment")
  730. .expect("no error");
  731. println!("Minted sat");
  732. let wallet_usd = Wallet::new(
  733. MINT_URL,
  734. CurrencyUnit::Usd,
  735. Arc::new(memory::empty().await.unwrap()),
  736. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  737. None,
  738. )
  739. .expect("failed to create new wallet");
  740. let mint_quote = wallet_usd.mint_quote(100.into(), None).await.unwrap();
  741. println!("Minted quote usd");
  742. let mut proof_streams =
  743. wallet_usd.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  744. let mut usd_proofs = proof_streams
  745. .next()
  746. .await
  747. .expect("payment")
  748. .expect("no error");
  749. usd_proofs.reverse();
  750. proofs.reverse();
  751. {
  752. let inputs: Proofs = vec![
  753. proofs.first().expect("There is a proof").clone(),
  754. usd_proofs.first().expect("There is a proof").clone(),
  755. ];
  756. let input_amount: u64 = inputs.total_amount().unwrap().into();
  757. let invoice = create_fake_invoice((input_amount - 1) * 1000, "".to_string());
  758. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  759. let melt_request = MeltRequest::new(melt_quote.id, inputs, None);
  760. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  761. let response = http_client
  762. .post_melt(
  763. &PaymentMethod::Known(KnownMethod::Bolt11),
  764. melt_request.clone(),
  765. )
  766. .await;
  767. match response {
  768. Err(err) => match err {
  769. cdk::Error::MultipleUnits => (),
  770. err => {
  771. panic!("Wrong mint error returned: {}", err);
  772. }
  773. },
  774. Ok(_) => {
  775. panic!("Should not have allowed to melt with multiple units");
  776. }
  777. }
  778. }
  779. {
  780. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  781. let inputs: Proofs = vec![proofs.first().expect("There is a proof").clone()];
  782. let input_amount: u64 = inputs.total_amount().unwrap().into();
  783. let invoice = create_fake_invoice((input_amount - 1) * 1000, "".to_string());
  784. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  785. let usd_active_keyset_id = wallet_usd.fetch_active_keyset().await.unwrap().id;
  786. let usd_pre_mint = PreMintSecrets::random(
  787. usd_active_keyset_id,
  788. inputs.total_amount().unwrap() + 100.into(),
  789. &SplitTarget::None,
  790. &fee_and_amounts,
  791. )
  792. .unwrap();
  793. let pre_mint = PreMintSecrets::random(
  794. active_keyset_id,
  795. 100.into(),
  796. &SplitTarget::None,
  797. &fee_and_amounts,
  798. )
  799. .unwrap();
  800. let mut usd_outputs = usd_pre_mint.blinded_messages();
  801. let mut sat_outputs = pre_mint.blinded_messages();
  802. usd_outputs.append(&mut sat_outputs);
  803. let quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  804. let melt_request = MeltRequest::new(quote.id, inputs, Some(usd_outputs));
  805. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  806. let response = http_client
  807. .post_melt(
  808. &PaymentMethod::Known(KnownMethod::Bolt11),
  809. melt_request.clone(),
  810. )
  811. .await;
  812. match response {
  813. Err(err) => match err {
  814. cdk::Error::MultipleUnits => (),
  815. err => {
  816. panic!("Wrong mint error returned: {}", err);
  817. }
  818. },
  819. Ok(_) => {
  820. panic!("Should not have allowed to melt with multiple units");
  821. }
  822. }
  823. }
  824. }
  825. /// Tests that swapping tokens where input unit doesn't match output unit fails
  826. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  827. async fn test_fake_mint_input_output_mismatch() {
  828. let wallet = Wallet::new(
  829. MINT_URL,
  830. CurrencyUnit::Sat,
  831. Arc::new(memory::empty().await.unwrap()),
  832. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  833. None,
  834. )
  835. .expect("failed to create new wallet");
  836. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  837. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  838. let proofs = proof_streams
  839. .next()
  840. .await
  841. .expect("payment")
  842. .expect("no error");
  843. let wallet_usd = Wallet::new(
  844. MINT_URL,
  845. CurrencyUnit::Usd,
  846. Arc::new(memory::empty().await.unwrap()),
  847. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  848. None,
  849. )
  850. .expect("failed to create new usd wallet");
  851. let usd_active_keyset_id = wallet_usd.fetch_active_keyset().await.unwrap().id;
  852. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  853. let inputs = proofs;
  854. let pre_mint = PreMintSecrets::random(
  855. usd_active_keyset_id,
  856. inputs.total_amount().unwrap(),
  857. &SplitTarget::None,
  858. &fee_and_amounts,
  859. )
  860. .unwrap();
  861. let swap_request = SwapRequest::new(inputs, pre_mint.blinded_messages());
  862. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  863. let response = http_client.post_swap(swap_request.clone()).await;
  864. match response {
  865. Err(err) => match err {
  866. cdk::Error::UnitMismatch => (),
  867. err => panic!("Wrong error returned: {}", err),
  868. },
  869. Ok(_) => {
  870. panic!("Should not have allowed to mint with multiple units");
  871. }
  872. }
  873. }
  874. /// Tests that swapping tokens where output amount is greater than input amount fails
  875. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  876. async fn test_fake_mint_swap_inflated() {
  877. let wallet = Wallet::new(
  878. MINT_URL,
  879. CurrencyUnit::Sat,
  880. Arc::new(memory::empty().await.unwrap()),
  881. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  882. None,
  883. )
  884. .expect("failed to create new wallet");
  885. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  886. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  887. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  888. let proofs = proof_streams
  889. .next()
  890. .await
  891. .expect("payment")
  892. .expect("no error");
  893. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  894. let pre_mint = PreMintSecrets::random(
  895. active_keyset_id,
  896. 101.into(),
  897. &SplitTarget::None,
  898. &fee_and_amounts,
  899. )
  900. .unwrap();
  901. let swap_request = SwapRequest::new(proofs, pre_mint.blinded_messages());
  902. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  903. let response = http_client.post_swap(swap_request.clone()).await;
  904. match response {
  905. Err(err) => match err {
  906. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  907. err => {
  908. panic!("Wrong mint error returned: {}", err);
  909. }
  910. },
  911. Ok(_) => {
  912. panic!("Should not have allowed to mint with multiple units");
  913. }
  914. }
  915. }
  916. /// Tests that tokens cannot be spent again after a failed swap attempt
  917. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  918. async fn test_fake_mint_swap_spend_after_fail() {
  919. let wallet = Wallet::new(
  920. MINT_URL,
  921. CurrencyUnit::Sat,
  922. Arc::new(memory::empty().await.unwrap()),
  923. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  924. None,
  925. )
  926. .expect("failed to create new wallet");
  927. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  928. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  929. let proofs = proof_streams
  930. .next()
  931. .await
  932. .expect("payment")
  933. .expect("no error");
  934. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  935. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  936. let pre_mint = PreMintSecrets::random(
  937. active_keyset_id,
  938. 100.into(),
  939. &SplitTarget::None,
  940. &fee_and_amounts,
  941. )
  942. .unwrap();
  943. let swap_request = SwapRequest::new(proofs.clone(), pre_mint.blinded_messages());
  944. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  945. let response = http_client.post_swap(swap_request.clone()).await;
  946. assert!(response.is_ok());
  947. let pre_mint = PreMintSecrets::random(
  948. active_keyset_id,
  949. 101.into(),
  950. &SplitTarget::None,
  951. &fee_and_amounts,
  952. )
  953. .unwrap();
  954. let swap_request = SwapRequest::new(proofs.clone(), pre_mint.blinded_messages());
  955. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  956. let response = http_client.post_swap(swap_request.clone()).await;
  957. match response {
  958. Err(err) => match err {
  959. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  960. err => panic!("Wrong mint error returned expected TransactionUnbalanced, got: {err}"),
  961. },
  962. Ok(_) => panic!("Should not have allowed swap with unbalanced"),
  963. }
  964. let pre_mint = PreMintSecrets::random(
  965. active_keyset_id,
  966. 100.into(),
  967. &SplitTarget::None,
  968. &fee_and_amounts,
  969. )
  970. .unwrap();
  971. let swap_request = SwapRequest::new(proofs, pre_mint.blinded_messages());
  972. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  973. let response = http_client.post_swap(swap_request.clone()).await;
  974. match response {
  975. Err(err) => match err {
  976. cdk::Error::TokenAlreadySpent => (),
  977. err => {
  978. panic!("Wrong mint error returned: {}", err);
  979. }
  980. },
  981. Ok(_) => {
  982. panic!("Should not have allowed to mint with multiple units");
  983. }
  984. }
  985. }
  986. /// Tests that tokens cannot be melted after a failed swap attempt
  987. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  988. async fn test_fake_mint_melt_spend_after_fail() {
  989. let wallet = Wallet::new(
  990. MINT_URL,
  991. CurrencyUnit::Sat,
  992. Arc::new(memory::empty().await.unwrap()),
  993. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  994. None,
  995. )
  996. .expect("failed to create new wallet");
  997. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  998. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  999. let proofs = proof_streams
  1000. .next()
  1001. .await
  1002. .expect("payment")
  1003. .expect("no error");
  1004. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  1005. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  1006. let pre_mint = PreMintSecrets::random(
  1007. active_keyset_id,
  1008. 100.into(),
  1009. &SplitTarget::None,
  1010. &fee_and_amounts,
  1011. )
  1012. .unwrap();
  1013. let swap_request = SwapRequest::new(proofs.clone(), pre_mint.blinded_messages());
  1014. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1015. let response = http_client.post_swap(swap_request.clone()).await;
  1016. assert!(response.is_ok());
  1017. let pre_mint = PreMintSecrets::random(
  1018. active_keyset_id,
  1019. 101.into(),
  1020. &SplitTarget::None,
  1021. &fee_and_amounts,
  1022. )
  1023. .unwrap();
  1024. let swap_request = SwapRequest::new(proofs.clone(), pre_mint.blinded_messages());
  1025. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1026. let response = http_client.post_swap(swap_request.clone()).await;
  1027. match response {
  1028. Err(err) => match err {
  1029. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  1030. err => panic!("Wrong mint error returned expected TransactionUnbalanced, got: {err}"),
  1031. },
  1032. Ok(_) => panic!("Should not have allowed swap with unbalanced"),
  1033. }
  1034. let input_amount: u64 = proofs.total_amount().unwrap().into();
  1035. let invoice = create_fake_invoice((input_amount - 1) * 1000, "".to_string());
  1036. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  1037. let melt_request = MeltRequest::new(melt_quote.id, proofs, None);
  1038. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1039. let response = http_client
  1040. .post_melt(
  1041. &PaymentMethod::Known(KnownMethod::Bolt11),
  1042. melt_request.clone(),
  1043. )
  1044. .await;
  1045. match response {
  1046. Err(err) => match err {
  1047. cdk::Error::TokenAlreadySpent => (),
  1048. err => {
  1049. panic!("Wrong mint error returned: {}", err);
  1050. }
  1051. },
  1052. Ok(_) => {
  1053. panic!("Should not have allowed to melt with multiple units");
  1054. }
  1055. }
  1056. }
  1057. /// Tests that attempting to swap with duplicate proofs fails
  1058. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1059. async fn test_fake_mint_duplicate_proofs_swap() {
  1060. let wallet = Wallet::new(
  1061. MINT_URL,
  1062. CurrencyUnit::Sat,
  1063. Arc::new(memory::empty().await.unwrap()),
  1064. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1065. None,
  1066. )
  1067. .expect("failed to create new wallet");
  1068. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  1069. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1070. let proofs = proof_streams
  1071. .next()
  1072. .await
  1073. .expect("payment")
  1074. .expect("no error");
  1075. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  1076. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  1077. let inputs = vec![proofs[0].clone(), proofs[0].clone()];
  1078. let pre_mint = PreMintSecrets::random(
  1079. active_keyset_id,
  1080. inputs.total_amount().unwrap(),
  1081. &SplitTarget::None,
  1082. &fee_and_amounts,
  1083. )
  1084. .unwrap();
  1085. let swap_request = SwapRequest::new(inputs.clone(), pre_mint.blinded_messages());
  1086. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1087. let response = http_client.post_swap(swap_request.clone()).await;
  1088. match response {
  1089. Err(err) => match err {
  1090. cdk::Error::DuplicateInputs => (),
  1091. err => {
  1092. panic!(
  1093. "Wrong mint error returned, expected duplicate inputs: {}",
  1094. err
  1095. );
  1096. }
  1097. },
  1098. Ok(_) => {
  1099. panic!("Should not have allowed duplicate inputs");
  1100. }
  1101. }
  1102. let blinded_message = pre_mint.blinded_messages();
  1103. let inputs = vec![proofs[0].clone()];
  1104. let outputs = vec![blinded_message[0].clone(), blinded_message[0].clone()];
  1105. let swap_request = SwapRequest::new(inputs, outputs);
  1106. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1107. let response = http_client.post_swap(swap_request.clone()).await;
  1108. match response {
  1109. Err(err) => match err {
  1110. cdk::Error::DuplicateOutputs => (),
  1111. err => {
  1112. panic!(
  1113. "Wrong mint error returned, expected duplicate outputs: {}",
  1114. err
  1115. );
  1116. }
  1117. },
  1118. Ok(_) => {
  1119. panic!("Should not have allow duplicate inputs");
  1120. }
  1121. }
  1122. }
  1123. /// Tests that attempting to melt with duplicate proofs fails
  1124. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1125. async fn test_fake_mint_duplicate_proofs_melt() {
  1126. let wallet = Wallet::new(
  1127. MINT_URL,
  1128. CurrencyUnit::Sat,
  1129. Arc::new(memory::empty().await.unwrap()),
  1130. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1131. None,
  1132. )
  1133. .expect("failed to create new wallet");
  1134. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  1135. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1136. let proofs = proof_streams
  1137. .next()
  1138. .await
  1139. .expect("payment")
  1140. .expect("no error");
  1141. let inputs = vec![proofs[0].clone(), proofs[0].clone()];
  1142. let invoice = create_fake_invoice(7000, "".to_string());
  1143. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  1144. let melt_request = MeltRequest::new(melt_quote.id, inputs, None);
  1145. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1146. let response = http_client
  1147. .post_melt(
  1148. &PaymentMethod::Known(KnownMethod::Bolt11),
  1149. melt_request.clone(),
  1150. )
  1151. .await;
  1152. match response {
  1153. Err(err) => match err {
  1154. cdk::Error::DuplicateInputs => (),
  1155. err => {
  1156. panic!("Wrong mint error returned: {}", err);
  1157. }
  1158. },
  1159. Ok(_) => {
  1160. panic!("Should not have allow duplicate inputs");
  1161. }
  1162. }
  1163. }
  1164. /// Tests that wallet automatically recovers proofs after a failed melt operation
  1165. /// by swapping them to new proofs, preventing loss of funds
  1166. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1167. async fn test_wallet_proof_recovery_after_failed_melt() {
  1168. let wallet = Wallet::new(
  1169. MINT_URL,
  1170. CurrencyUnit::Sat,
  1171. Arc::new(memory::empty().await.unwrap()),
  1172. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1173. None,
  1174. )
  1175. .expect("failed to create new wallet");
  1176. // Mint 100 sats
  1177. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  1178. let _roof_streams = wallet
  1179. .wait_and_mint_quote(
  1180. mint_quote.clone(),
  1181. SplitTarget::default(),
  1182. None,
  1183. Duration::from_secs(1000),
  1184. )
  1185. .await;
  1186. assert_eq!(wallet.total_balance().await.unwrap(), Amount::from(100));
  1187. // Create a melt quote that will fail
  1188. let fake_description = FakeInvoiceDescription {
  1189. pay_invoice_state: MeltQuoteState::Unknown,
  1190. check_payment_state: MeltQuoteState::Unpaid,
  1191. pay_err: true,
  1192. check_err: false,
  1193. };
  1194. let invoice = create_fake_invoice(1000, serde_json::to_string(&fake_description).unwrap());
  1195. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  1196. // Attempt to melt - this should fail but trigger proof recovery
  1197. let melt_result = wallet.melt(&melt_quote.id).await;
  1198. assert!(melt_result.is_err(), "Melt should have failed");
  1199. // Verify wallet still has balance (proofs recovered)
  1200. assert_eq!(
  1201. wallet.total_balance().await.unwrap(),
  1202. Amount::from(100),
  1203. "Balance should be recovered"
  1204. );
  1205. // Verify we can still spend the recovered proofs
  1206. let valid_invoice = create_fake_invoice(7000, "".to_string());
  1207. let valid_melt_quote = wallet
  1208. .melt_quote(valid_invoice.to_string(), None)
  1209. .await
  1210. .unwrap();
  1211. let successful_melt = wallet.melt(&valid_melt_quote.id).await;
  1212. assert!(
  1213. successful_melt.is_ok(),
  1214. "Should be able to spend recovered proofs"
  1215. );
  1216. }
  1217. /// Tests that concurrent melt attempts for the same invoice result in exactly one success
  1218. ///
  1219. /// This test verifies the race condition protection: when multiple melt quotes exist for the
  1220. /// same invoice and all are attempted concurrently, only one should succeed due to
  1221. /// the FOR UPDATE locking on quotes with the same request_lookup_id.
  1222. #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
  1223. async fn test_concurrent_melt_same_invoice() {
  1224. const NUM_WALLETS: usize = 4;
  1225. // Create multiple wallets to simulate concurrent requests
  1226. let mut wallets = Vec::with_capacity(NUM_WALLETS);
  1227. for i in 0..NUM_WALLETS {
  1228. let wallet = Arc::new(
  1229. Wallet::new(
  1230. MINT_URL,
  1231. CurrencyUnit::Sat,
  1232. Arc::new(memory::empty().await.unwrap()),
  1233. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1234. None,
  1235. )
  1236. .expect(&format!("failed to create wallet {}", i)),
  1237. );
  1238. wallets.push(wallet);
  1239. }
  1240. // Mint proofs for all wallets
  1241. for (i, wallet) in wallets.iter().enumerate() {
  1242. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  1243. let mut proof_streams =
  1244. wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1245. proof_streams
  1246. .next()
  1247. .await
  1248. .expect(&format!("payment for wallet {}", i))
  1249. .expect("no error");
  1250. }
  1251. // Create a single invoice that all wallets will try to pay
  1252. let fake_description = FakeInvoiceDescription::default();
  1253. let invoice = create_fake_invoice(9000, serde_json::to_string(&fake_description).unwrap());
  1254. // All wallets create melt quotes for the same invoice
  1255. let mut melt_quotes = Vec::with_capacity(NUM_WALLETS);
  1256. for wallet in &wallets {
  1257. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  1258. melt_quotes.push(melt_quote);
  1259. }
  1260. // Verify all quotes have the same request (same invoice = same lookup_id)
  1261. for quote in &melt_quotes[1..] {
  1262. assert_eq!(
  1263. melt_quotes[0].request, quote.request,
  1264. "All quotes should be for the same invoice"
  1265. );
  1266. }
  1267. // Attempt all melts concurrently
  1268. let mut handles = Vec::with_capacity(NUM_WALLETS);
  1269. for (wallet, quote) in wallets.iter().zip(melt_quotes.iter()) {
  1270. let wallet_clone = Arc::clone(wallet);
  1271. let quote_id = quote.id.clone();
  1272. handles.push(tokio::spawn(
  1273. async move { wallet_clone.melt(&quote_id).await },
  1274. ));
  1275. }
  1276. // Collect results
  1277. let mut results = Vec::with_capacity(NUM_WALLETS);
  1278. for handle in handles {
  1279. results.push(handle.await.expect("task panicked"));
  1280. }
  1281. // Count successes and failures
  1282. let success_count = results.iter().filter(|r| r.is_ok()).count();
  1283. let failure_count = results.iter().filter(|r| r.is_err()).count();
  1284. assert_eq!(
  1285. success_count, 1,
  1286. "Expected exactly one successful melt, got {}. Results: {:?}",
  1287. success_count, results
  1288. );
  1289. assert_eq!(
  1290. failure_count,
  1291. NUM_WALLETS - 1,
  1292. "Expected {} failed melts, got {}",
  1293. NUM_WALLETS - 1,
  1294. failure_count
  1295. );
  1296. // Verify all failures were due to duplicate detection
  1297. for result in &results {
  1298. if let Err(err) = result {
  1299. let err_str = err.to_string().to_lowercase();
  1300. assert!(
  1301. err_str.contains("duplicate")
  1302. || err_str.contains("already paid")
  1303. || err_str.contains("pending"),
  1304. "Expected duplicate/already paid/pending error, got: {}",
  1305. err
  1306. );
  1307. }
  1308. }
  1309. }
  1310. /// Tests that wallet automatically recovers proofs after a failed swap operation
  1311. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1312. async fn test_wallet_proof_recovery_after_failed_swap() {
  1313. let wallet = Wallet::new(
  1314. MINT_URL,
  1315. CurrencyUnit::Sat,
  1316. Arc::new(memory::empty().await.unwrap()),
  1317. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1318. None,
  1319. )
  1320. .expect("failed to create new wallet");
  1321. // Mint 100 sats
  1322. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  1323. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1324. let initial_proofs = proof_streams
  1325. .next()
  1326. .await
  1327. .expect("payment")
  1328. .expect("no error");
  1329. let initial_ys: Vec<_> = initial_proofs.iter().map(|p| p.y().unwrap()).collect();
  1330. assert_eq!(wallet.total_balance().await.unwrap(), Amount::from(100));
  1331. let unspent_proofs = wallet.get_unspent_proofs().await.unwrap();
  1332. // Create an invalid swap by manually constructing a request that will fail
  1333. // We'll use the wallet's swap with invalid parameters to trigger a failure
  1334. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  1335. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  1336. // Create invalid swap request (requesting more than we have)
  1337. let preswap = PreMintSecrets::random(
  1338. active_keyset_id,
  1339. 1000.into(), // More than the 100 we have
  1340. &SplitTarget::default(),
  1341. &fee_and_amounts,
  1342. )
  1343. .unwrap();
  1344. let swap_request = SwapRequest::new(unspent_proofs.clone(), preswap.blinded_messages());
  1345. // Use HTTP client directly to bypass wallet's validation and trigger recovery
  1346. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1347. let response = http_client.post_swap(swap_request).await;
  1348. assert!(response.is_err(), "Swap should have failed");
  1349. // Note: The HTTP client doesn't trigger the wallet's try_proof_operation wrapper
  1350. // So we need to test through the wallet's own methods
  1351. // After the failed HTTP request, the proofs are still in the wallet's database
  1352. // Verify balance is still available after the failed operation
  1353. assert_eq!(
  1354. wallet.total_balance().await.unwrap(),
  1355. Amount::from(100),
  1356. "Balance should still be available"
  1357. );
  1358. // Verify we can perform a successful swap operation
  1359. let successful_swap = wallet
  1360. .swap(None, SplitTarget::None, unspent_proofs, None, false)
  1361. .await;
  1362. assert!(
  1363. successful_swap.is_ok(),
  1364. "Should be able to swap after failed operation"
  1365. );
  1366. // Verify the proofs were swapped to new ones
  1367. let final_proofs = wallet.get_unspent_proofs().await.unwrap();
  1368. let final_ys: Vec<_> = final_proofs.iter().map(|p| p.y().unwrap()).collect();
  1369. // The Ys should be different after the successful swap
  1370. assert!(
  1371. initial_ys.iter().any(|y| !final_ys.contains(y)),
  1372. "Proofs should have been swapped to new ones"
  1373. );
  1374. }
  1375. /// Tests that melt_proofs works correctly with proofs that are not already in the wallet's database.
  1376. /// This is similar to the receive flow where proofs come from an external source.
  1377. ///
  1378. /// Flow:
  1379. /// 1. Wallet A mints proofs (proofs ARE in Wallet A's database)
  1380. /// 2. Wallet B creates a melt quote
  1381. /// 3. Wallet B calls melt_proofs with proofs from Wallet A (proofs are NOT in Wallet B's database)
  1382. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1383. async fn test_melt_proofs_external() {
  1384. // Create sender wallet (Wallet A) and mint some proofs
  1385. let wallet_sender = Wallet::new(
  1386. MINT_URL,
  1387. CurrencyUnit::Sat,
  1388. Arc::new(memory::empty().await.unwrap()),
  1389. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1390. None,
  1391. )
  1392. .expect("failed to create sender wallet");
  1393. let mint_quote = wallet_sender.mint_quote(100.into(), None).await.unwrap();
  1394. let mut proof_streams =
  1395. wallet_sender.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1396. let proofs = proof_streams
  1397. .next()
  1398. .await
  1399. .expect("payment")
  1400. .expect("no error");
  1401. assert_eq!(proofs.total_amount().unwrap(), Amount::from(100));
  1402. // Create receiver/melter wallet (Wallet B) with a separate database
  1403. // These proofs are NOT in Wallet B's database
  1404. let wallet_melter = Wallet::new(
  1405. MINT_URL,
  1406. CurrencyUnit::Sat,
  1407. Arc::new(memory::empty().await.unwrap()),
  1408. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1409. None,
  1410. )
  1411. .expect("failed to create melter wallet");
  1412. // Verify proofs are not in the melter wallet's database
  1413. let melter_proofs = wallet_melter.get_unspent_proofs().await.unwrap();
  1414. assert!(
  1415. melter_proofs.is_empty(),
  1416. "Melter wallet should have no proofs initially"
  1417. );
  1418. // Create a fake invoice for melting
  1419. let fake_description = FakeInvoiceDescription::default();
  1420. let invoice = create_fake_invoice(9000, serde_json::to_string(&fake_description).unwrap());
  1421. // Wallet B creates a melt quote
  1422. let melt_quote = wallet_melter
  1423. .melt_quote(invoice.to_string(), None)
  1424. .await
  1425. .unwrap();
  1426. // Wallet B calls melt_proofs with external proofs (from Wallet A)
  1427. // These proofs are NOT in wallet_melter's database
  1428. let melted = wallet_melter
  1429. .melt_proofs(&melt_quote.id, proofs.clone())
  1430. .await
  1431. .unwrap();
  1432. // Verify the melt succeeded
  1433. assert_eq!(melted.amount, Amount::from(9));
  1434. assert_eq!(melted.fee_paid, 1.into());
  1435. // Verify change was returned (100 input - 9 melt amount = 91 change, minus fee reserve)
  1436. assert!(melted.change.is_some());
  1437. let change_amount = melted.change.unwrap().total_amount().unwrap();
  1438. assert!(change_amount > Amount::ZERO, "Should have received change");
  1439. // Verify the melter wallet now has the change proofs
  1440. let melter_balance = wallet_melter.total_balance().await.unwrap();
  1441. assert_eq!(melter_balance, change_amount);
  1442. // Verify a transaction was recorded
  1443. let transactions = wallet_melter
  1444. .list_transactions(Some(TransactionDirection::Outgoing))
  1445. .await
  1446. .unwrap();
  1447. assert_eq!(transactions.len(), 1);
  1448. assert_eq!(transactions[0].amount, Amount::from(9));
  1449. }
  1450. /// Tests that melt automatically performs a swap when proofs don't exactly match
  1451. /// the required amount (quote + fee_reserve + input_fee).
  1452. ///
  1453. /// This test verifies the swap-before-melt optimization:
  1454. /// 1. Mint proofs that will NOT exactly match a melt amount
  1455. /// 2. Create a melt quote for a specific amount
  1456. /// 3. Call melt() - it should automatically swap proofs to get exact denominations
  1457. /// 4. Verify the melt succeeded
  1458. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1459. async fn test_melt_with_swap_for_exact_amount() {
  1460. let wallet = Wallet::new(
  1461. MINT_URL,
  1462. CurrencyUnit::Sat,
  1463. Arc::new(memory::empty().await.unwrap()),
  1464. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1465. None,
  1466. )
  1467. .expect("failed to create new wallet");
  1468. // Mint 100 sats - this will give us proofs in standard denominations
  1469. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  1470. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1471. let proofs = proof_streams
  1472. .next()
  1473. .await
  1474. .expect("payment")
  1475. .expect("no error");
  1476. let initial_balance = wallet.total_balance().await.unwrap();
  1477. assert_eq!(initial_balance, Amount::from(100));
  1478. // Log the proof denominations we received
  1479. let proof_amounts: Vec<u64> = proofs.iter().map(|p| u64::from(p.amount)).collect();
  1480. tracing::info!("Initial proof denominations: {:?}", proof_amounts);
  1481. // Create a melt quote for an amount that likely won't match our proof denominations exactly
  1482. // Using 7 sats (7000 msats) which requires specific denominations
  1483. let fake_description = FakeInvoiceDescription::default();
  1484. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  1485. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  1486. tracing::info!(
  1487. "Melt quote: amount={}, fee_reserve={}",
  1488. melt_quote.amount,
  1489. melt_quote.fee_reserve
  1490. );
  1491. // Call melt() - this should trigger swap-before-melt if proofs don't match exactly
  1492. let melted = wallet.melt(&melt_quote.id).await.unwrap();
  1493. // Verify the melt succeeded
  1494. assert_eq!(melted.amount, Amount::from(7));
  1495. tracing::info!(
  1496. "Melt completed: amount={}, fee_paid={}",
  1497. melted.amount,
  1498. melted.fee_paid
  1499. );
  1500. // Verify final balance is correct (initial - melt_amount - fees)
  1501. let final_balance = wallet.total_balance().await.unwrap();
  1502. tracing::info!(
  1503. "Balance: initial={}, final={}, paid={}",
  1504. initial_balance,
  1505. final_balance,
  1506. melted.amount + melted.fee_paid
  1507. );
  1508. assert!(
  1509. final_balance < initial_balance,
  1510. "Balance should have decreased after melt"
  1511. );
  1512. assert_eq!(
  1513. final_balance,
  1514. initial_balance - melted.amount - melted.fee_paid,
  1515. "Final balance should be initial - amount - fees"
  1516. );
  1517. }
  1518. /// Tests that melt works correctly when proofs already exactly match the required amount.
  1519. /// In this case, no swap should be needed.
  1520. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1521. async fn test_melt_exact_proofs_no_swap_needed() {
  1522. let wallet = Wallet::new(
  1523. MINT_URL,
  1524. CurrencyUnit::Sat,
  1525. Arc::new(memory::empty().await.unwrap()),
  1526. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1527. None,
  1528. )
  1529. .expect("failed to create new wallet");
  1530. // Mint a larger amount to have more denomination options
  1531. let mint_quote = wallet.mint_quote(1000.into(), None).await.unwrap();
  1532. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1533. let _proofs = proof_streams
  1534. .next()
  1535. .await
  1536. .expect("payment")
  1537. .expect("no error");
  1538. let initial_balance = wallet.total_balance().await.unwrap();
  1539. assert_eq!(initial_balance, Amount::from(1000));
  1540. // Create a melt for a power-of-2 amount that's more likely to match existing denominations
  1541. let fake_description = FakeInvoiceDescription::default();
  1542. let invoice = create_fake_invoice(64_000, serde_json::to_string(&fake_description).unwrap()); // 64 sats
  1543. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  1544. // Melt should succeed
  1545. let melted = wallet.melt(&melt_quote.id).await.unwrap();
  1546. assert_eq!(melted.amount, Amount::from(64));
  1547. let final_balance = wallet.total_balance().await.unwrap();
  1548. assert_eq!(
  1549. final_balance,
  1550. initial_balance - melted.amount - melted.fee_paid
  1551. );
  1552. }
  1553. /// Tests the check_all_mint_quotes functionality for Bolt11 quotes
  1554. ///
  1555. /// This test verifies that:
  1556. /// 1. Paid mint quotes are automatically minted when check_all_mint_quotes is called
  1557. /// 2. The total amount returned matches the minted proofs
  1558. /// 3. Quote state is properly updated after minting
  1559. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1560. async fn test_check_all_mint_quotes_bolt11() {
  1561. let wallet = Wallet::new(
  1562. MINT_URL,
  1563. CurrencyUnit::Sat,
  1564. Arc::new(memory::empty().await.unwrap()),
  1565. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1566. None,
  1567. )
  1568. .expect("failed to create new wallet");
  1569. // Create first mint quote and pay it (using proof_stream triggers fake wallet payment)
  1570. let mint_quote_1 = wallet.mint_quote(100.into(), None).await.unwrap();
  1571. // Wait for the payment to be registered (fake wallet auto-pays)
  1572. let mut payment_stream_1 = wallet.payment_stream(&mint_quote_1);
  1573. payment_stream_1
  1574. .next()
  1575. .await
  1576. .expect("payment")
  1577. .expect("no error");
  1578. // Create second mint quote and pay it
  1579. let mint_quote_2 = wallet.mint_quote(50.into(), None).await.unwrap();
  1580. let mut payment_stream_2 = wallet.payment_stream(&mint_quote_2);
  1581. payment_stream_2
  1582. .next()
  1583. .await
  1584. .expect("payment")
  1585. .expect("no error");
  1586. // Verify no proofs have been minted yet
  1587. assert_eq!(wallet.total_balance().await.unwrap(), Amount::ZERO);
  1588. // Call check_all_mint_quotes - this should mint both paid quotes
  1589. let total_minted = wallet.check_all_mint_quotes().await.unwrap();
  1590. // Verify the total amount minted is correct (100 + 50 = 150)
  1591. assert_eq!(total_minted, Amount::from(150));
  1592. // Verify wallet balance matches
  1593. assert_eq!(wallet.total_balance().await.unwrap(), Amount::from(150));
  1594. // Calling check_all_mint_quotes again should return 0 (quotes already minted)
  1595. let second_check = wallet.check_all_mint_quotes().await.unwrap();
  1596. assert_eq!(second_check, Amount::ZERO);
  1597. }
  1598. /// Tests the get_unissued_mint_quotes wallet method
  1599. ///
  1600. /// This test verifies that:
  1601. /// 1. Unpaid quotes are included (wallet needs to check with mint)
  1602. /// 2. Paid but not issued quotes are included
  1603. /// 3. Fully issued quotes are excluded
  1604. /// 4. Only quotes for the current mint URL are returned
  1605. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1606. async fn test_get_unissued_mint_quotes_wallet() {
  1607. let wallet = Wallet::new(
  1608. MINT_URL,
  1609. CurrencyUnit::Sat,
  1610. Arc::new(memory::empty().await.unwrap()),
  1611. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1612. None,
  1613. )
  1614. .expect("failed to create new wallet");
  1615. // Create a quote but don't pay it (stays unpaid)
  1616. let unpaid_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  1617. // Create another quote and pay it but don't mint
  1618. let paid_quote = wallet.mint_quote(50.into(), None).await.unwrap();
  1619. let mut payment_stream = wallet.payment_stream(&paid_quote);
  1620. payment_stream
  1621. .next()
  1622. .await
  1623. .expect("payment")
  1624. .expect("no error");
  1625. // Create a third quote and fully mint it
  1626. let minted_quote = wallet.mint_quote(25.into(), None).await.unwrap();
  1627. let mut proof_stream = wallet.proof_stream(minted_quote.clone(), SplitTarget::default(), None);
  1628. proof_stream
  1629. .next()
  1630. .await
  1631. .expect("payment")
  1632. .expect("no error");
  1633. // Get unissued quotes
  1634. let unissued_quotes = wallet.get_unissued_mint_quotes().await.unwrap();
  1635. // Should have 2 quotes: unpaid and paid-but-not-issued
  1636. // The fully minted quote should be excluded
  1637. assert_eq!(
  1638. unissued_quotes.len(),
  1639. 2,
  1640. "Should have 2 unissued quotes (unpaid and paid-not-issued)"
  1641. );
  1642. let quote_ids: Vec<&str> = unissued_quotes.iter().map(|q| q.id.as_str()).collect();
  1643. assert!(
  1644. quote_ids.contains(&unpaid_quote.id.as_str()),
  1645. "Unpaid quote should be included"
  1646. );
  1647. assert!(
  1648. quote_ids.contains(&paid_quote.id.as_str()),
  1649. "Paid but not issued quote should be included"
  1650. );
  1651. assert!(
  1652. !quote_ids.contains(&minted_quote.id.as_str()),
  1653. "Fully minted quote should NOT be included"
  1654. );
  1655. }
  1656. /// Tests that mint quote state is properly updated after minting
  1657. ///
  1658. /// This test verifies that:
  1659. /// 1. amount_issued is updated after successful minting
  1660. /// 2. Quote state is updated correctly
  1661. /// 3. The quote is stored properly in the localstore
  1662. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1663. async fn test_mint_quote_state_updates_after_minting() {
  1664. let wallet = Wallet::new(
  1665. MINT_URL,
  1666. CurrencyUnit::Sat,
  1667. Arc::new(memory::empty().await.unwrap()),
  1668. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1669. None,
  1670. )
  1671. .expect("failed to create new wallet");
  1672. let mint_amount = Amount::from(100);
  1673. let mint_quote = wallet.mint_quote(mint_amount, None).await.unwrap();
  1674. // Get the quote from localstore before minting
  1675. let quote_before = wallet
  1676. .localstore
  1677. .get_mint_quote(&mint_quote.id)
  1678. .await
  1679. .unwrap()
  1680. .expect("Quote should exist");
  1681. // Verify initial state
  1682. assert_eq!(quote_before.amount_issued, Amount::ZERO);
  1683. // Mint the tokens using wait_and_mint_quote
  1684. let proofs = wallet
  1685. .wait_and_mint_quote(
  1686. mint_quote.clone(),
  1687. SplitTarget::default(),
  1688. None,
  1689. Duration::from_secs(60),
  1690. )
  1691. .await
  1692. .expect("minting should succeed");
  1693. let minted_amount = proofs.total_amount().unwrap();
  1694. assert_eq!(minted_amount, mint_amount);
  1695. // Check the quote is now either removed or updated in the localstore
  1696. // After minting, the quote should be removed from localstore (it's fully issued)
  1697. let quote_after = wallet
  1698. .localstore
  1699. .get_mint_quote(&mint_quote.id)
  1700. .await
  1701. .unwrap();
  1702. // The quote should either be removed or have amount_issued updated
  1703. match quote_after {
  1704. Some(quote) => {
  1705. // If still present, amount_issued should equal the minted amount
  1706. assert_eq!(
  1707. quote.amount_issued, minted_amount,
  1708. "amount_issued should be updated after minting"
  1709. );
  1710. }
  1711. None => {
  1712. // Quote was removed after being fully issued - this is also valid behavior
  1713. }
  1714. }
  1715. // Verify the unissued quotes no longer contains this quote
  1716. let unissued = wallet.get_unissued_mint_quotes().await.unwrap();
  1717. let unissued_ids: Vec<&str> = unissued.iter().map(|q| q.id.as_str()).collect();
  1718. assert!(
  1719. !unissued_ids.contains(&mint_quote.id.as_str()),
  1720. "Fully minted quote should not appear in unissued quotes"
  1721. );
  1722. }