fake_wallet.rs 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231
  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, WalletTrait};
  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
  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_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_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_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_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_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_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_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_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_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_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_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_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.mint_quote(100.into(), None).await.unwrap();
  720. let mut proof_streams =
  721. wallet_usd.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  722. let usd_proofs = proof_streams
  723. .next()
  724. .await
  725. .expect("payment")
  726. .expect("no error");
  727. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  728. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  729. {
  730. let inputs: Proofs = vec![
  731. proofs.first().expect("There is a proof").clone(),
  732. usd_proofs.first().expect("There is a proof").clone(),
  733. ];
  734. let pre_mint = PreMintSecrets::random(
  735. active_keyset_id,
  736. inputs.total_amount().unwrap(),
  737. &SplitTarget::None,
  738. &fee_and_amounts,
  739. )
  740. .unwrap();
  741. let swap_request = SwapRequest::new(inputs, pre_mint.blinded_messages());
  742. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  743. let response = http_client.post_swap(swap_request.clone()).await;
  744. match response {
  745. Err(err) => match err {
  746. cdk::Error::MultipleUnits => (),
  747. err => {
  748. panic!("Wrong mint error returned: {}", err);
  749. }
  750. },
  751. Ok(_) => {
  752. panic!("Should not have allowed to mint with multiple units");
  753. }
  754. }
  755. }
  756. {
  757. let usd_active_keyset_id = wallet_usd.fetch_active_keyset().await.unwrap().id;
  758. let inputs: Proofs = proofs.into_iter().take(2).collect();
  759. let total_inputs = inputs.total_amount().unwrap();
  760. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  761. let half = total_inputs / 2.into();
  762. let usd_pre_mint = PreMintSecrets::random(
  763. usd_active_keyset_id,
  764. half,
  765. &SplitTarget::None,
  766. &fee_and_amounts,
  767. )
  768. .unwrap();
  769. let pre_mint = PreMintSecrets::random(
  770. active_keyset_id,
  771. total_inputs - half,
  772. &SplitTarget::None,
  773. &fee_and_amounts,
  774. )
  775. .unwrap();
  776. let mut usd_outputs = usd_pre_mint.blinded_messages();
  777. let mut sat_outputs = pre_mint.blinded_messages();
  778. usd_outputs.append(&mut sat_outputs);
  779. let swap_request = SwapRequest::new(inputs, usd_outputs);
  780. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  781. let response = http_client.post_swap(swap_request.clone()).await;
  782. match response {
  783. Err(err) => match err {
  784. cdk::Error::MultipleUnits => (),
  785. err => {
  786. panic!("Wrong mint error returned: {}", err);
  787. }
  788. },
  789. Ok(_) => {
  790. panic!("Should not have allowed to mint with multiple units");
  791. }
  792. }
  793. }
  794. }
  795. /// Tests that attempting to melt tokens with multiple currency units fails
  796. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  797. async fn test_fake_mint_multiple_unit_melt() {
  798. let wallet = Wallet::new(
  799. MINT_URL,
  800. CurrencyUnit::Sat,
  801. Arc::new(memory::empty().await.unwrap()),
  802. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  803. None,
  804. )
  805. .expect("failed to create new wallet");
  806. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  807. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  808. let mut proofs = proof_streams
  809. .next()
  810. .await
  811. .expect("payment")
  812. .expect("no error");
  813. println!("Minted sat");
  814. let wallet_usd = Wallet::new(
  815. MINT_URL,
  816. CurrencyUnit::Usd,
  817. Arc::new(memory::empty().await.unwrap()),
  818. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  819. None,
  820. )
  821. .expect("failed to create new wallet");
  822. let mint_quote = wallet_usd.mint_quote(100.into(), None).await.unwrap();
  823. println!("Minted quote usd");
  824. let mut proof_streams =
  825. wallet_usd.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  826. let mut usd_proofs = proof_streams
  827. .next()
  828. .await
  829. .expect("payment")
  830. .expect("no error");
  831. usd_proofs.reverse();
  832. proofs.reverse();
  833. {
  834. let inputs: Proofs = vec![
  835. proofs.first().expect("There is a proof").clone(),
  836. usd_proofs.first().expect("There is a proof").clone(),
  837. ];
  838. let input_amount: u64 = inputs.total_amount().unwrap().into();
  839. let invoice = create_fake_invoice((input_amount - 1) * 1000, "".to_string());
  840. let melt_quote = wallet
  841. .melt_quote(PaymentMethod::BOLT11, invoice.to_string(), None, None)
  842. .await
  843. .unwrap();
  844. let melt_request = MeltRequest::new(melt_quote.id, inputs, None);
  845. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  846. let response = http_client
  847. .post_melt(
  848. &PaymentMethod::Known(KnownMethod::Bolt11),
  849. melt_request.clone(),
  850. )
  851. .await;
  852. match response {
  853. Err(err) => match err {
  854. cdk::Error::MultipleUnits => (),
  855. err => {
  856. panic!("Wrong mint error returned: {}", err);
  857. }
  858. },
  859. Ok(_) => {
  860. panic!("Should not have allowed to melt with multiple units");
  861. }
  862. }
  863. }
  864. {
  865. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  866. let inputs: Proofs = vec![proofs.first().expect("There is a proof").clone()];
  867. let input_amount: u64 = inputs.total_amount().unwrap().into();
  868. let invoice = create_fake_invoice((input_amount - 1) * 1000, "".to_string());
  869. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  870. let usd_active_keyset_id = wallet_usd.fetch_active_keyset().await.unwrap().id;
  871. let usd_pre_mint = PreMintSecrets::random(
  872. usd_active_keyset_id,
  873. inputs.total_amount().unwrap() + 100.into(),
  874. &SplitTarget::None,
  875. &fee_and_amounts,
  876. )
  877. .unwrap();
  878. let pre_mint = PreMintSecrets::random(
  879. active_keyset_id,
  880. 100.into(),
  881. &SplitTarget::None,
  882. &fee_and_amounts,
  883. )
  884. .unwrap();
  885. let mut usd_outputs = usd_pre_mint.blinded_messages();
  886. let mut sat_outputs = pre_mint.blinded_messages();
  887. usd_outputs.append(&mut sat_outputs);
  888. let quote = wallet
  889. .melt_quote(PaymentMethod::BOLT11, invoice.to_string(), None, None)
  890. .await
  891. .unwrap();
  892. let melt_request = MeltRequest::new(quote.id, inputs, Some(usd_outputs));
  893. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  894. let response = http_client
  895. .post_melt(
  896. &PaymentMethod::Known(KnownMethod::Bolt11),
  897. melt_request.clone(),
  898. )
  899. .await;
  900. match response {
  901. Err(err) => match err {
  902. cdk::Error::MultipleUnits => (),
  903. err => {
  904. panic!("Wrong mint error returned: {}", err);
  905. }
  906. },
  907. Ok(_) => {
  908. panic!("Should not have allowed to melt with multiple units");
  909. }
  910. }
  911. }
  912. }
  913. /// Tests that swapping tokens where input unit doesn't match output unit fails
  914. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  915. async fn test_fake_mint_input_output_mismatch() {
  916. let wallet = Wallet::new(
  917. MINT_URL,
  918. CurrencyUnit::Sat,
  919. Arc::new(memory::empty().await.unwrap()),
  920. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  921. None,
  922. )
  923. .expect("failed to create new wallet");
  924. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  925. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  926. let proofs = proof_streams
  927. .next()
  928. .await
  929. .expect("payment")
  930. .expect("no error");
  931. let wallet_usd = Wallet::new(
  932. MINT_URL,
  933. CurrencyUnit::Usd,
  934. Arc::new(memory::empty().await.unwrap()),
  935. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  936. None,
  937. )
  938. .expect("failed to create new usd wallet");
  939. let usd_active_keyset_id = wallet_usd.fetch_active_keyset().await.unwrap().id;
  940. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  941. let inputs = proofs;
  942. let pre_mint = PreMintSecrets::random(
  943. usd_active_keyset_id,
  944. inputs.total_amount().unwrap(),
  945. &SplitTarget::None,
  946. &fee_and_amounts,
  947. )
  948. .unwrap();
  949. let swap_request = SwapRequest::new(inputs, pre_mint.blinded_messages());
  950. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  951. let response = http_client.post_swap(swap_request.clone()).await;
  952. match response {
  953. Err(err) => match err {
  954. cdk::Error::UnitMismatch => (),
  955. err => panic!("Wrong error returned: {}", err),
  956. },
  957. Ok(_) => {
  958. panic!("Should not have allowed to mint with multiple units");
  959. }
  960. }
  961. }
  962. /// Tests that swapping tokens where output amount is greater than input amount fails
  963. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  964. async fn test_fake_mint_swap_inflated() {
  965. let wallet = Wallet::new(
  966. MINT_URL,
  967. CurrencyUnit::Sat,
  968. Arc::new(memory::empty().await.unwrap()),
  969. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  970. None,
  971. )
  972. .expect("failed to create new wallet");
  973. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  974. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  975. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  976. let proofs = proof_streams
  977. .next()
  978. .await
  979. .expect("payment")
  980. .expect("no error");
  981. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  982. let pre_mint = PreMintSecrets::random(
  983. active_keyset_id,
  984. 101.into(),
  985. &SplitTarget::None,
  986. &fee_and_amounts,
  987. )
  988. .unwrap();
  989. let swap_request = SwapRequest::new(proofs, pre_mint.blinded_messages());
  990. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  991. let response = http_client.post_swap(swap_request.clone()).await;
  992. match response {
  993. Err(err) => match err {
  994. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  995. err => {
  996. panic!("Wrong mint error returned: {}", err);
  997. }
  998. },
  999. Ok(_) => {
  1000. panic!("Should not have allowed to mint with multiple units");
  1001. }
  1002. }
  1003. }
  1004. /// Tests that tokens cannot be spent again after a failed swap attempt
  1005. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1006. async fn test_fake_mint_swap_spend_after_fail() {
  1007. let wallet = Wallet::new(
  1008. MINT_URL,
  1009. CurrencyUnit::Sat,
  1010. Arc::new(memory::empty().await.unwrap()),
  1011. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1012. None,
  1013. )
  1014. .expect("failed to create new wallet");
  1015. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  1016. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1017. let proofs = proof_streams
  1018. .next()
  1019. .await
  1020. .expect("payment")
  1021. .expect("no error");
  1022. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  1023. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  1024. let pre_mint = PreMintSecrets::random(
  1025. active_keyset_id,
  1026. 100.into(),
  1027. &SplitTarget::None,
  1028. &fee_and_amounts,
  1029. )
  1030. .unwrap();
  1031. let swap_request = SwapRequest::new(proofs.clone(), pre_mint.blinded_messages());
  1032. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1033. let response = http_client.post_swap(swap_request.clone()).await;
  1034. assert!(response.is_ok());
  1035. let pre_mint = PreMintSecrets::random(
  1036. active_keyset_id,
  1037. 101.into(),
  1038. &SplitTarget::None,
  1039. &fee_and_amounts,
  1040. )
  1041. .unwrap();
  1042. let swap_request = SwapRequest::new(proofs.clone(), pre_mint.blinded_messages());
  1043. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1044. let response = http_client.post_swap(swap_request.clone()).await;
  1045. match response {
  1046. Err(err) => match err {
  1047. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  1048. err => panic!("Wrong mint error returned expected TransactionUnbalanced, got: {err}"),
  1049. },
  1050. Ok(_) => panic!("Should not have allowed swap with unbalanced"),
  1051. }
  1052. let pre_mint = PreMintSecrets::random(
  1053. active_keyset_id,
  1054. 100.into(),
  1055. &SplitTarget::None,
  1056. &fee_and_amounts,
  1057. )
  1058. .unwrap();
  1059. let swap_request = SwapRequest::new(proofs, pre_mint.blinded_messages());
  1060. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1061. let response = http_client.post_swap(swap_request.clone()).await;
  1062. match response {
  1063. Err(err) => match err {
  1064. cdk::Error::TokenAlreadySpent => (),
  1065. err => {
  1066. panic!("Wrong mint error returned: {}", err);
  1067. }
  1068. },
  1069. Ok(_) => {
  1070. panic!("Should not have allowed to mint with multiple units");
  1071. }
  1072. }
  1073. }
  1074. /// Tests that tokens cannot be melted after a failed swap attempt
  1075. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1076. async fn test_fake_mint_melt_spend_after_fail() {
  1077. let wallet = Wallet::new(
  1078. MINT_URL,
  1079. CurrencyUnit::Sat,
  1080. Arc::new(memory::empty().await.unwrap()),
  1081. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1082. None,
  1083. )
  1084. .expect("failed to create new wallet");
  1085. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  1086. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1087. let proofs = proof_streams
  1088. .next()
  1089. .await
  1090. .expect("payment")
  1091. .expect("no error");
  1092. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  1093. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  1094. let pre_mint = PreMintSecrets::random(
  1095. active_keyset_id,
  1096. 100.into(),
  1097. &SplitTarget::None,
  1098. &fee_and_amounts,
  1099. )
  1100. .unwrap();
  1101. let swap_request = SwapRequest::new(proofs.clone(), pre_mint.blinded_messages());
  1102. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1103. let response = http_client.post_swap(swap_request.clone()).await;
  1104. assert!(response.is_ok());
  1105. let pre_mint = PreMintSecrets::random(
  1106. active_keyset_id,
  1107. 101.into(),
  1108. &SplitTarget::None,
  1109. &fee_and_amounts,
  1110. )
  1111. .unwrap();
  1112. let swap_request = SwapRequest::new(proofs.clone(), pre_mint.blinded_messages());
  1113. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1114. let response = http_client.post_swap(swap_request.clone()).await;
  1115. match response {
  1116. Err(err) => match err {
  1117. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  1118. err => panic!("Wrong mint error returned expected TransactionUnbalanced, got: {err}"),
  1119. },
  1120. Ok(_) => panic!("Should not have allowed swap with unbalanced"),
  1121. }
  1122. let input_amount: u64 = proofs.total_amount().unwrap().into();
  1123. let invoice = create_fake_invoice((input_amount - 1) * 1000, "".to_string());
  1124. let melt_quote = wallet
  1125. .melt_quote(PaymentMethod::BOLT11, invoice.to_string(), None, None)
  1126. .await
  1127. .unwrap();
  1128. let melt_request = MeltRequest::new(melt_quote.id, proofs, None);
  1129. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1130. let response = http_client
  1131. .post_melt(
  1132. &PaymentMethod::Known(KnownMethod::Bolt11),
  1133. melt_request.clone(),
  1134. )
  1135. .await;
  1136. match response {
  1137. Err(err) => match err {
  1138. cdk::Error::TokenAlreadySpent => (),
  1139. err => {
  1140. panic!("Wrong mint error returned: {}", err);
  1141. }
  1142. },
  1143. Ok(_) => {
  1144. panic!("Should not have allowed to melt with multiple units");
  1145. }
  1146. }
  1147. }
  1148. /// Tests that attempting to swap with duplicate proofs fails
  1149. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1150. async fn test_fake_mint_duplicate_proofs_swap() {
  1151. let wallet = Wallet::new(
  1152. MINT_URL,
  1153. CurrencyUnit::Sat,
  1154. Arc::new(memory::empty().await.unwrap()),
  1155. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1156. None,
  1157. )
  1158. .expect("failed to create new wallet");
  1159. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  1160. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1161. let proofs = proof_streams
  1162. .next()
  1163. .await
  1164. .expect("payment")
  1165. .expect("no error");
  1166. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  1167. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  1168. let inputs = vec![proofs[0].clone(), proofs[0].clone()];
  1169. let pre_mint = PreMintSecrets::random(
  1170. active_keyset_id,
  1171. inputs.total_amount().unwrap(),
  1172. &SplitTarget::None,
  1173. &fee_and_amounts,
  1174. )
  1175. .unwrap();
  1176. let swap_request = SwapRequest::new(inputs.clone(), pre_mint.blinded_messages());
  1177. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1178. let response = http_client.post_swap(swap_request.clone()).await;
  1179. match response {
  1180. Err(err) => match err {
  1181. cdk::Error::DuplicateInputs => (),
  1182. err => {
  1183. panic!(
  1184. "Wrong mint error returned, expected duplicate inputs: {}",
  1185. err
  1186. );
  1187. }
  1188. },
  1189. Ok(_) => {
  1190. panic!("Should not have allowed duplicate inputs");
  1191. }
  1192. }
  1193. let blinded_message = pre_mint.blinded_messages();
  1194. let inputs = vec![proofs[0].clone()];
  1195. let outputs = vec![blinded_message[0].clone(), blinded_message[0].clone()];
  1196. let swap_request = SwapRequest::new(inputs, outputs);
  1197. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1198. let response = http_client.post_swap(swap_request.clone()).await;
  1199. match response {
  1200. Err(err) => match err {
  1201. cdk::Error::DuplicateOutputs => (),
  1202. err => {
  1203. panic!(
  1204. "Wrong mint error returned, expected duplicate outputs: {}",
  1205. err
  1206. );
  1207. }
  1208. },
  1209. Ok(_) => {
  1210. panic!("Should not have allow duplicate inputs");
  1211. }
  1212. }
  1213. }
  1214. /// Tests that attempting to melt with duplicate proofs fails
  1215. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1216. async fn test_fake_mint_duplicate_proofs_melt() {
  1217. let wallet = Wallet::new(
  1218. MINT_URL,
  1219. CurrencyUnit::Sat,
  1220. Arc::new(memory::empty().await.unwrap()),
  1221. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1222. None,
  1223. )
  1224. .expect("failed to create new wallet");
  1225. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  1226. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1227. let proofs = proof_streams
  1228. .next()
  1229. .await
  1230. .expect("payment")
  1231. .expect("no error");
  1232. let inputs = vec![proofs[0].clone(), proofs[0].clone()];
  1233. let invoice = create_fake_invoice(7000, "".to_string());
  1234. let melt_quote = wallet
  1235. .melt_quote(PaymentMethod::BOLT11, invoice.to_string(), None, None)
  1236. .await
  1237. .unwrap();
  1238. let melt_request = MeltRequest::new(melt_quote.id, inputs, None);
  1239. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1240. let response = http_client
  1241. .post_melt(
  1242. &PaymentMethod::Known(KnownMethod::Bolt11),
  1243. melt_request.clone(),
  1244. )
  1245. .await;
  1246. match response {
  1247. Err(err) => match err {
  1248. cdk::Error::DuplicateInputs => (),
  1249. err => {
  1250. panic!("Wrong mint error returned: {}", err);
  1251. }
  1252. },
  1253. Ok(_) => {
  1254. panic!("Should not have allow duplicate inputs");
  1255. }
  1256. }
  1257. }
  1258. /// Tests that wallet automatically recovers proofs after a failed melt operation
  1259. /// by swapping them to new proofs, preventing loss of funds
  1260. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1261. async fn test_wallet_proof_recovery_after_failed_melt() {
  1262. let wallet = Wallet::new(
  1263. MINT_URL,
  1264. CurrencyUnit::Sat,
  1265. Arc::new(memory::empty().await.unwrap()),
  1266. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1267. None,
  1268. )
  1269. .expect("failed to create new wallet");
  1270. // Mint 100 sats
  1271. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  1272. let _roof_streams = wallet
  1273. .wait_and_mint_quote(
  1274. mint_quote.clone(),
  1275. SplitTarget::default(),
  1276. None,
  1277. Duration::from_secs(1000),
  1278. )
  1279. .await;
  1280. assert_eq!(wallet.total_balance().await.unwrap(), Amount::from(100));
  1281. // Create a melt quote that will fail
  1282. let fake_description = FakeInvoiceDescription {
  1283. pay_invoice_state: MeltQuoteState::Unknown,
  1284. check_payment_state: MeltQuoteState::Unpaid,
  1285. pay_err: true,
  1286. check_err: false,
  1287. };
  1288. let invoice = create_fake_invoice(1000, serde_json::to_string(&fake_description).unwrap());
  1289. let melt_quote = wallet
  1290. .melt_quote(PaymentMethod::BOLT11, invoice.to_string(), None, None)
  1291. .await
  1292. .unwrap();
  1293. // Attempt to melt - this should fail but trigger proof recovery
  1294. let melt_result = async {
  1295. let prepared = wallet
  1296. .prepare_melt(&melt_quote.id, std::collections::HashMap::new())
  1297. .await?;
  1298. prepared.confirm().await
  1299. }
  1300. .await;
  1301. assert!(melt_result.is_err(), "Melt should have failed");
  1302. // Verify wallet still has balance (proofs recovered)
  1303. assert_eq!(
  1304. wallet.total_balance().await.unwrap(),
  1305. Amount::from(100),
  1306. "Balance should be recovered"
  1307. );
  1308. // Verify we can still spend the recovered proofs
  1309. let valid_invoice = create_fake_invoice(7000, "".to_string());
  1310. let valid_melt_quote = wallet
  1311. .melt_quote(PaymentMethod::BOLT11, valid_invoice.to_string(), None, None)
  1312. .await
  1313. .unwrap();
  1314. let successful_melt = async {
  1315. let prepared = wallet
  1316. .prepare_melt(&valid_melt_quote.id, std::collections::HashMap::new())
  1317. .await?;
  1318. prepared.confirm().await
  1319. }
  1320. .await;
  1321. assert!(
  1322. successful_melt.is_ok(),
  1323. "Should be able to spend recovered proofs"
  1324. );
  1325. }
  1326. /// Tests that concurrent melt attempts for the same invoice result in exactly one success
  1327. ///
  1328. /// This test verifies the race condition protection: when multiple melt quotes exist for the
  1329. /// same invoice and all are attempted concurrently, only one should succeed due to
  1330. /// the FOR UPDATE locking on quotes with the same request_lookup_id.
  1331. #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
  1332. async fn test_concurrent_melt_same_invoice() {
  1333. const NUM_WALLETS: usize = 4;
  1334. // Create multiple wallets to simulate concurrent requests
  1335. let mut wallets = Vec::with_capacity(NUM_WALLETS);
  1336. for i in 0..NUM_WALLETS {
  1337. let wallet = Arc::new(
  1338. Wallet::new(
  1339. MINT_URL,
  1340. CurrencyUnit::Sat,
  1341. Arc::new(memory::empty().await.unwrap()),
  1342. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1343. None,
  1344. )
  1345. .expect(&format!("failed to create wallet {}", i)),
  1346. );
  1347. wallets.push(wallet);
  1348. }
  1349. // Mint proofs for all wallets
  1350. for (i, wallet) in wallets.iter().enumerate() {
  1351. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  1352. let mut proof_streams =
  1353. wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1354. proof_streams
  1355. .next()
  1356. .await
  1357. .expect(&format!("payment for wallet {}", i))
  1358. .expect("no error");
  1359. }
  1360. // Create a single invoice that all wallets will try to pay
  1361. let fake_description = FakeInvoiceDescription::default();
  1362. let invoice = create_fake_invoice(9000, serde_json::to_string(&fake_description).unwrap());
  1363. // All wallets create melt quotes for the same invoice
  1364. let mut melt_quotes = Vec::with_capacity(NUM_WALLETS);
  1365. for wallet in &wallets {
  1366. let melt_quote = wallet
  1367. .melt_quote(PaymentMethod::BOLT11, invoice.to_string(), None, None)
  1368. .await
  1369. .unwrap();
  1370. melt_quotes.push(melt_quote);
  1371. }
  1372. // Verify all quotes have the same request (same invoice = same lookup_id)
  1373. for quote in &melt_quotes[1..] {
  1374. assert_eq!(
  1375. melt_quotes[0].request, quote.request,
  1376. "All quotes should be for the same invoice"
  1377. );
  1378. }
  1379. // Attempt all melts concurrently
  1380. let mut handles = Vec::with_capacity(NUM_WALLETS);
  1381. for (wallet, quote) in wallets.iter().zip(melt_quotes.iter()) {
  1382. let wallet_clone = Arc::clone(wallet);
  1383. let quote_id = quote.id.clone();
  1384. handles.push(tokio::spawn(async move {
  1385. let prepared = wallet_clone
  1386. .prepare_melt(&quote_id, std::collections::HashMap::new())
  1387. .await?;
  1388. prepared.confirm().await
  1389. }));
  1390. }
  1391. // Collect results
  1392. let mut results = Vec::with_capacity(NUM_WALLETS);
  1393. for handle in handles {
  1394. results.push(handle.await.expect("task panicked"));
  1395. }
  1396. // Count successes and failures
  1397. let success_count = results.iter().filter(|r| r.is_ok()).count();
  1398. let failure_count = results.iter().filter(|r| r.is_err()).count();
  1399. assert_eq!(
  1400. success_count, 1,
  1401. "Expected exactly one successful melt, got {}. Results: {:?}",
  1402. success_count, results
  1403. );
  1404. assert_eq!(
  1405. failure_count,
  1406. NUM_WALLETS - 1,
  1407. "Expected {} failed melts, got {}",
  1408. NUM_WALLETS - 1,
  1409. failure_count
  1410. );
  1411. // Verify all failures were due to duplicate detection
  1412. for result in &results {
  1413. if let Err(err) = result {
  1414. let err_str = err.to_string().to_lowercase();
  1415. assert!(
  1416. err_str.contains("duplicate")
  1417. || err_str.contains("already paid")
  1418. || err_str.contains("pending")
  1419. || err_str.contains("payment failed"),
  1420. "Expected duplicate/already paid/pending/payment failed error, got: {}",
  1421. err
  1422. );
  1423. }
  1424. }
  1425. }
  1426. /// Tests that wallet automatically recovers proofs after a failed swap operation
  1427. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1428. async fn test_wallet_proof_recovery_after_failed_swap() {
  1429. let wallet = Wallet::new(
  1430. MINT_URL,
  1431. CurrencyUnit::Sat,
  1432. Arc::new(memory::empty().await.unwrap()),
  1433. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1434. None,
  1435. )
  1436. .expect("failed to create new wallet");
  1437. // Mint 100 sats
  1438. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  1439. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1440. let initial_proofs = proof_streams
  1441. .next()
  1442. .await
  1443. .expect("payment")
  1444. .expect("no error");
  1445. let initial_ys: Vec<_> = initial_proofs.iter().map(|p| p.y().unwrap()).collect();
  1446. assert_eq!(wallet.total_balance().await.unwrap(), Amount::from(100));
  1447. let unspent_proofs = wallet.get_unspent_proofs().await.unwrap();
  1448. // Create an invalid swap by manually constructing a request that will fail
  1449. // We'll use the wallet's swap with invalid parameters to trigger a failure
  1450. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  1451. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  1452. // Create invalid swap request (requesting more than we have)
  1453. let preswap = PreMintSecrets::random(
  1454. active_keyset_id,
  1455. 1000.into(), // More than the 100 we have
  1456. &SplitTarget::default(),
  1457. &fee_and_amounts,
  1458. )
  1459. .unwrap();
  1460. let swap_request = SwapRequest::new(unspent_proofs.clone(), preswap.blinded_messages());
  1461. // Use HTTP client directly to bypass wallet's validation and trigger recovery
  1462. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1463. let response = http_client.post_swap(swap_request).await;
  1464. assert!(response.is_err(), "Swap should have failed");
  1465. // Note: The HTTP client doesn't trigger the wallet's try_proof_operation wrapper
  1466. // So we need to test through the wallet's own methods
  1467. // After the failed HTTP request, the proofs are still in the wallet's database
  1468. // Verify balance is still available after the failed operation
  1469. assert_eq!(
  1470. wallet.total_balance().await.unwrap(),
  1471. Amount::from(100),
  1472. "Balance should still be available"
  1473. );
  1474. // Verify we can perform a successful swap operation
  1475. let successful_swap = wallet
  1476. .swap(None, SplitTarget::None, unspent_proofs, None, false)
  1477. .await;
  1478. assert!(
  1479. successful_swap.is_ok(),
  1480. "Should be able to swap after failed operation"
  1481. );
  1482. // Verify the proofs were swapped to new ones
  1483. let final_proofs = wallet.get_unspent_proofs().await.unwrap();
  1484. let final_ys: Vec<_> = final_proofs.iter().map(|p| p.y().unwrap()).collect();
  1485. // The Ys should be different after the successful swap
  1486. assert!(
  1487. initial_ys.iter().any(|y| !final_ys.contains(y)),
  1488. "Proofs should have been swapped to new ones"
  1489. );
  1490. }
  1491. /// Tests that melt_proofs works correctly with proofs that are not already in the wallet's database.
  1492. /// This is similar to the receive flow where proofs come from an external source.
  1493. ///
  1494. /// Flow:
  1495. /// 1. Wallet A mints proofs (proofs ARE in Wallet A's database)
  1496. /// 2. Wallet B creates a melt quote
  1497. /// 3. Wallet B calls melt_proofs with proofs from Wallet A (proofs are NOT in Wallet B's database)
  1498. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1499. async fn test_melt_proofs_external() {
  1500. // Create sender wallet (Wallet A) and mint some proofs
  1501. let wallet_sender = Wallet::new(
  1502. MINT_URL,
  1503. CurrencyUnit::Sat,
  1504. Arc::new(memory::empty().await.unwrap()),
  1505. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1506. None,
  1507. )
  1508. .expect("failed to create sender wallet");
  1509. let mint_quote = wallet_sender.mint_quote(100.into(), None).await.unwrap();
  1510. let mut proof_streams =
  1511. wallet_sender.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1512. let proofs = proof_streams
  1513. .next()
  1514. .await
  1515. .expect("payment")
  1516. .expect("no error");
  1517. assert_eq!(proofs.total_amount().unwrap(), Amount::from(100));
  1518. // Create receiver/melter wallet (Wallet B) with a separate database
  1519. // These proofs are NOT in Wallet B's database
  1520. let wallet_melter = Wallet::new(
  1521. MINT_URL,
  1522. CurrencyUnit::Sat,
  1523. Arc::new(memory::empty().await.unwrap()),
  1524. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1525. None,
  1526. )
  1527. .expect("failed to create melter wallet");
  1528. // Verify proofs are not in the melter wallet's database
  1529. let melter_proofs = wallet_melter.get_unspent_proofs().await.unwrap();
  1530. assert!(
  1531. melter_proofs.is_empty(),
  1532. "Melter wallet should have no proofs initially"
  1533. );
  1534. // Create a fake invoice for melting
  1535. let fake_description = FakeInvoiceDescription::default();
  1536. let invoice = create_fake_invoice(9000, serde_json::to_string(&fake_description).unwrap());
  1537. // Wallet B creates a melt quote
  1538. let melt_quote = wallet_melter
  1539. .melt_quote(PaymentMethod::BOLT11, invoice.to_string(), None, None)
  1540. .await
  1541. .unwrap();
  1542. // Wallet B calls melt_proofs with external proofs (from Wallet A)
  1543. // These proofs are NOT in wallet_melter's database
  1544. let prepared = wallet_melter
  1545. .prepare_melt_proofs(
  1546. &melt_quote.id,
  1547. proofs.clone(),
  1548. std::collections::HashMap::new(),
  1549. )
  1550. .await
  1551. .unwrap();
  1552. let melted = prepared.confirm().await.unwrap();
  1553. // Verify the melt succeeded
  1554. assert_eq!(melted.amount(), Amount::from(9));
  1555. assert_eq!(melted.fee_paid(), 1.into());
  1556. // Verify change was returned (100 input - 9 melt amount = 91 change, minus fee reserve)
  1557. assert!(melted.change().is_some());
  1558. let change_amount = melted.change().unwrap().total_amount().unwrap();
  1559. assert!(change_amount > Amount::ZERO, "Should have received change");
  1560. // Verify the melter wallet now has the change proofs
  1561. let melter_balance = wallet_melter.total_balance().await.unwrap();
  1562. assert_eq!(melter_balance, change_amount);
  1563. // Verify a transaction was recorded
  1564. let transactions = wallet_melter
  1565. .list_transactions(Some(TransactionDirection::Outgoing))
  1566. .await
  1567. .unwrap();
  1568. assert_eq!(transactions.len(), 1);
  1569. assert_eq!(transactions[0].amount, Amount::from(9));
  1570. }
  1571. /// Tests that melt automatically performs a swap when proofs don't exactly match
  1572. /// the required amount (quote + fee_reserve + input_fee).
  1573. ///
  1574. /// This test verifies the swap-before-melt optimization:
  1575. /// 1. Mint proofs that will NOT exactly match a melt amount
  1576. /// 2. Create a melt quote for a specific amount
  1577. /// 3. Call melt() - it should automatically swap proofs to get exact denominations
  1578. /// 4. Verify the melt succeeded
  1579. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1580. async fn test_melt_with_swap_for_exact_amount() {
  1581. let wallet = Wallet::new(
  1582. MINT_URL,
  1583. CurrencyUnit::Sat,
  1584. Arc::new(memory::empty().await.unwrap()),
  1585. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1586. None,
  1587. )
  1588. .expect("failed to create new wallet");
  1589. // Mint 100 sats - this will give us proofs in standard denominations
  1590. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  1591. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1592. let proofs = proof_streams
  1593. .next()
  1594. .await
  1595. .expect("payment")
  1596. .expect("no error");
  1597. let initial_balance = wallet.total_balance().await.unwrap();
  1598. assert_eq!(initial_balance, Amount::from(100));
  1599. // Log the proof denominations we received
  1600. let proof_amounts: Vec<u64> = proofs.iter().map(|p| u64::from(p.amount)).collect();
  1601. tracing::info!("Initial proof denominations: {:?}", proof_amounts);
  1602. // Create a melt quote for an amount that likely won't match our proof denominations exactly
  1603. // Using 7 sats (7000 msats) which requires specific denominations
  1604. let fake_description = FakeInvoiceDescription::default();
  1605. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  1606. let melt_quote = wallet
  1607. .melt_quote(PaymentMethod::BOLT11, invoice.to_string(), None, None)
  1608. .await
  1609. .unwrap();
  1610. tracing::info!(
  1611. "Melt quote: amount={}, fee_reserve={}",
  1612. melt_quote.amount,
  1613. melt_quote.fee_reserve
  1614. );
  1615. // Call melt() - this should trigger swap-before-melt if proofs don't match exactly
  1616. let prepared = wallet
  1617. .prepare_melt(&melt_quote.id, std::collections::HashMap::new())
  1618. .await
  1619. .unwrap();
  1620. let melted = prepared.confirm().await.unwrap();
  1621. // Verify the melt succeeded
  1622. assert_eq!(melted.amount(), Amount::from(7));
  1623. tracing::info!(
  1624. "Melt completed: amount={}, fee_paid={}",
  1625. melted.amount(),
  1626. melted.fee_paid()
  1627. );
  1628. // Verify final balance is correct (initial - melt_amount - fees)
  1629. let final_balance = wallet.total_balance().await.unwrap();
  1630. tracing::info!(
  1631. "Balance: initial={}, final={}, paid={}",
  1632. initial_balance,
  1633. final_balance,
  1634. melted.amount() + melted.fee_paid()
  1635. );
  1636. assert!(
  1637. final_balance < initial_balance,
  1638. "Balance should have decreased after melt"
  1639. );
  1640. assert_eq!(
  1641. final_balance,
  1642. initial_balance - melted.amount() - melted.fee_paid(),
  1643. "Final balance should be initial - amount - fees"
  1644. );
  1645. }
  1646. /// Tests that melt works correctly when proofs already exactly match the required amount.
  1647. /// In this case, no swap should be needed.
  1648. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1649. async fn test_melt_exact_proofs_no_swap_needed() {
  1650. let wallet = Wallet::new(
  1651. MINT_URL,
  1652. CurrencyUnit::Sat,
  1653. Arc::new(memory::empty().await.unwrap()),
  1654. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1655. None,
  1656. )
  1657. .expect("failed to create new wallet");
  1658. // Mint a larger amount to have more denomination options
  1659. let mint_quote = wallet.mint_quote(1000.into(), None).await.unwrap();
  1660. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1661. let _proofs = proof_streams
  1662. .next()
  1663. .await
  1664. .expect("payment")
  1665. .expect("no error");
  1666. let initial_balance = wallet.total_balance().await.unwrap();
  1667. assert_eq!(initial_balance, Amount::from(1000));
  1668. // Create a melt for a power-of-2 amount that's more likely to match existing denominations
  1669. let fake_description = FakeInvoiceDescription::default();
  1670. let invoice = create_fake_invoice(64_000, serde_json::to_string(&fake_description).unwrap()); // 64 sats
  1671. let melt_quote = wallet
  1672. .melt_quote(PaymentMethod::BOLT11, invoice.to_string(), None, None)
  1673. .await
  1674. .unwrap();
  1675. // Melt should succeed
  1676. let prepared = wallet
  1677. .prepare_melt(&melt_quote.id, std::collections::HashMap::new())
  1678. .await
  1679. .unwrap();
  1680. let melted = prepared.confirm().await.unwrap();
  1681. assert_eq!(melted.amount(), Amount::from(64));
  1682. let final_balance = wallet.total_balance().await.unwrap();
  1683. assert_eq!(
  1684. final_balance,
  1685. initial_balance - melted.amount() - melted.fee_paid()
  1686. );
  1687. }
  1688. /// Tests the check_all_mint_quotes functionality for Bolt11 quotes
  1689. ///
  1690. /// This test verifies that:
  1691. /// 1. Paid mint quotes are automatically minted when check_all_mint_quotes is called
  1692. /// 2. The total amount returned matches the minted proofs
  1693. /// 3. Quote state is properly updated after minting
  1694. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1695. async fn test_check_all_mint_quotes_bolt11() {
  1696. let wallet = Wallet::new(
  1697. MINT_URL,
  1698. CurrencyUnit::Sat,
  1699. Arc::new(memory::empty().await.unwrap()),
  1700. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1701. None,
  1702. )
  1703. .expect("failed to create new wallet");
  1704. // Create first mint quote and pay it (using proof_stream triggers fake wallet payment)
  1705. let mint_quote_1 = wallet.mint_quote(100.into(), None).await.unwrap();
  1706. // Wait for the payment to be registered (fake wallet auto-pays)
  1707. let mut payment_stream_1 = wallet.payment_stream(&mint_quote_1);
  1708. payment_stream_1
  1709. .next()
  1710. .await
  1711. .expect("payment")
  1712. .expect("no error");
  1713. // Create second mint quote and pay it
  1714. let mint_quote_2 = wallet.mint_quote(50.into(), None).await.unwrap();
  1715. let mut payment_stream_2 = wallet.payment_stream(&mint_quote_2);
  1716. payment_stream_2
  1717. .next()
  1718. .await
  1719. .expect("payment")
  1720. .expect("no error");
  1721. // Verify no proofs have been minted yet
  1722. assert_eq!(wallet.total_balance().await.unwrap(), Amount::ZERO);
  1723. // Call mint_unissued_quotes - this should mint both paid quotes
  1724. let total_minted = wallet.mint_unissued_quotes().await.unwrap();
  1725. // Verify the total amount minted is correct (100 + 50 = 150)
  1726. assert_eq!(total_minted, Amount::from(150));
  1727. // Verify wallet balance matches
  1728. assert_eq!(wallet.total_balance().await.unwrap(), Amount::from(150));
  1729. // Calling mint_unissued_quotes again should return 0 (quotes already minted)
  1730. let second_check = wallet.mint_unissued_quotes().await.unwrap();
  1731. assert_eq!(second_check, Amount::ZERO);
  1732. }
  1733. /// Tests the get_unissued_mint_quotes wallet method
  1734. ///
  1735. /// This test verifies that:
  1736. /// 1. Unpaid quotes are included (wallet needs to check with mint)
  1737. /// 2. Paid but not issued quotes are included
  1738. /// 3. Fully issued quotes are excluded
  1739. /// 4. Only quotes for the current mint URL are returned
  1740. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1741. async fn test_get_unissued_mint_quotes_wallet() {
  1742. let wallet = Wallet::new(
  1743. MINT_URL,
  1744. CurrencyUnit::Sat,
  1745. Arc::new(memory::empty().await.unwrap()),
  1746. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1747. None,
  1748. )
  1749. .expect("failed to create new wallet");
  1750. // Create a quote but don't pay it (stays unpaid)
  1751. let unpaid_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  1752. // Create another quote and pay it but don't mint
  1753. let paid_quote = wallet.mint_quote(50.into(), None).await.unwrap();
  1754. let mut payment_stream = wallet.payment_stream(&paid_quote);
  1755. payment_stream
  1756. .next()
  1757. .await
  1758. .expect("payment")
  1759. .expect("no error");
  1760. // Create a third quote and fully mint it
  1761. let minted_quote = wallet.mint_quote(25.into(), None).await.unwrap();
  1762. let mut proof_stream = wallet.proof_stream(minted_quote.clone(), SplitTarget::default(), None);
  1763. proof_stream
  1764. .next()
  1765. .await
  1766. .expect("payment")
  1767. .expect("no error");
  1768. // Get unissued quotes
  1769. let unissued_quotes = wallet.get_unissued_mint_quotes().await.unwrap();
  1770. // Should have 2 quotes: unpaid and paid-but-not-issued
  1771. // The fully minted quote should be excluded
  1772. assert_eq!(
  1773. unissued_quotes.len(),
  1774. 2,
  1775. "Should have 2 unissued quotes (unpaid and paid-not-issued)"
  1776. );
  1777. let quote_ids: Vec<&str> = unissued_quotes.iter().map(|q| q.id.as_str()).collect();
  1778. assert!(
  1779. quote_ids.contains(&unpaid_quote.id.as_str()),
  1780. "Unpaid quote should be included"
  1781. );
  1782. assert!(
  1783. quote_ids.contains(&paid_quote.id.as_str()),
  1784. "Paid but not issued quote should be included"
  1785. );
  1786. assert!(
  1787. !quote_ids.contains(&minted_quote.id.as_str()),
  1788. "Fully minted quote should NOT be included"
  1789. );
  1790. }
  1791. /// Tests that mint quote state is properly updated after minting
  1792. ///
  1793. /// This test verifies that:
  1794. /// 1. amount_issued is updated after successful minting
  1795. /// 2. Quote state is updated correctly
  1796. /// 3. The quote is stored properly in the localstore
  1797. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1798. async fn test_refresh_mint_quote_status_updates_after_minting() {
  1799. let wallet = Wallet::new(
  1800. MINT_URL,
  1801. CurrencyUnit::Sat,
  1802. Arc::new(memory::empty().await.unwrap()),
  1803. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1804. None,
  1805. )
  1806. .expect("failed to create new wallet");
  1807. let mint_amount = Amount::from(100);
  1808. let mint_quote = wallet.mint_quote(mint_amount, None).await.unwrap();
  1809. // Get the quote from localstore before minting
  1810. let quote_before = wallet
  1811. .localstore
  1812. .get_mint_quote(&mint_quote.id)
  1813. .await
  1814. .unwrap()
  1815. .expect("Quote should exist");
  1816. // Verify initial state
  1817. assert_eq!(quote_before.amount_issued, Amount::ZERO);
  1818. // Mint the tokens using wait_and_mint_quote
  1819. let proofs = wallet
  1820. .wait_and_mint_quote(
  1821. mint_quote.clone(),
  1822. SplitTarget::default(),
  1823. None,
  1824. Duration::from_secs(60),
  1825. )
  1826. .await
  1827. .expect("minting should succeed");
  1828. let minted_amount = proofs.total_amount().unwrap();
  1829. assert_eq!(minted_amount, mint_amount);
  1830. // Check the quote is now either removed or updated in the localstore
  1831. // After minting, the quote should be removed from localstore (it's fully issued)
  1832. let quote_after = wallet
  1833. .localstore
  1834. .get_mint_quote(&mint_quote.id)
  1835. .await
  1836. .unwrap();
  1837. // The quote should either be removed or have amount_issued updated
  1838. match quote_after {
  1839. Some(quote) => {
  1840. // If still present, amount_issued should equal the minted amount
  1841. assert_eq!(
  1842. quote.amount_issued, minted_amount,
  1843. "amount_issued should be updated after minting"
  1844. );
  1845. }
  1846. None => {
  1847. // Quote was removed after being fully issued - this is also valid behavior
  1848. }
  1849. }
  1850. // Verify the unissued quotes no longer contains this quote
  1851. let unissued = wallet.get_unissued_mint_quotes().await.unwrap();
  1852. let unissued_ids: Vec<&str> = unissued.iter().map(|q| q.id.as_str()).collect();
  1853. assert!(
  1854. !unissued_ids.contains(&mint_quote.id.as_str()),
  1855. "Fully minted quote should not appear in unissued quotes"
  1856. );
  1857. }