fake_wallet.rs 73 KB

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