fake_wallet.rs 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240
  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_bolt11_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
  58. .melt_quote(PaymentMethod::BOLT11, invoice.to_string(), None, None)
  59. .await
  60. .unwrap();
  61. let melt = async {
  62. let prepared = wallet
  63. .prepare_melt(&melt_quote.id, std::collections::HashMap::new())
  64. .await?;
  65. prepared.confirm().await
  66. }
  67. .await;
  68. assert!(melt.is_err());
  69. // melt failed, but there is new code to reclaim unspent proofs
  70. assert!(!wallet
  71. .localstore
  72. .get_proofs(None, None, Some(vec![State::Pending]), None)
  73. .await
  74. .unwrap()
  75. .is_empty());
  76. }
  77. /// Tests that if the pay error fails and the check returns unknown or failed,
  78. /// the input proofs should be unset as spending (returned to unspent state)
  79. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  80. async fn test_fake_melt_payment_fail() {
  81. let wallet = Wallet::new(
  82. MINT_URL,
  83. CurrencyUnit::Sat,
  84. Arc::new(memory::empty().await.unwrap()),
  85. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  86. None,
  87. )
  88. .expect("Failed to create new wallet");
  89. let mint_quote = wallet.mint_bolt11_quote(100.into(), None).await.unwrap();
  90. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  91. let _proofs = proof_streams
  92. .next()
  93. .await
  94. .expect("payment")
  95. .expect("no error");
  96. let fake_description = FakeInvoiceDescription {
  97. pay_invoice_state: MeltQuoteState::Unknown,
  98. check_payment_state: MeltQuoteState::Unknown,
  99. pay_err: true,
  100. check_err: false,
  101. };
  102. let invoice = create_fake_invoice(1000, serde_json::to_string(&fake_description).unwrap());
  103. let melt_quote = wallet
  104. .melt_quote(PaymentMethod::BOLT11, invoice.to_string(), None, None)
  105. .await
  106. .unwrap();
  107. // The melt should error at the payment invoice command
  108. let melt = async {
  109. let prepared = wallet
  110. .prepare_melt(&melt_quote.id, std::collections::HashMap::new())
  111. .await?;
  112. prepared.confirm().await
  113. }
  114. .await;
  115. assert!(melt.is_err());
  116. let fake_description = FakeInvoiceDescription {
  117. pay_invoice_state: MeltQuoteState::Failed,
  118. check_payment_state: MeltQuoteState::Failed,
  119. pay_err: true,
  120. check_err: false,
  121. };
  122. let invoice = create_fake_invoice(1000, serde_json::to_string(&fake_description).unwrap());
  123. let melt_quote = wallet
  124. .melt_quote(PaymentMethod::BOLT11, invoice.to_string(), None, None)
  125. .await
  126. .unwrap();
  127. // The melt should error at the payment invoice command
  128. let melt = async {
  129. let prepared = wallet
  130. .prepare_melt(&melt_quote.id, std::collections::HashMap::new())
  131. .await?;
  132. prepared.confirm().await
  133. }
  134. .await;
  135. assert!(melt.is_err());
  136. let wallet_bal = wallet.total_balance().await.unwrap();
  137. assert_eq!(wallet_bal, 100.into());
  138. }
  139. /// Tests that when both the pay_invoice and check_invoice both fail,
  140. /// the proofs should remain in pending state
  141. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  142. async fn test_fake_melt_payment_fail_and_check() {
  143. let wallet = Wallet::new(
  144. MINT_URL,
  145. CurrencyUnit::Sat,
  146. Arc::new(memory::empty().await.unwrap()),
  147. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  148. None,
  149. )
  150. .expect("Failed to create new wallet");
  151. let mint_quote = wallet.mint_bolt11_quote(100.into(), None).await.unwrap();
  152. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  153. let _proofs = proof_streams
  154. .next()
  155. .await
  156. .expect("payment")
  157. .expect("no error");
  158. let fake_description = FakeInvoiceDescription {
  159. pay_invoice_state: MeltQuoteState::Unknown,
  160. check_payment_state: MeltQuoteState::Unknown,
  161. pay_err: true,
  162. check_err: true,
  163. };
  164. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  165. let melt_quote = wallet
  166. .melt_quote(PaymentMethod::BOLT11, invoice.to_string(), None, None)
  167. .await
  168. .unwrap();
  169. // The melt should error at the payment invoice command
  170. let melt = async {
  171. let prepared = wallet
  172. .prepare_melt(&melt_quote.id, std::collections::HashMap::new())
  173. .await?;
  174. prepared.confirm().await
  175. }
  176. .await;
  177. assert!(melt.is_err());
  178. assert!(!wallet
  179. .localstore
  180. .get_proofs(None, None, Some(vec![State::Pending]), None)
  181. .await
  182. .unwrap()
  183. .is_empty());
  184. }
  185. /// Tests that when the ln backend returns a failed status but does not error,
  186. /// the mint should do a second check, then remove proofs from pending state
  187. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  188. async fn test_fake_melt_payment_return_fail_status() {
  189. let wallet = Wallet::new(
  190. MINT_URL,
  191. CurrencyUnit::Sat,
  192. Arc::new(memory::empty().await.unwrap()),
  193. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  194. None,
  195. )
  196. .expect("Failed to create new wallet");
  197. let mint_quote = wallet.mint_bolt11_quote(100.into(), None).await.unwrap();
  198. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  199. let _proofs = proof_streams
  200. .next()
  201. .await
  202. .expect("payment")
  203. .expect("no error");
  204. let fake_description = FakeInvoiceDescription {
  205. pay_invoice_state: MeltQuoteState::Failed,
  206. check_payment_state: MeltQuoteState::Failed,
  207. pay_err: false,
  208. check_err: false,
  209. };
  210. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  211. let melt_quote = wallet
  212. .melt_quote(PaymentMethod::BOLT11, invoice.to_string(), None, None)
  213. .await
  214. .unwrap();
  215. // The melt should error at the payment invoice command
  216. let melt = async {
  217. let prepared = wallet
  218. .prepare_melt(&melt_quote.id, std::collections::HashMap::new())
  219. .await?;
  220. prepared.confirm().await
  221. }
  222. .await;
  223. assert!(melt.is_err());
  224. wallet.check_all_pending_proofs().await.unwrap();
  225. let pending = wallet
  226. .localstore
  227. .get_proofs(None, None, Some(vec![State::Pending]), None)
  228. .await
  229. .unwrap();
  230. assert!(pending.is_empty());
  231. let fake_description = FakeInvoiceDescription {
  232. pay_invoice_state: MeltQuoteState::Unknown,
  233. check_payment_state: MeltQuoteState::Unknown,
  234. pay_err: false,
  235. check_err: false,
  236. };
  237. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  238. let melt_quote = wallet
  239. .melt_quote(PaymentMethod::BOLT11, invoice.to_string(), None, None)
  240. .await
  241. .unwrap();
  242. // The melt should error at the payment invoice command
  243. let melt = async {
  244. let prepared = wallet
  245. .prepare_melt(&melt_quote.id, std::collections::HashMap::new())
  246. .await?;
  247. prepared.confirm().await
  248. }
  249. .await;
  250. assert!(melt.is_err());
  251. wallet.check_all_pending_proofs().await.unwrap();
  252. assert!(wallet
  253. .localstore
  254. .get_proofs(None, None, Some(vec![State::Pending]), None)
  255. .await
  256. .unwrap()
  257. .is_empty());
  258. }
  259. /// Tests that when the ln backend returns an error with unknown status,
  260. /// the mint should do a second check, then remove proofs from pending state
  261. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  262. async fn test_fake_melt_payment_error_unknown() {
  263. let wallet = Wallet::new(
  264. MINT_URL,
  265. CurrencyUnit::Sat,
  266. Arc::new(memory::empty().await.unwrap()),
  267. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  268. None,
  269. )
  270. .unwrap();
  271. let mint_quote = wallet.mint_bolt11_quote(100.into(), None).await.unwrap();
  272. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  273. let _proofs = proof_streams
  274. .next()
  275. .await
  276. .expect("payment")
  277. .expect("no error");
  278. let fake_description = FakeInvoiceDescription {
  279. pay_invoice_state: MeltQuoteState::Failed,
  280. check_payment_state: MeltQuoteState::Unknown,
  281. pay_err: true,
  282. check_err: false,
  283. };
  284. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  285. let melt_quote = wallet
  286. .melt_quote(PaymentMethod::BOLT11, invoice.to_string(), None, None)
  287. .await
  288. .unwrap();
  289. // The melt should error at the payment invoice command
  290. let melt = async {
  291. let prepared = wallet
  292. .prepare_melt(&melt_quote.id, std::collections::HashMap::new())
  293. .await?;
  294. prepared.confirm().await
  295. }
  296. .await;
  297. assert!(melt.is_err());
  298. let fake_description = FakeInvoiceDescription {
  299. pay_invoice_state: MeltQuoteState::Unknown,
  300. check_payment_state: MeltQuoteState::Unknown,
  301. pay_err: true,
  302. check_err: false,
  303. };
  304. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  305. let melt_quote = wallet
  306. .melt_quote(PaymentMethod::BOLT11, invoice.to_string(), None, None)
  307. .await
  308. .unwrap();
  309. // The melt should error at the payment invoice command
  310. let melt = async {
  311. let prepared = wallet
  312. .prepare_melt(&melt_quote.id, std::collections::HashMap::new())
  313. .await?;
  314. prepared.confirm().await
  315. }
  316. .await;
  317. assert!(melt.is_err());
  318. assert!(wallet
  319. .localstore
  320. .get_proofs(None, None, Some(vec![State::Pending]), None)
  321. .await
  322. .unwrap()
  323. .is_empty());
  324. }
  325. /// Tests that when the ln backend returns an error but the second check returns paid,
  326. /// proofs should remain in pending state
  327. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  328. async fn test_fake_melt_payment_err_paid() {
  329. let wallet = Wallet::new(
  330. MINT_URL,
  331. CurrencyUnit::Sat,
  332. Arc::new(memory::empty().await.unwrap()),
  333. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  334. None,
  335. )
  336. .expect("Failed to create new wallet");
  337. let mint_quote = wallet.mint_bolt11_quote(100.into(), None).await.unwrap();
  338. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  339. let _proofs = proof_streams
  340. .next()
  341. .await
  342. .expect("payment")
  343. .expect("no error");
  344. let old_balance = wallet.total_balance().await.expect("balance");
  345. let fake_description = FakeInvoiceDescription {
  346. pay_invoice_state: MeltQuoteState::Failed,
  347. check_payment_state: MeltQuoteState::Paid,
  348. pay_err: true,
  349. check_err: false,
  350. };
  351. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  352. let melt_quote = wallet
  353. .melt_quote(PaymentMethod::BOLT11, invoice.to_string(), None, None)
  354. .await
  355. .unwrap();
  356. // The melt should complete successfully
  357. let prepared = wallet
  358. .prepare_melt(&melt_quote.id, std::collections::HashMap::new())
  359. .await
  360. .unwrap();
  361. let melt = prepared.confirm().await.unwrap();
  362. assert!(melt.fee_paid() == Amount::ZERO);
  363. assert!(melt.amount() == Amount::from(7));
  364. // melt failed, but there is new code to reclaim unspent proofs
  365. assert_eq!(
  366. old_balance - melt.amount(),
  367. wallet.total_balance().await.expect("new balance")
  368. );
  369. assert!(wallet
  370. .localstore
  371. .get_proofs(None, None, Some(vec![State::Pending]), None)
  372. .await
  373. .unwrap()
  374. .is_empty());
  375. }
  376. /// Tests that change outputs in a melt quote are correctly handled
  377. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  378. async fn test_fake_melt_change_in_quote() {
  379. let wallet = Wallet::new(
  380. MINT_URL,
  381. CurrencyUnit::Sat,
  382. Arc::new(memory::empty().await.unwrap()),
  383. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  384. None,
  385. )
  386. .expect("Failed to create new wallet");
  387. let mint_quote = wallet.mint_bolt11_quote(100.into(), None).await.unwrap();
  388. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  389. let _proofs = proof_streams
  390. .next()
  391. .await
  392. .expect("payment")
  393. .expect("no error");
  394. let transaction = wallet
  395. .list_transactions(Some(TransactionDirection::Incoming))
  396. .await
  397. .unwrap()
  398. .pop()
  399. .expect("No transaction found");
  400. assert_eq!(wallet.mint_url, transaction.mint_url);
  401. assert_eq!(TransactionDirection::Incoming, transaction.direction);
  402. assert_eq!(Amount::from(100), transaction.amount);
  403. assert_eq!(Amount::from(0), transaction.fee);
  404. assert_eq!(CurrencyUnit::Sat, transaction.unit);
  405. let fake_description = FakeInvoiceDescription::default();
  406. let invoice = create_fake_invoice(9000, serde_json::to_string(&fake_description).unwrap());
  407. let proofs = wallet.get_unspent_proofs().await.unwrap();
  408. let melt_quote = wallet
  409. .melt_quote(PaymentMethod::BOLT11, invoice.to_string(), None, None)
  410. .await
  411. .unwrap();
  412. let keyset = wallet.fetch_active_keyset().await.unwrap();
  413. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  414. let premint_secrets = PreMintSecrets::random(
  415. keyset.id,
  416. 100.into(),
  417. &SplitTarget::default(),
  418. &fee_and_amounts,
  419. )
  420. .unwrap();
  421. let client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  422. let melt_request = MeltRequest::new(
  423. melt_quote.id.clone(),
  424. proofs.clone(),
  425. Some(premint_secrets.blinded_messages()),
  426. );
  427. let melt_response = client
  428. .post_melt(&PaymentMethod::Known(KnownMethod::Bolt11), melt_request)
  429. .await
  430. .unwrap();
  431. assert!(melt_response.change.is_some());
  432. let check = client.get_melt_quote_status(&melt_quote.id).await.unwrap();
  433. let mut melt_change = melt_response.change.unwrap();
  434. melt_change.sort_by(|a, b| a.amount.cmp(&b.amount));
  435. let mut check = check.change.unwrap();
  436. check.sort_by(|a, b| a.amount.cmp(&b.amount));
  437. assert_eq!(melt_change, check);
  438. }
  439. /// Tests minting tokens with a valid witness signature
  440. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  441. async fn test_fake_mint_with_witness() {
  442. let wallet = Wallet::new(
  443. MINT_URL,
  444. CurrencyUnit::Sat,
  445. Arc::new(memory::empty().await.unwrap()),
  446. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  447. None,
  448. )
  449. .expect("failed to create new wallet");
  450. let mint_quote = wallet.mint_bolt11_quote(100.into(), None).await.unwrap();
  451. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  452. let proofs = proof_streams
  453. .next()
  454. .await
  455. .expect("payment")
  456. .expect("no error");
  457. let mint_amount = proofs.total_amount().unwrap();
  458. assert!(mint_amount == 100.into());
  459. }
  460. /// Tests that minting without a witness signature fails with the correct error
  461. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  462. async fn test_fake_mint_without_witness() {
  463. let wallet = Wallet::new(
  464. MINT_URL,
  465. CurrencyUnit::Sat,
  466. Arc::new(memory::empty().await.unwrap()),
  467. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  468. None,
  469. )
  470. .expect("failed to create new wallet");
  471. let mint_quote = wallet.mint_bolt11_quote(100.into(), None).await.unwrap();
  472. let mut payment_streams = wallet.payment_stream(&mint_quote);
  473. payment_streams
  474. .next()
  475. .await
  476. .expect("payment")
  477. .expect("no error");
  478. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  479. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  480. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  481. let premint_secrets = PreMintSecrets::random(
  482. active_keyset_id,
  483. 100.into(),
  484. &SplitTarget::default(),
  485. &fee_and_amounts,
  486. )
  487. .unwrap();
  488. let request = MintRequest {
  489. quote: mint_quote.id,
  490. outputs: premint_secrets.blinded_messages(),
  491. signature: None,
  492. };
  493. let response = http_client
  494. .post_mint(&PaymentMethod::Known(KnownMethod::Bolt11), request.clone())
  495. .await;
  496. match response {
  497. Err(cdk::error::Error::SignatureMissingOrInvalid) => {} //pass
  498. Err(err) => panic!("Wrong mint response for minting without witness: {}", err),
  499. Ok(_) => panic!("Minting should not have succeed without a witness"),
  500. }
  501. }
  502. /// Tests that minting with an incorrect witness signature fails with the correct error
  503. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  504. async fn test_fake_mint_with_wrong_witness() {
  505. let wallet = Wallet::new(
  506. MINT_URL,
  507. CurrencyUnit::Sat,
  508. Arc::new(memory::empty().await.unwrap()),
  509. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  510. None,
  511. )
  512. .expect("failed to create new wallet");
  513. let mint_quote = wallet.mint_bolt11_quote(100.into(), None).await.unwrap();
  514. let mut payment_streams = wallet.payment_stream(&mint_quote);
  515. payment_streams
  516. .next()
  517. .await
  518. .expect("payment")
  519. .expect("no error");
  520. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  521. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  522. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  523. let premint_secrets = PreMintSecrets::random(
  524. active_keyset_id,
  525. 100.into(),
  526. &SplitTarget::default(),
  527. &fee_and_amounts,
  528. )
  529. .unwrap();
  530. let mut request = MintRequest {
  531. quote: mint_quote.id,
  532. outputs: premint_secrets.blinded_messages(),
  533. signature: None,
  534. };
  535. let secret_key = SecretKey::generate();
  536. request
  537. .sign(secret_key)
  538. .expect("failed to sign the mint request");
  539. let response = http_client
  540. .post_mint(&PaymentMethod::Known(KnownMethod::Bolt11), request.clone())
  541. .await;
  542. match response {
  543. Err(cdk::error::Error::SignatureMissingOrInvalid) => {} //pass
  544. Err(err) => panic!("Wrong mint response for minting without witness: {}", err),
  545. Ok(_) => panic!("Minting should not have succeed without a witness"),
  546. }
  547. }
  548. /// Tests that attempting to mint more tokens than allowed by the quote fails
  549. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  550. async fn test_fake_mint_inflated() {
  551. let wallet = Wallet::new(
  552. MINT_URL,
  553. CurrencyUnit::Sat,
  554. Arc::new(memory::empty().await.unwrap()),
  555. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  556. None,
  557. )
  558. .expect("failed to create new wallet");
  559. let mint_quote = wallet.mint_bolt11_quote(100.into(), None).await.unwrap();
  560. let mut payment_streams = wallet.payment_stream(&mint_quote);
  561. payment_streams
  562. .next()
  563. .await
  564. .expect("payment")
  565. .expect("no error");
  566. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  567. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  568. let pre_mint = PreMintSecrets::random(
  569. active_keyset_id,
  570. 500.into(),
  571. &SplitTarget::None,
  572. &fee_and_amounts,
  573. )
  574. .unwrap();
  575. let quote_info = wallet
  576. .localstore
  577. .get_mint_quote(&mint_quote.id)
  578. .await
  579. .unwrap()
  580. .expect("there is a quote");
  581. let mut mint_request = MintRequest {
  582. quote: mint_quote.id,
  583. outputs: pre_mint.blinded_messages(),
  584. signature: None,
  585. };
  586. if let Some(secret_key) = quote_info.secret_key {
  587. mint_request
  588. .sign(secret_key)
  589. .expect("failed to sign the mint request");
  590. }
  591. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  592. let response = http_client
  593. .post_mint(
  594. &PaymentMethod::Known(KnownMethod::Bolt11),
  595. mint_request.clone(),
  596. )
  597. .await;
  598. match response {
  599. Err(err) => match err {
  600. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  601. err => {
  602. panic!("Wrong mint error returned: {}", err);
  603. }
  604. },
  605. Ok(_) => {
  606. panic!("Should not have allowed second payment");
  607. }
  608. }
  609. }
  610. /// Tests that attempting to mint with multiple currency units in the same request fails
  611. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  612. async fn test_fake_mint_multiple_units() {
  613. let wallet = Wallet::new(
  614. MINT_URL,
  615. CurrencyUnit::Sat,
  616. Arc::new(memory::empty().await.unwrap()),
  617. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  618. None,
  619. )
  620. .expect("failed to create new wallet");
  621. let mint_quote = wallet.mint_bolt11_quote(100.into(), None).await.unwrap();
  622. let mut payment_streams = wallet.payment_stream(&mint_quote);
  623. payment_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. let pre_mint = PreMintSecrets::random(
  631. active_keyset_id,
  632. 50.into(),
  633. &SplitTarget::None,
  634. &fee_and_amounts,
  635. )
  636. .unwrap();
  637. let wallet_usd = Wallet::new(
  638. MINT_URL,
  639. CurrencyUnit::Usd,
  640. Arc::new(memory::empty().await.unwrap()),
  641. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  642. None,
  643. )
  644. .expect("failed to create new wallet");
  645. let active_keyset_id = wallet_usd.fetch_active_keyset().await.unwrap().id;
  646. let usd_pre_mint = PreMintSecrets::random(
  647. active_keyset_id,
  648. 50.into(),
  649. &SplitTarget::None,
  650. &fee_and_amounts,
  651. )
  652. .unwrap();
  653. let quote_info = wallet
  654. .localstore
  655. .get_mint_quote(&mint_quote.id)
  656. .await
  657. .unwrap()
  658. .expect("there is a quote");
  659. let mut sat_outputs = pre_mint.blinded_messages();
  660. let mut usd_outputs = usd_pre_mint.blinded_messages();
  661. sat_outputs.append(&mut usd_outputs);
  662. let mut mint_request = MintRequest {
  663. quote: mint_quote.id,
  664. outputs: sat_outputs,
  665. signature: None,
  666. };
  667. if let Some(secret_key) = quote_info.secret_key {
  668. mint_request
  669. .sign(secret_key)
  670. .expect("failed to sign the mint request");
  671. }
  672. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  673. let response = http_client
  674. .post_mint(
  675. &PaymentMethod::Known(KnownMethod::Bolt11),
  676. mint_request.clone(),
  677. )
  678. .await;
  679. match response {
  680. Err(err) => match err {
  681. cdk::Error::MultipleUnits => (),
  682. err => {
  683. panic!("Wrong mint error returned: {}", err);
  684. }
  685. },
  686. Ok(_) => {
  687. panic!("Should not have allowed to mint with multiple units");
  688. }
  689. }
  690. }
  691. /// Tests that attempting to swap tokens with multiple currency units fails
  692. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  693. async fn test_fake_mint_multiple_unit_swap() {
  694. let wallet = Wallet::new(
  695. MINT_URL,
  696. CurrencyUnit::Sat,
  697. Arc::new(memory::empty().await.unwrap()),
  698. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  699. None,
  700. )
  701. .expect("failed to create new wallet");
  702. wallet.refresh_keysets().await.unwrap();
  703. let mint_quote = wallet.mint_bolt11_quote(100.into(), None).await.unwrap();
  704. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  705. let proofs = proof_streams
  706. .next()
  707. .await
  708. .expect("payment")
  709. .expect("no error");
  710. let wallet_usd = Wallet::new(
  711. MINT_URL,
  712. CurrencyUnit::Usd,
  713. Arc::new(memory::empty().await.unwrap()),
  714. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  715. None,
  716. )
  717. .expect("failed to create usd wallet");
  718. wallet_usd.refresh_keysets().await.unwrap();
  719. let mint_quote = wallet_usd
  720. .mint_bolt11_quote(100.into(), None)
  721. .await
  722. .unwrap();
  723. let mut proof_streams =
  724. wallet_usd.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  725. let usd_proofs = proof_streams
  726. .next()
  727. .await
  728. .expect("payment")
  729. .expect("no error");
  730. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  731. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  732. {
  733. let inputs: Proofs = vec![
  734. proofs.first().expect("There is a proof").clone(),
  735. usd_proofs.first().expect("There is a proof").clone(),
  736. ];
  737. let pre_mint = PreMintSecrets::random(
  738. active_keyset_id,
  739. inputs.total_amount().unwrap(),
  740. &SplitTarget::None,
  741. &fee_and_amounts,
  742. )
  743. .unwrap();
  744. let swap_request = SwapRequest::new(inputs, pre_mint.blinded_messages());
  745. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  746. let response = http_client.post_swap(swap_request.clone()).await;
  747. match response {
  748. Err(err) => match err {
  749. cdk::Error::MultipleUnits => (),
  750. err => {
  751. panic!("Wrong mint error returned: {}", err);
  752. }
  753. },
  754. Ok(_) => {
  755. panic!("Should not have allowed to mint with multiple units");
  756. }
  757. }
  758. }
  759. {
  760. let usd_active_keyset_id = wallet_usd.fetch_active_keyset().await.unwrap().id;
  761. let inputs: Proofs = proofs.into_iter().take(2).collect();
  762. let total_inputs = inputs.total_amount().unwrap();
  763. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  764. let half = total_inputs / 2.into();
  765. let usd_pre_mint = PreMintSecrets::random(
  766. usd_active_keyset_id,
  767. half,
  768. &SplitTarget::None,
  769. &fee_and_amounts,
  770. )
  771. .unwrap();
  772. let pre_mint = PreMintSecrets::random(
  773. active_keyset_id,
  774. total_inputs - half,
  775. &SplitTarget::None,
  776. &fee_and_amounts,
  777. )
  778. .unwrap();
  779. let mut usd_outputs = usd_pre_mint.blinded_messages();
  780. let mut sat_outputs = pre_mint.blinded_messages();
  781. usd_outputs.append(&mut sat_outputs);
  782. let swap_request = SwapRequest::new(inputs, usd_outputs);
  783. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  784. let response = http_client.post_swap(swap_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 mint with multiple units");
  794. }
  795. }
  796. }
  797. }
  798. /// Tests that attempting to melt tokens with multiple currency units fails
  799. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  800. async fn test_fake_mint_multiple_unit_melt() {
  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_bolt11_quote(100.into(), None).await.unwrap();
  810. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  811. let mut proofs = proof_streams
  812. .next()
  813. .await
  814. .expect("payment")
  815. .expect("no error");
  816. println!("Minted sat");
  817. let wallet_usd = Wallet::new(
  818. MINT_URL,
  819. CurrencyUnit::Usd,
  820. Arc::new(memory::empty().await.unwrap()),
  821. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  822. None,
  823. )
  824. .expect("failed to create new wallet");
  825. let mint_quote = wallet_usd
  826. .mint_bolt11_quote(100.into(), None)
  827. .await
  828. .unwrap();
  829. println!("Minted quote usd");
  830. let mut proof_streams =
  831. wallet_usd.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  832. let mut usd_proofs = proof_streams
  833. .next()
  834. .await
  835. .expect("payment")
  836. .expect("no error");
  837. usd_proofs.reverse();
  838. proofs.reverse();
  839. {
  840. let inputs: Proofs = vec![
  841. proofs.first().expect("There is a proof").clone(),
  842. usd_proofs.first().expect("There is a proof").clone(),
  843. ];
  844. let input_amount: u64 = inputs.total_amount().unwrap().into();
  845. let invoice = create_fake_invoice((input_amount - 1) * 1000, "".to_string());
  846. let melt_quote = wallet
  847. .melt_quote(PaymentMethod::BOLT11, invoice.to_string(), None, None)
  848. .await
  849. .unwrap();
  850. let melt_request = MeltRequest::new(melt_quote.id, inputs, None);
  851. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  852. let response = http_client
  853. .post_melt(
  854. &PaymentMethod::Known(KnownMethod::Bolt11),
  855. melt_request.clone(),
  856. )
  857. .await;
  858. match response {
  859. Err(err) => match err {
  860. cdk::Error::MultipleUnits => (),
  861. err => {
  862. panic!("Wrong mint error returned: {}", err);
  863. }
  864. },
  865. Ok(_) => {
  866. panic!("Should not have allowed to melt with multiple units");
  867. }
  868. }
  869. }
  870. {
  871. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  872. let inputs: Proofs = vec![proofs.first().expect("There is a proof").clone()];
  873. let input_amount: u64 = inputs.total_amount().unwrap().into();
  874. let invoice = create_fake_invoice((input_amount - 1) * 1000, "".to_string());
  875. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  876. let usd_active_keyset_id = wallet_usd.fetch_active_keyset().await.unwrap().id;
  877. let usd_pre_mint = PreMintSecrets::random(
  878. usd_active_keyset_id,
  879. inputs.total_amount().unwrap() + 100.into(),
  880. &SplitTarget::None,
  881. &fee_and_amounts,
  882. )
  883. .unwrap();
  884. let pre_mint = PreMintSecrets::random(
  885. active_keyset_id,
  886. 100.into(),
  887. &SplitTarget::None,
  888. &fee_and_amounts,
  889. )
  890. .unwrap();
  891. let mut usd_outputs = usd_pre_mint.blinded_messages();
  892. let mut sat_outputs = pre_mint.blinded_messages();
  893. usd_outputs.append(&mut sat_outputs);
  894. let quote = wallet
  895. .melt_quote(PaymentMethod::BOLT11, invoice.to_string(), None, None)
  896. .await
  897. .unwrap();
  898. let melt_request = MeltRequest::new(quote.id, inputs, Some(usd_outputs));
  899. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  900. let response = http_client
  901. .post_melt(
  902. &PaymentMethod::Known(KnownMethod::Bolt11),
  903. melt_request.clone(),
  904. )
  905. .await;
  906. match response {
  907. Err(err) => match err {
  908. cdk::Error::MultipleUnits => (),
  909. err => {
  910. panic!("Wrong mint error returned: {}", err);
  911. }
  912. },
  913. Ok(_) => {
  914. panic!("Should not have allowed to melt with multiple units");
  915. }
  916. }
  917. }
  918. }
  919. /// Tests that swapping tokens where input unit doesn't match output unit fails
  920. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  921. async fn test_fake_mint_input_output_mismatch() {
  922. let wallet = Wallet::new(
  923. MINT_URL,
  924. CurrencyUnit::Sat,
  925. Arc::new(memory::empty().await.unwrap()),
  926. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  927. None,
  928. )
  929. .expect("failed to create new wallet");
  930. let mint_quote = wallet.mint_bolt11_quote(100.into(), None).await.unwrap();
  931. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  932. let proofs = proof_streams
  933. .next()
  934. .await
  935. .expect("payment")
  936. .expect("no error");
  937. let wallet_usd = Wallet::new(
  938. MINT_URL,
  939. CurrencyUnit::Usd,
  940. Arc::new(memory::empty().await.unwrap()),
  941. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  942. None,
  943. )
  944. .expect("failed to create new usd wallet");
  945. let usd_active_keyset_id = wallet_usd.fetch_active_keyset().await.unwrap().id;
  946. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  947. let inputs = proofs;
  948. let pre_mint = PreMintSecrets::random(
  949. usd_active_keyset_id,
  950. inputs.total_amount().unwrap(),
  951. &SplitTarget::None,
  952. &fee_and_amounts,
  953. )
  954. .unwrap();
  955. let swap_request = SwapRequest::new(inputs, pre_mint.blinded_messages());
  956. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  957. let response = http_client.post_swap(swap_request.clone()).await;
  958. match response {
  959. Err(err) => match err {
  960. cdk::Error::UnitMismatch => (),
  961. err => panic!("Wrong error returned: {}", err),
  962. },
  963. Ok(_) => {
  964. panic!("Should not have allowed to mint with multiple units");
  965. }
  966. }
  967. }
  968. /// Tests that swapping tokens where output amount is greater than input amount fails
  969. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  970. async fn test_fake_mint_swap_inflated() {
  971. let wallet = Wallet::new(
  972. MINT_URL,
  973. CurrencyUnit::Sat,
  974. Arc::new(memory::empty().await.unwrap()),
  975. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  976. None,
  977. )
  978. .expect("failed to create new wallet");
  979. let mint_quote = wallet.mint_bolt11_quote(100.into(), None).await.unwrap();
  980. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  981. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  982. let proofs = proof_streams
  983. .next()
  984. .await
  985. .expect("payment")
  986. .expect("no error");
  987. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  988. let pre_mint = PreMintSecrets::random(
  989. active_keyset_id,
  990. 101.into(),
  991. &SplitTarget::None,
  992. &fee_and_amounts,
  993. )
  994. .unwrap();
  995. let swap_request = SwapRequest::new(proofs, pre_mint.blinded_messages());
  996. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  997. let response = http_client.post_swap(swap_request.clone()).await;
  998. match response {
  999. Err(err) => match err {
  1000. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  1001. err => {
  1002. panic!("Wrong mint error returned: {}", err);
  1003. }
  1004. },
  1005. Ok(_) => {
  1006. panic!("Should not have allowed to mint with multiple units");
  1007. }
  1008. }
  1009. }
  1010. /// Tests that tokens cannot be spent again after a failed swap attempt
  1011. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1012. async fn test_fake_mint_swap_spend_after_fail() {
  1013. let wallet = Wallet::new(
  1014. MINT_URL,
  1015. CurrencyUnit::Sat,
  1016. Arc::new(memory::empty().await.unwrap()),
  1017. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1018. None,
  1019. )
  1020. .expect("failed to create new wallet");
  1021. let mint_quote = wallet.mint_bolt11_quote(100.into(), None).await.unwrap();
  1022. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1023. let proofs = proof_streams
  1024. .next()
  1025. .await
  1026. .expect("payment")
  1027. .expect("no error");
  1028. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  1029. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  1030. let pre_mint = PreMintSecrets::random(
  1031. active_keyset_id,
  1032. 100.into(),
  1033. &SplitTarget::None,
  1034. &fee_and_amounts,
  1035. )
  1036. .unwrap();
  1037. let swap_request = SwapRequest::new(proofs.clone(), pre_mint.blinded_messages());
  1038. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1039. let response = http_client.post_swap(swap_request.clone()).await;
  1040. assert!(response.is_ok());
  1041. let pre_mint = PreMintSecrets::random(
  1042. active_keyset_id,
  1043. 101.into(),
  1044. &SplitTarget::None,
  1045. &fee_and_amounts,
  1046. )
  1047. .unwrap();
  1048. let swap_request = SwapRequest::new(proofs.clone(), pre_mint.blinded_messages());
  1049. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1050. let response = http_client.post_swap(swap_request.clone()).await;
  1051. match response {
  1052. Err(err) => match err {
  1053. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  1054. err => panic!("Wrong mint error returned expected TransactionUnbalanced, got: {err}"),
  1055. },
  1056. Ok(_) => panic!("Should not have allowed swap with unbalanced"),
  1057. }
  1058. let pre_mint = PreMintSecrets::random(
  1059. active_keyset_id,
  1060. 100.into(),
  1061. &SplitTarget::None,
  1062. &fee_and_amounts,
  1063. )
  1064. .unwrap();
  1065. let swap_request = SwapRequest::new(proofs, pre_mint.blinded_messages());
  1066. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1067. let response = http_client.post_swap(swap_request.clone()).await;
  1068. match response {
  1069. Err(err) => match err {
  1070. cdk::Error::TokenAlreadySpent => (),
  1071. err => {
  1072. panic!("Wrong mint error returned: {}", err);
  1073. }
  1074. },
  1075. Ok(_) => {
  1076. panic!("Should not have allowed to mint with multiple units");
  1077. }
  1078. }
  1079. }
  1080. /// Tests that tokens cannot be melted after a failed swap attempt
  1081. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1082. async fn test_fake_mint_melt_spend_after_fail() {
  1083. let wallet = Wallet::new(
  1084. MINT_URL,
  1085. CurrencyUnit::Sat,
  1086. Arc::new(memory::empty().await.unwrap()),
  1087. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1088. None,
  1089. )
  1090. .expect("failed to create new wallet");
  1091. let mint_quote = wallet.mint_bolt11_quote(100.into(), None).await.unwrap();
  1092. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1093. let proofs = proof_streams
  1094. .next()
  1095. .await
  1096. .expect("payment")
  1097. .expect("no error");
  1098. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  1099. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  1100. let pre_mint = PreMintSecrets::random(
  1101. active_keyset_id,
  1102. 100.into(),
  1103. &SplitTarget::None,
  1104. &fee_and_amounts,
  1105. )
  1106. .unwrap();
  1107. let swap_request = SwapRequest::new(proofs.clone(), pre_mint.blinded_messages());
  1108. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1109. let response = http_client.post_swap(swap_request.clone()).await;
  1110. assert!(response.is_ok());
  1111. let pre_mint = PreMintSecrets::random(
  1112. active_keyset_id,
  1113. 101.into(),
  1114. &SplitTarget::None,
  1115. &fee_and_amounts,
  1116. )
  1117. .unwrap();
  1118. let swap_request = SwapRequest::new(proofs.clone(), pre_mint.blinded_messages());
  1119. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1120. let response = http_client.post_swap(swap_request.clone()).await;
  1121. match response {
  1122. Err(err) => match err {
  1123. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  1124. err => panic!("Wrong mint error returned expected TransactionUnbalanced, got: {err}"),
  1125. },
  1126. Ok(_) => panic!("Should not have allowed swap with unbalanced"),
  1127. }
  1128. let input_amount: u64 = proofs.total_amount().unwrap().into();
  1129. let invoice = create_fake_invoice((input_amount - 1) * 1000, "".to_string());
  1130. let melt_quote = wallet
  1131. .melt_quote(PaymentMethod::BOLT11, invoice.to_string(), None, None)
  1132. .await
  1133. .unwrap();
  1134. let melt_request = MeltRequest::new(melt_quote.id, proofs, None);
  1135. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1136. let response = http_client
  1137. .post_melt(
  1138. &PaymentMethod::Known(KnownMethod::Bolt11),
  1139. melt_request.clone(),
  1140. )
  1141. .await;
  1142. match response {
  1143. Err(err) => match err {
  1144. cdk::Error::TokenAlreadySpent => (),
  1145. err => {
  1146. panic!("Wrong mint error returned: {}", err);
  1147. }
  1148. },
  1149. Ok(_) => {
  1150. panic!("Should not have allowed to melt with multiple units");
  1151. }
  1152. }
  1153. }
  1154. /// Tests that attempting to swap with duplicate proofs fails
  1155. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1156. async fn test_fake_mint_duplicate_proofs_swap() {
  1157. let wallet = Wallet::new(
  1158. MINT_URL,
  1159. CurrencyUnit::Sat,
  1160. Arc::new(memory::empty().await.unwrap()),
  1161. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1162. None,
  1163. )
  1164. .expect("failed to create new wallet");
  1165. let mint_quote = wallet.mint_bolt11_quote(100.into(), None).await.unwrap();
  1166. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1167. let proofs = proof_streams
  1168. .next()
  1169. .await
  1170. .expect("payment")
  1171. .expect("no error");
  1172. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  1173. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  1174. let inputs = vec![proofs[0].clone(), proofs[0].clone()];
  1175. let pre_mint = PreMintSecrets::random(
  1176. active_keyset_id,
  1177. inputs.total_amount().unwrap(),
  1178. &SplitTarget::None,
  1179. &fee_and_amounts,
  1180. )
  1181. .unwrap();
  1182. let swap_request = SwapRequest::new(inputs.clone(), pre_mint.blinded_messages());
  1183. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1184. let response = http_client.post_swap(swap_request.clone()).await;
  1185. match response {
  1186. Err(err) => match err {
  1187. cdk::Error::DuplicateInputs => (),
  1188. err => {
  1189. panic!(
  1190. "Wrong mint error returned, expected duplicate inputs: {}",
  1191. err
  1192. );
  1193. }
  1194. },
  1195. Ok(_) => {
  1196. panic!("Should not have allowed duplicate inputs");
  1197. }
  1198. }
  1199. let blinded_message = pre_mint.blinded_messages();
  1200. let inputs = vec![proofs[0].clone()];
  1201. let outputs = vec![blinded_message[0].clone(), blinded_message[0].clone()];
  1202. let swap_request = SwapRequest::new(inputs, outputs);
  1203. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1204. let response = http_client.post_swap(swap_request.clone()).await;
  1205. match response {
  1206. Err(err) => match err {
  1207. cdk::Error::DuplicateOutputs => (),
  1208. err => {
  1209. panic!(
  1210. "Wrong mint error returned, expected duplicate outputs: {}",
  1211. err
  1212. );
  1213. }
  1214. },
  1215. Ok(_) => {
  1216. panic!("Should not have allow duplicate inputs");
  1217. }
  1218. }
  1219. }
  1220. /// Tests that attempting to melt with duplicate proofs fails
  1221. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1222. async fn test_fake_mint_duplicate_proofs_melt() {
  1223. let wallet = Wallet::new(
  1224. MINT_URL,
  1225. CurrencyUnit::Sat,
  1226. Arc::new(memory::empty().await.unwrap()),
  1227. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1228. None,
  1229. )
  1230. .expect("failed to create new wallet");
  1231. let mint_quote = wallet.mint_bolt11_quote(100.into(), None).await.unwrap();
  1232. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1233. let proofs = proof_streams
  1234. .next()
  1235. .await
  1236. .expect("payment")
  1237. .expect("no error");
  1238. let inputs = vec![proofs[0].clone(), proofs[0].clone()];
  1239. let invoice = create_fake_invoice(7000, "".to_string());
  1240. let melt_quote = wallet
  1241. .melt_quote(PaymentMethod::BOLT11, invoice.to_string(), None, None)
  1242. .await
  1243. .unwrap();
  1244. let melt_request = MeltRequest::new(melt_quote.id, inputs, None);
  1245. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1246. let response = http_client
  1247. .post_melt(
  1248. &PaymentMethod::Known(KnownMethod::Bolt11),
  1249. melt_request.clone(),
  1250. )
  1251. .await;
  1252. match response {
  1253. Err(err) => match err {
  1254. cdk::Error::DuplicateInputs => (),
  1255. err => {
  1256. panic!("Wrong mint error returned: {}", err);
  1257. }
  1258. },
  1259. Ok(_) => {
  1260. panic!("Should not have allow duplicate inputs");
  1261. }
  1262. }
  1263. }
  1264. /// Tests that wallet automatically recovers proofs after a failed melt operation
  1265. /// by swapping them to new proofs, preventing loss of funds
  1266. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1267. async fn test_wallet_proof_recovery_after_failed_melt() {
  1268. let wallet = Wallet::new(
  1269. MINT_URL,
  1270. CurrencyUnit::Sat,
  1271. Arc::new(memory::empty().await.unwrap()),
  1272. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1273. None,
  1274. )
  1275. .expect("failed to create new wallet");
  1276. // Mint 100 sats
  1277. let mint_quote = wallet.mint_bolt11_quote(100.into(), None).await.unwrap();
  1278. let _roof_streams = wallet
  1279. .wait_and_mint_quote(
  1280. mint_quote.clone(),
  1281. SplitTarget::default(),
  1282. None,
  1283. Duration::from_secs(1000),
  1284. )
  1285. .await;
  1286. assert_eq!(wallet.total_balance().await.unwrap(), Amount::from(100));
  1287. // Create a melt quote that will fail
  1288. let fake_description = FakeInvoiceDescription {
  1289. pay_invoice_state: MeltQuoteState::Unknown,
  1290. check_payment_state: MeltQuoteState::Unpaid,
  1291. pay_err: true,
  1292. check_err: false,
  1293. };
  1294. let invoice = create_fake_invoice(1000, serde_json::to_string(&fake_description).unwrap());
  1295. let melt_quote = wallet
  1296. .melt_quote(PaymentMethod::BOLT11, invoice.to_string(), None, None)
  1297. .await
  1298. .unwrap();
  1299. // Attempt to melt - this should fail but trigger proof recovery
  1300. let melt_result = async {
  1301. let prepared = wallet
  1302. .prepare_melt(&melt_quote.id, std::collections::HashMap::new())
  1303. .await?;
  1304. prepared.confirm().await
  1305. }
  1306. .await;
  1307. assert!(melt_result.is_err(), "Melt should have failed");
  1308. // Verify wallet still has balance (proofs recovered)
  1309. assert_eq!(
  1310. wallet.total_balance().await.unwrap(),
  1311. Amount::from(100),
  1312. "Balance should be recovered"
  1313. );
  1314. // Verify we can still spend the recovered proofs
  1315. let valid_invoice = create_fake_invoice(7000, "".to_string());
  1316. let valid_melt_quote = wallet
  1317. .melt_quote(PaymentMethod::BOLT11, valid_invoice.to_string(), None, None)
  1318. .await
  1319. .unwrap();
  1320. let successful_melt = async {
  1321. let prepared = wallet
  1322. .prepare_melt(&valid_melt_quote.id, std::collections::HashMap::new())
  1323. .await?;
  1324. prepared.confirm().await
  1325. }
  1326. .await;
  1327. assert!(
  1328. successful_melt.is_ok(),
  1329. "Should be able to spend recovered proofs"
  1330. );
  1331. }
  1332. /// Tests that concurrent melt attempts for the same invoice result in exactly one success
  1333. ///
  1334. /// This test verifies the race condition protection: when multiple melt quotes exist for the
  1335. /// same invoice and all are attempted concurrently, only one should succeed due to
  1336. /// the FOR UPDATE locking on quotes with the same request_lookup_id.
  1337. #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
  1338. async fn test_concurrent_melt_same_invoice() {
  1339. const NUM_WALLETS: usize = 4;
  1340. // Create multiple wallets to simulate concurrent requests
  1341. let mut wallets = Vec::with_capacity(NUM_WALLETS);
  1342. for i in 0..NUM_WALLETS {
  1343. let wallet = Arc::new(
  1344. Wallet::new(
  1345. MINT_URL,
  1346. CurrencyUnit::Sat,
  1347. Arc::new(memory::empty().await.unwrap()),
  1348. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1349. None,
  1350. )
  1351. .expect(&format!("failed to create wallet {}", i)),
  1352. );
  1353. wallets.push(wallet);
  1354. }
  1355. // Mint proofs for all wallets
  1356. for (i, wallet) in wallets.iter().enumerate() {
  1357. let mint_quote = wallet.mint_bolt11_quote(100.into(), None).await.unwrap();
  1358. let mut proof_streams =
  1359. wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1360. proof_streams
  1361. .next()
  1362. .await
  1363. .expect(&format!("payment for wallet {}", i))
  1364. .expect("no error");
  1365. }
  1366. // Create a single invoice that all wallets will try to pay
  1367. let fake_description = FakeInvoiceDescription::default();
  1368. let invoice = create_fake_invoice(9000, serde_json::to_string(&fake_description).unwrap());
  1369. // All wallets create melt quotes for the same invoice
  1370. let mut melt_quotes = Vec::with_capacity(NUM_WALLETS);
  1371. for wallet in &wallets {
  1372. let melt_quote = wallet
  1373. .melt_quote(PaymentMethod::BOLT11, invoice.to_string(), None, None)
  1374. .await
  1375. .unwrap();
  1376. melt_quotes.push(melt_quote);
  1377. }
  1378. // Verify all quotes have the same request (same invoice = same lookup_id)
  1379. for quote in &melt_quotes[1..] {
  1380. assert_eq!(
  1381. melt_quotes[0].request, quote.request,
  1382. "All quotes should be for the same invoice"
  1383. );
  1384. }
  1385. // Attempt all melts concurrently
  1386. let mut handles = Vec::with_capacity(NUM_WALLETS);
  1387. for (wallet, quote) in wallets.iter().zip(melt_quotes.iter()) {
  1388. let wallet_clone = Arc::clone(wallet);
  1389. let quote_id = quote.id.clone();
  1390. handles.push(tokio::spawn(async move {
  1391. let prepared = wallet_clone
  1392. .prepare_melt(&quote_id, std::collections::HashMap::new())
  1393. .await?;
  1394. prepared.confirm().await
  1395. }));
  1396. }
  1397. // Collect results
  1398. let mut results = Vec::with_capacity(NUM_WALLETS);
  1399. for handle in handles {
  1400. results.push(handle.await.expect("task panicked"));
  1401. }
  1402. // Count successes and failures
  1403. let success_count = results.iter().filter(|r| r.is_ok()).count();
  1404. let failure_count = results.iter().filter(|r| r.is_err()).count();
  1405. assert_eq!(
  1406. success_count, 1,
  1407. "Expected exactly one successful melt, got {}. Results: {:?}",
  1408. success_count, results
  1409. );
  1410. assert_eq!(
  1411. failure_count,
  1412. NUM_WALLETS - 1,
  1413. "Expected {} failed melts, got {}",
  1414. NUM_WALLETS - 1,
  1415. failure_count
  1416. );
  1417. // Verify all failures were due to duplicate detection
  1418. for result in &results {
  1419. if let Err(err) = result {
  1420. let err_str = err.to_string().to_lowercase();
  1421. assert!(
  1422. err_str.contains("duplicate")
  1423. || err_str.contains("already paid")
  1424. || err_str.contains("pending")
  1425. || err_str.contains("payment failed"),
  1426. "Expected duplicate/already paid/pending/payment failed error, got: {}",
  1427. err
  1428. );
  1429. }
  1430. }
  1431. }
  1432. /// Tests that wallet automatically recovers proofs after a failed swap operation
  1433. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1434. async fn test_wallet_proof_recovery_after_failed_swap() {
  1435. let wallet = Wallet::new(
  1436. MINT_URL,
  1437. CurrencyUnit::Sat,
  1438. Arc::new(memory::empty().await.unwrap()),
  1439. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1440. None,
  1441. )
  1442. .expect("failed to create new wallet");
  1443. // Mint 100 sats
  1444. let mint_quote = wallet.mint_bolt11_quote(100.into(), None).await.unwrap();
  1445. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1446. let initial_proofs = proof_streams
  1447. .next()
  1448. .await
  1449. .expect("payment")
  1450. .expect("no error");
  1451. let initial_ys: Vec<_> = initial_proofs.iter().map(|p| p.y().unwrap()).collect();
  1452. assert_eq!(wallet.total_balance().await.unwrap(), Amount::from(100));
  1453. let unspent_proofs = wallet.get_unspent_proofs().await.unwrap();
  1454. // Create an invalid swap by manually constructing a request that will fail
  1455. // We'll use the wallet's swap with invalid parameters to trigger a failure
  1456. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  1457. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  1458. // Create invalid swap request (requesting more than we have)
  1459. let preswap = PreMintSecrets::random(
  1460. active_keyset_id,
  1461. 1000.into(), // More than the 100 we have
  1462. &SplitTarget::default(),
  1463. &fee_and_amounts,
  1464. )
  1465. .unwrap();
  1466. let swap_request = SwapRequest::new(unspent_proofs.clone(), preswap.blinded_messages());
  1467. // Use HTTP client directly to bypass wallet's validation and trigger recovery
  1468. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1469. let response = http_client.post_swap(swap_request).await;
  1470. assert!(response.is_err(), "Swap should have failed");
  1471. // Note: The HTTP client doesn't trigger the wallet's try_proof_operation wrapper
  1472. // So we need to test through the wallet's own methods
  1473. // After the failed HTTP request, the proofs are still in the wallet's database
  1474. // Verify balance is still available after the failed operation
  1475. assert_eq!(
  1476. wallet.total_balance().await.unwrap(),
  1477. Amount::from(100),
  1478. "Balance should still be available"
  1479. );
  1480. // Verify we can perform a successful swap operation
  1481. let successful_swap = wallet
  1482. .swap(None, SplitTarget::None, unspent_proofs, None, false)
  1483. .await;
  1484. assert!(
  1485. successful_swap.is_ok(),
  1486. "Should be able to swap after failed operation"
  1487. );
  1488. // Verify the proofs were swapped to new ones
  1489. let final_proofs = wallet.get_unspent_proofs().await.unwrap();
  1490. let final_ys: Vec<_> = final_proofs.iter().map(|p| p.y().unwrap()).collect();
  1491. // The Ys should be different after the successful swap
  1492. assert!(
  1493. initial_ys.iter().any(|y| !final_ys.contains(y)),
  1494. "Proofs should have been swapped to new ones"
  1495. );
  1496. }
  1497. /// Tests that melt_proofs works correctly with proofs that are not already in the wallet's database.
  1498. /// This is similar to the receive flow where proofs come from an external source.
  1499. ///
  1500. /// Flow:
  1501. /// 1. Wallet A mints proofs (proofs ARE in Wallet A's database)
  1502. /// 2. Wallet B creates a melt quote
  1503. /// 3. Wallet B calls melt_proofs with proofs from Wallet A (proofs are NOT in Wallet B's database)
  1504. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1505. async fn test_melt_proofs_external() {
  1506. // Create sender wallet (Wallet A) and mint some proofs
  1507. let wallet_sender = Wallet::new(
  1508. MINT_URL,
  1509. CurrencyUnit::Sat,
  1510. Arc::new(memory::empty().await.unwrap()),
  1511. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1512. None,
  1513. )
  1514. .expect("failed to create sender wallet");
  1515. let mint_quote = wallet_sender
  1516. .mint_bolt11_quote(100.into(), None)
  1517. .await
  1518. .unwrap();
  1519. let mut proof_streams =
  1520. wallet_sender.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1521. let proofs = proof_streams
  1522. .next()
  1523. .await
  1524. .expect("payment")
  1525. .expect("no error");
  1526. assert_eq!(proofs.total_amount().unwrap(), Amount::from(100));
  1527. // Create receiver/melter wallet (Wallet B) with a separate database
  1528. // These proofs are NOT in Wallet B's database
  1529. let wallet_melter = Wallet::new(
  1530. MINT_URL,
  1531. CurrencyUnit::Sat,
  1532. Arc::new(memory::empty().await.unwrap()),
  1533. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1534. None,
  1535. )
  1536. .expect("failed to create melter wallet");
  1537. // Verify proofs are not in the melter wallet's database
  1538. let melter_proofs = wallet_melter.get_unspent_proofs().await.unwrap();
  1539. assert!(
  1540. melter_proofs.is_empty(),
  1541. "Melter wallet should have no proofs initially"
  1542. );
  1543. // Create a fake invoice for melting
  1544. let fake_description = FakeInvoiceDescription::default();
  1545. let invoice = create_fake_invoice(9000, serde_json::to_string(&fake_description).unwrap());
  1546. // Wallet B creates a melt quote
  1547. let melt_quote = wallet_melter
  1548. .melt_quote(PaymentMethod::BOLT11, invoice.to_string(), None, None)
  1549. .await
  1550. .unwrap();
  1551. // Wallet B calls melt_proofs with external proofs (from Wallet A)
  1552. // These proofs are NOT in wallet_melter's database
  1553. let prepared = wallet_melter
  1554. .prepare_melt_proofs(
  1555. &melt_quote.id,
  1556. proofs.clone(),
  1557. std::collections::HashMap::new(),
  1558. )
  1559. .await
  1560. .unwrap();
  1561. let melted = prepared.confirm().await.unwrap();
  1562. // Verify the melt succeeded
  1563. assert_eq!(melted.amount(), Amount::from(9));
  1564. assert_eq!(melted.fee_paid(), 1.into());
  1565. // Verify change was returned (100 input - 9 melt amount = 91 change, minus fee reserve)
  1566. assert!(melted.change().is_some());
  1567. let change_amount = melted.change().unwrap().total_amount().unwrap();
  1568. assert!(change_amount > Amount::ZERO, "Should have received change");
  1569. // Verify the melter wallet now has the change proofs
  1570. let melter_balance = wallet_melter.total_balance().await.unwrap();
  1571. assert_eq!(melter_balance, change_amount);
  1572. // Verify a transaction was recorded
  1573. let transactions = wallet_melter
  1574. .list_transactions(Some(TransactionDirection::Outgoing))
  1575. .await
  1576. .unwrap();
  1577. assert_eq!(transactions.len(), 1);
  1578. assert_eq!(transactions[0].amount, Amount::from(9));
  1579. }
  1580. /// Tests that melt automatically performs a swap when proofs don't exactly match
  1581. /// the required amount (quote + fee_reserve + input_fee).
  1582. ///
  1583. /// This test verifies the swap-before-melt optimization:
  1584. /// 1. Mint proofs that will NOT exactly match a melt amount
  1585. /// 2. Create a melt quote for a specific amount
  1586. /// 3. Call melt() - it should automatically swap proofs to get exact denominations
  1587. /// 4. Verify the melt succeeded
  1588. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1589. async fn test_melt_with_swap_for_exact_amount() {
  1590. let wallet = Wallet::new(
  1591. MINT_URL,
  1592. CurrencyUnit::Sat,
  1593. Arc::new(memory::empty().await.unwrap()),
  1594. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1595. None,
  1596. )
  1597. .expect("failed to create new wallet");
  1598. // Mint 100 sats - this will give us proofs in standard denominations
  1599. let mint_quote = wallet.mint_bolt11_quote(100.into(), None).await.unwrap();
  1600. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1601. let proofs = proof_streams
  1602. .next()
  1603. .await
  1604. .expect("payment")
  1605. .expect("no error");
  1606. let initial_balance = wallet.total_balance().await.unwrap();
  1607. assert_eq!(initial_balance, Amount::from(100));
  1608. // Log the proof denominations we received
  1609. let proof_amounts: Vec<u64> = proofs.iter().map(|p| u64::from(p.amount)).collect();
  1610. tracing::info!("Initial proof denominations: {:?}", proof_amounts);
  1611. // Create a melt quote for an amount that likely won't match our proof denominations exactly
  1612. // Using 7 sats (7000 msats) which requires specific denominations
  1613. let fake_description = FakeInvoiceDescription::default();
  1614. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  1615. let melt_quote = wallet
  1616. .melt_quote(PaymentMethod::BOLT11, invoice.to_string(), None, None)
  1617. .await
  1618. .unwrap();
  1619. tracing::info!(
  1620. "Melt quote: amount={}, fee_reserve={}",
  1621. melt_quote.amount,
  1622. melt_quote.fee_reserve
  1623. );
  1624. // Call melt() - this should trigger swap-before-melt if proofs don't match exactly
  1625. let prepared = wallet
  1626. .prepare_melt(&melt_quote.id, std::collections::HashMap::new())
  1627. .await
  1628. .unwrap();
  1629. let melted = prepared.confirm().await.unwrap();
  1630. // Verify the melt succeeded
  1631. assert_eq!(melted.amount(), Amount::from(7));
  1632. tracing::info!(
  1633. "Melt completed: amount={}, fee_paid={}",
  1634. melted.amount(),
  1635. melted.fee_paid()
  1636. );
  1637. // Verify final balance is correct (initial - melt_amount - fees)
  1638. let final_balance = wallet.total_balance().await.unwrap();
  1639. tracing::info!(
  1640. "Balance: initial={}, final={}, paid={}",
  1641. initial_balance,
  1642. final_balance,
  1643. melted.amount() + melted.fee_paid()
  1644. );
  1645. assert!(
  1646. final_balance < initial_balance,
  1647. "Balance should have decreased after melt"
  1648. );
  1649. assert_eq!(
  1650. final_balance,
  1651. initial_balance - melted.amount() - melted.fee_paid(),
  1652. "Final balance should be initial - amount - fees"
  1653. );
  1654. }
  1655. /// Tests that melt works correctly when proofs already exactly match the required amount.
  1656. /// In this case, no swap should be needed.
  1657. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1658. async fn test_melt_exact_proofs_no_swap_needed() {
  1659. let wallet = Wallet::new(
  1660. MINT_URL,
  1661. CurrencyUnit::Sat,
  1662. Arc::new(memory::empty().await.unwrap()),
  1663. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1664. None,
  1665. )
  1666. .expect("failed to create new wallet");
  1667. // Mint a larger amount to have more denomination options
  1668. let mint_quote = wallet.mint_bolt11_quote(1000.into(), None).await.unwrap();
  1669. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1670. let _proofs = proof_streams
  1671. .next()
  1672. .await
  1673. .expect("payment")
  1674. .expect("no error");
  1675. let initial_balance = wallet.total_balance().await.unwrap();
  1676. assert_eq!(initial_balance, Amount::from(1000));
  1677. // Create a melt for a power-of-2 amount that's more likely to match existing denominations
  1678. let fake_description = FakeInvoiceDescription::default();
  1679. let invoice = create_fake_invoice(64_000, serde_json::to_string(&fake_description).unwrap()); // 64 sats
  1680. let melt_quote = wallet
  1681. .melt_quote(PaymentMethod::BOLT11, invoice.to_string(), None, None)
  1682. .await
  1683. .unwrap();
  1684. // Melt should succeed
  1685. let prepared = wallet
  1686. .prepare_melt(&melt_quote.id, std::collections::HashMap::new())
  1687. .await
  1688. .unwrap();
  1689. let melted = prepared.confirm().await.unwrap();
  1690. assert_eq!(melted.amount(), Amount::from(64));
  1691. let final_balance = wallet.total_balance().await.unwrap();
  1692. assert_eq!(
  1693. final_balance,
  1694. initial_balance - melted.amount() - melted.fee_paid()
  1695. );
  1696. }
  1697. /// Tests the check_all_mint_quotes functionality for Bolt11 quotes
  1698. ///
  1699. /// This test verifies that:
  1700. /// 1. Paid mint quotes are automatically minted when check_all_mint_quotes is called
  1701. /// 2. The total amount returned matches the minted proofs
  1702. /// 3. Quote state is properly updated after minting
  1703. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1704. async fn test_check_all_mint_quotes_bolt11() {
  1705. let wallet = Wallet::new(
  1706. MINT_URL,
  1707. CurrencyUnit::Sat,
  1708. Arc::new(memory::empty().await.unwrap()),
  1709. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1710. None,
  1711. )
  1712. .expect("failed to create new wallet");
  1713. // Create first mint quote and pay it (using proof_stream triggers fake wallet payment)
  1714. let mint_quote_1 = wallet.mint_bolt11_quote(100.into(), None).await.unwrap();
  1715. // Wait for the payment to be registered (fake wallet auto-pays)
  1716. let mut payment_stream_1 = wallet.payment_stream(&mint_quote_1);
  1717. payment_stream_1
  1718. .next()
  1719. .await
  1720. .expect("payment")
  1721. .expect("no error");
  1722. // Create second mint quote and pay it
  1723. let mint_quote_2 = wallet.mint_bolt11_quote(50.into(), None).await.unwrap();
  1724. let mut payment_stream_2 = wallet.payment_stream(&mint_quote_2);
  1725. payment_stream_2
  1726. .next()
  1727. .await
  1728. .expect("payment")
  1729. .expect("no error");
  1730. // Verify no proofs have been minted yet
  1731. assert_eq!(wallet.total_balance().await.unwrap(), Amount::ZERO);
  1732. // Call mint_unissued_quotes - this should mint both paid quotes
  1733. let total_minted = wallet.mint_unissued_quotes().await.unwrap();
  1734. // Verify the total amount minted is correct (100 + 50 = 150)
  1735. assert_eq!(total_minted, Amount::from(150));
  1736. // Verify wallet balance matches
  1737. assert_eq!(wallet.total_balance().await.unwrap(), Amount::from(150));
  1738. // Calling mint_unissued_quotes again should return 0 (quotes already minted)
  1739. let second_check = wallet.mint_unissued_quotes().await.unwrap();
  1740. assert_eq!(second_check, Amount::ZERO);
  1741. }
  1742. /// Tests the get_unissued_mint_quotes wallet method
  1743. ///
  1744. /// This test verifies that:
  1745. /// 1. Unpaid quotes are included (wallet needs to check with mint)
  1746. /// 2. Paid but not issued quotes are included
  1747. /// 3. Fully issued quotes are excluded
  1748. /// 4. Only quotes for the current mint URL are returned
  1749. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1750. async fn test_get_unissued_mint_quotes_wallet() {
  1751. let wallet = Wallet::new(
  1752. MINT_URL,
  1753. CurrencyUnit::Sat,
  1754. Arc::new(memory::empty().await.unwrap()),
  1755. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1756. None,
  1757. )
  1758. .expect("failed to create new wallet");
  1759. // Create a quote but don't pay it (stays unpaid)
  1760. let unpaid_quote = wallet.mint_bolt11_quote(100.into(), None).await.unwrap();
  1761. // Create another quote and pay it but don't mint
  1762. let paid_quote = wallet.mint_bolt11_quote(50.into(), None).await.unwrap();
  1763. let mut payment_stream = wallet.payment_stream(&paid_quote);
  1764. payment_stream
  1765. .next()
  1766. .await
  1767. .expect("payment")
  1768. .expect("no error");
  1769. // Create a third quote and fully mint it
  1770. let minted_quote = wallet.mint_bolt11_quote(25.into(), None).await.unwrap();
  1771. let mut proof_stream = wallet.proof_stream(minted_quote.clone(), SplitTarget::default(), None);
  1772. proof_stream
  1773. .next()
  1774. .await
  1775. .expect("payment")
  1776. .expect("no error");
  1777. // Get unissued quotes
  1778. let unissued_quotes = wallet.get_unissued_mint_quotes().await.unwrap();
  1779. // Should have 2 quotes: unpaid and paid-but-not-issued
  1780. // The fully minted quote should be excluded
  1781. assert_eq!(
  1782. unissued_quotes.len(),
  1783. 2,
  1784. "Should have 2 unissued quotes (unpaid and paid-not-issued)"
  1785. );
  1786. let quote_ids: Vec<&str> = unissued_quotes.iter().map(|q| q.id.as_str()).collect();
  1787. assert!(
  1788. quote_ids.contains(&unpaid_quote.id.as_str()),
  1789. "Unpaid quote should be included"
  1790. );
  1791. assert!(
  1792. quote_ids.contains(&paid_quote.id.as_str()),
  1793. "Paid but not issued quote should be included"
  1794. );
  1795. assert!(
  1796. !quote_ids.contains(&minted_quote.id.as_str()),
  1797. "Fully minted quote should NOT be included"
  1798. );
  1799. }
  1800. /// Tests that mint quote state is properly updated after minting
  1801. ///
  1802. /// This test verifies that:
  1803. /// 1. amount_issued is updated after successful minting
  1804. /// 2. Quote state is updated correctly
  1805. /// 3. The quote is stored properly in the localstore
  1806. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1807. async fn test_refresh_mint_quote_status_updates_after_minting() {
  1808. let wallet = Wallet::new(
  1809. MINT_URL,
  1810. CurrencyUnit::Sat,
  1811. Arc::new(memory::empty().await.unwrap()),
  1812. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1813. None,
  1814. )
  1815. .expect("failed to create new wallet");
  1816. let mint_amount = Amount::from(100);
  1817. let mint_quote = wallet.mint_bolt11_quote(mint_amount, None).await.unwrap();
  1818. // Get the quote from localstore before minting
  1819. let quote_before = wallet
  1820. .localstore
  1821. .get_mint_quote(&mint_quote.id)
  1822. .await
  1823. .unwrap()
  1824. .expect("Quote should exist");
  1825. // Verify initial state
  1826. assert_eq!(quote_before.amount_issued, Amount::ZERO);
  1827. // Mint the tokens using wait_and_mint_quote
  1828. let proofs = wallet
  1829. .wait_and_mint_quote(
  1830. mint_quote.clone(),
  1831. SplitTarget::default(),
  1832. None,
  1833. Duration::from_secs(60),
  1834. )
  1835. .await
  1836. .expect("minting should succeed");
  1837. let minted_amount = proofs.total_amount().unwrap();
  1838. assert_eq!(minted_amount, mint_amount);
  1839. // Check the quote is now either removed or updated in the localstore
  1840. // After minting, the quote should be removed from localstore (it's fully issued)
  1841. let quote_after = wallet
  1842. .localstore
  1843. .get_mint_quote(&mint_quote.id)
  1844. .await
  1845. .unwrap();
  1846. // The quote should either be removed or have amount_issued updated
  1847. match quote_after {
  1848. Some(quote) => {
  1849. // If still present, amount_issued should equal the minted amount
  1850. assert_eq!(
  1851. quote.amount_issued, minted_amount,
  1852. "amount_issued should be updated after minting"
  1853. );
  1854. }
  1855. None => {
  1856. // Quote was removed after being fully issued - this is also valid behavior
  1857. }
  1858. }
  1859. // Verify the unissued quotes no longer contains this quote
  1860. let unissued = wallet.get_unissued_mint_quotes().await.unwrap();
  1861. let unissued_ids: Vec<&str> = unissued.iter().map(|q| q.id.as_str()).collect();
  1862. assert!(
  1863. !unissued_ids.contains(&mint_quote.id.as_str()),
  1864. "Fully minted quote should not appear in unissued quotes"
  1865. );
  1866. }