fake_wallet.rs 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863
  1. //! Fake Wallet Integration Tests
  2. //!
  3. //! This file contains tests for the fake wallet backend functionality.
  4. //! The fake wallet simulates Lightning Network behavior for testing purposes,
  5. //! allowing verification of mint behavior in various payment scenarios without
  6. //! requiring a real Lightning node.
  7. //!
  8. //! Test Scenarios:
  9. //! - Pending payment states and proof handling
  10. //! - Payment failure cases and proof state management
  11. //! - Change output verification in melt operations
  12. //! - Witness signature validation
  13. //! - Cross-unit transaction validation
  14. //! - Overflow and balance validation
  15. //! - Duplicate proof detection
  16. use std::sync::Arc;
  17. use std::time::Duration;
  18. use bip39::Mnemonic;
  19. use cashu::Amount;
  20. use cdk::amount::SplitTarget;
  21. use cdk::nuts::nut00::ProofsMethods;
  22. use cdk::nuts::{
  23. CurrencyUnit, MeltQuoteState, MeltRequest, MintRequest, PreMintSecrets, Proofs, SecretKey,
  24. State, SwapRequest,
  25. };
  26. use cdk::wallet::types::TransactionDirection;
  27. use cdk::wallet::{HttpClient, MintConnector, Wallet};
  28. use cdk::StreamExt;
  29. use cdk_fake_wallet::{create_fake_invoice, FakeInvoiceDescription};
  30. use cdk_sqlite::wallet::memory;
  31. const MINT_URL: &str = "http://127.0.0.1:8086";
  32. /// Tests that when both pay and check return pending status, input proofs should remain pending
  33. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  34. async fn test_fake_tokens_pending() {
  35. let wallet = Wallet::new(
  36. MINT_URL,
  37. CurrencyUnit::Sat,
  38. Arc::new(memory::empty().await.unwrap()),
  39. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  40. None,
  41. )
  42. .expect("failed to create new wallet");
  43. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  44. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  45. let _proofs = proof_streams
  46. .next()
  47. .await
  48. .expect("payment")
  49. .expect("no error");
  50. let fake_description = FakeInvoiceDescription {
  51. pay_invoice_state: MeltQuoteState::Pending,
  52. check_payment_state: MeltQuoteState::Pending,
  53. pay_err: false,
  54. check_err: false,
  55. };
  56. let invoice = create_fake_invoice(1000, serde_json::to_string(&fake_description).unwrap());
  57. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  58. let melt = wallet.melt(&melt_quote.id).await;
  59. assert!(melt.is_err());
  60. // melt failed, but there is new code to reclaim unspent proofs
  61. assert!(!wallet
  62. .localstore
  63. .get_proofs(None, None, Some(vec![State::Pending]), None)
  64. .await
  65. .unwrap()
  66. .is_empty());
  67. }
  68. /// Tests that if the pay error fails and the check returns unknown or failed,
  69. /// the input proofs should be unset as spending (returned to unspent state)
  70. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  71. async fn test_fake_melt_payment_fail() {
  72. let wallet = Wallet::new(
  73. MINT_URL,
  74. CurrencyUnit::Sat,
  75. Arc::new(memory::empty().await.unwrap()),
  76. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  77. None,
  78. )
  79. .expect("Failed to create new wallet");
  80. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  81. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  82. let _proofs = proof_streams
  83. .next()
  84. .await
  85. .expect("payment")
  86. .expect("no error");
  87. let fake_description = FakeInvoiceDescription {
  88. pay_invoice_state: MeltQuoteState::Unknown,
  89. check_payment_state: MeltQuoteState::Unknown,
  90. pay_err: true,
  91. check_err: false,
  92. };
  93. let invoice = create_fake_invoice(1000, serde_json::to_string(&fake_description).unwrap());
  94. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  95. // The melt should error at the payment invoice command
  96. let melt = wallet.melt(&melt_quote.id).await;
  97. assert!(melt.is_err());
  98. let fake_description = FakeInvoiceDescription {
  99. pay_invoice_state: MeltQuoteState::Failed,
  100. check_payment_state: MeltQuoteState::Failed,
  101. pay_err: true,
  102. check_err: false,
  103. };
  104. let invoice = create_fake_invoice(1000, serde_json::to_string(&fake_description).unwrap());
  105. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  106. // The melt should error at the payment invoice command
  107. let melt = wallet.melt(&melt_quote.id).await;
  108. assert!(melt.is_err());
  109. let wallet_bal = wallet.total_balance().await.unwrap();
  110. assert_eq!(wallet_bal, 98.into());
  111. }
  112. /// Tests that when both the pay_invoice and check_invoice both fail,
  113. /// the proofs should remain in pending state
  114. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  115. async fn test_fake_melt_payment_fail_and_check() {
  116. let wallet = Wallet::new(
  117. MINT_URL,
  118. CurrencyUnit::Sat,
  119. Arc::new(memory::empty().await.unwrap()),
  120. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  121. None,
  122. )
  123. .expect("Failed to create new wallet");
  124. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  125. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  126. let _proofs = proof_streams
  127. .next()
  128. .await
  129. .expect("payment")
  130. .expect("no error");
  131. let fake_description = FakeInvoiceDescription {
  132. pay_invoice_state: MeltQuoteState::Unknown,
  133. check_payment_state: MeltQuoteState::Unknown,
  134. pay_err: true,
  135. check_err: true,
  136. };
  137. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  138. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  139. // The melt should error at the payment invoice command
  140. let melt = wallet.melt(&melt_quote.id).await;
  141. assert!(melt.is_err());
  142. assert!(!wallet
  143. .localstore
  144. .get_proofs(None, None, Some(vec![State::Pending]), None)
  145. .await
  146. .unwrap()
  147. .is_empty());
  148. }
  149. /// Tests that when the ln backend returns a failed status but does not error,
  150. /// the mint should do a second check, then remove proofs from pending state
  151. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  152. async fn test_fake_melt_payment_return_fail_status() {
  153. let wallet = Wallet::new(
  154. MINT_URL,
  155. CurrencyUnit::Sat,
  156. Arc::new(memory::empty().await.unwrap()),
  157. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  158. None,
  159. )
  160. .expect("Failed to create new wallet");
  161. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  162. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  163. let _proofs = proof_streams
  164. .next()
  165. .await
  166. .expect("payment")
  167. .expect("no error");
  168. let fake_description = FakeInvoiceDescription {
  169. pay_invoice_state: MeltQuoteState::Failed,
  170. check_payment_state: MeltQuoteState::Failed,
  171. pay_err: false,
  172. check_err: false,
  173. };
  174. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  175. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  176. // The melt should error at the payment invoice command
  177. let melt = wallet.melt(&melt_quote.id).await;
  178. assert!(melt.is_err());
  179. wallet.check_all_pending_proofs().await.unwrap();
  180. let pending = wallet
  181. .localstore
  182. .get_proofs(None, None, Some(vec![State::Pending]), None)
  183. .await
  184. .unwrap();
  185. assert!(pending.is_empty());
  186. let fake_description = FakeInvoiceDescription {
  187. pay_invoice_state: MeltQuoteState::Unknown,
  188. check_payment_state: MeltQuoteState::Unknown,
  189. pay_err: false,
  190. check_err: false,
  191. };
  192. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  193. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  194. // The melt should error at the payment invoice command
  195. let melt = wallet.melt(&melt_quote.id).await;
  196. assert!(melt.is_err());
  197. wallet.check_all_pending_proofs().await.unwrap();
  198. assert!(!wallet
  199. .localstore
  200. .get_proofs(None, None, Some(vec![State::Pending]), None)
  201. .await
  202. .unwrap()
  203. .is_empty());
  204. }
  205. /// Tests that when the ln backend returns an error with unknown status,
  206. /// the mint should do a second check, then remove proofs from pending state
  207. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  208. async fn test_fake_melt_payment_error_unknown() {
  209. let wallet = Wallet::new(
  210. MINT_URL,
  211. CurrencyUnit::Sat,
  212. Arc::new(memory::empty().await.unwrap()),
  213. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  214. None,
  215. )
  216. .unwrap();
  217. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  218. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  219. let _proofs = proof_streams
  220. .next()
  221. .await
  222. .expect("payment")
  223. .expect("no error");
  224. let fake_description = FakeInvoiceDescription {
  225. pay_invoice_state: MeltQuoteState::Failed,
  226. check_payment_state: MeltQuoteState::Unknown,
  227. pay_err: true,
  228. check_err: false,
  229. };
  230. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  231. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  232. // The melt should error at the payment invoice command
  233. let melt = wallet.melt(&melt_quote.id).await;
  234. assert!(melt.is_err());
  235. let fake_description = FakeInvoiceDescription {
  236. pay_invoice_state: MeltQuoteState::Unknown,
  237. check_payment_state: MeltQuoteState::Unknown,
  238. pay_err: true,
  239. check_err: false,
  240. };
  241. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  242. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  243. // The melt should error at the payment invoice command
  244. let melt = wallet.melt(&melt_quote.id).await;
  245. assert!(melt.is_err());
  246. assert!(!wallet
  247. .localstore
  248. .get_proofs(None, None, Some(vec![State::Pending]), None)
  249. .await
  250. .unwrap()
  251. .is_empty());
  252. }
  253. /// Tests that when the ln backend returns an error but the second check returns paid,
  254. /// proofs should remain in pending state
  255. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  256. async fn test_fake_melt_payment_err_paid() {
  257. let wallet = Wallet::new(
  258. MINT_URL,
  259. CurrencyUnit::Sat,
  260. Arc::new(memory::empty().await.unwrap()),
  261. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  262. None,
  263. )
  264. .expect("Failed to create new wallet");
  265. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  266. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  267. let _proofs = proof_streams
  268. .next()
  269. .await
  270. .expect("payment")
  271. .expect("no error");
  272. let old_balance = wallet.total_balance().await.expect("balance");
  273. let fake_description = FakeInvoiceDescription {
  274. pay_invoice_state: MeltQuoteState::Failed,
  275. check_payment_state: MeltQuoteState::Paid,
  276. pay_err: true,
  277. check_err: false,
  278. };
  279. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  280. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  281. // The melt should error at the payment invoice command
  282. let melt = wallet.melt(&melt_quote.id).await.unwrap();
  283. assert!(melt.fee_paid == Amount::ZERO);
  284. assert!(melt.amount == Amount::from(7));
  285. // melt failed, but there is new code to reclaim unspent proofs
  286. assert_eq!(
  287. old_balance - melt.amount,
  288. wallet.total_balance().await.expect("new balance")
  289. );
  290. assert!(wallet
  291. .localstore
  292. .get_proofs(None, None, Some(vec![State::Pending]), None)
  293. .await
  294. .unwrap()
  295. .is_empty());
  296. }
  297. /// Tests that change outputs in a melt quote are correctly handled
  298. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  299. async fn test_fake_melt_change_in_quote() {
  300. let wallet = Wallet::new(
  301. MINT_URL,
  302. CurrencyUnit::Sat,
  303. Arc::new(memory::empty().await.unwrap()),
  304. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  305. None,
  306. )
  307. .expect("Failed to create new wallet");
  308. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  309. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  310. let _proofs = proof_streams
  311. .next()
  312. .await
  313. .expect("payment")
  314. .expect("no error");
  315. let transaction = wallet
  316. .list_transactions(Some(TransactionDirection::Incoming))
  317. .await
  318. .unwrap()
  319. .pop()
  320. .expect("No transaction found");
  321. assert_eq!(wallet.mint_url, transaction.mint_url);
  322. assert_eq!(TransactionDirection::Incoming, transaction.direction);
  323. assert_eq!(Amount::from(100), transaction.amount);
  324. assert_eq!(Amount::from(0), transaction.fee);
  325. assert_eq!(CurrencyUnit::Sat, transaction.unit);
  326. let fake_description = FakeInvoiceDescription::default();
  327. let invoice = create_fake_invoice(9000, serde_json::to_string(&fake_description).unwrap());
  328. let proofs = wallet.get_unspent_proofs().await.unwrap();
  329. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  330. let keyset = wallet.fetch_active_keyset().await.unwrap();
  331. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  332. let premint_secrets = PreMintSecrets::random(
  333. keyset.id,
  334. 100.into(),
  335. &SplitTarget::default(),
  336. &fee_and_amounts,
  337. )
  338. .unwrap();
  339. let client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  340. let melt_request = MeltRequest::new(
  341. melt_quote.id.clone(),
  342. proofs.clone(),
  343. Some(premint_secrets.blinded_messages()),
  344. );
  345. let melt_response = client.post_melt(melt_request).await.unwrap();
  346. assert!(melt_response.change.is_some());
  347. let check = wallet.melt_quote_status(&melt_quote.id).await.unwrap();
  348. let mut melt_change = melt_response.change.unwrap();
  349. melt_change.sort_by(|a, b| a.amount.cmp(&b.amount));
  350. let mut check = check.change.unwrap();
  351. check.sort_by(|a, b| a.amount.cmp(&b.amount));
  352. assert_eq!(melt_change, check);
  353. }
  354. /// Tests minting tokens with a valid witness signature
  355. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  356. async fn test_fake_mint_with_witness() {
  357. let wallet = Wallet::new(
  358. MINT_URL,
  359. CurrencyUnit::Sat,
  360. Arc::new(memory::empty().await.unwrap()),
  361. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  362. None,
  363. )
  364. .expect("failed to create new wallet");
  365. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  366. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  367. let proofs = proof_streams
  368. .next()
  369. .await
  370. .expect("payment")
  371. .expect("no error");
  372. let mint_amount = proofs.total_amount().unwrap();
  373. assert!(mint_amount == 100.into());
  374. }
  375. /// Tests that minting without a witness signature fails with the correct error
  376. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  377. async fn test_fake_mint_without_witness() {
  378. let wallet = Wallet::new(
  379. MINT_URL,
  380. CurrencyUnit::Sat,
  381. Arc::new(memory::empty().await.unwrap()),
  382. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  383. None,
  384. )
  385. .expect("failed to create new wallet");
  386. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  387. let mut payment_streams = wallet.payment_stream(&mint_quote);
  388. payment_streams
  389. .next()
  390. .await
  391. .expect("payment")
  392. .expect("no error");
  393. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  394. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  395. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  396. let premint_secrets = PreMintSecrets::random(
  397. active_keyset_id,
  398. 100.into(),
  399. &SplitTarget::default(),
  400. &fee_and_amounts,
  401. )
  402. .unwrap();
  403. let request = MintRequest {
  404. quote: mint_quote.id,
  405. outputs: premint_secrets.blinded_messages(),
  406. signature: None,
  407. };
  408. let response = http_client.post_mint(request.clone()).await;
  409. match response {
  410. Err(cdk::error::Error::SignatureMissingOrInvalid) => {} //pass
  411. Err(err) => panic!("Wrong mint response for minting without witness: {}", err),
  412. Ok(_) => panic!("Minting should not have succeed without a witness"),
  413. }
  414. }
  415. /// Tests that minting with an incorrect witness signature fails with the correct error
  416. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  417. async fn test_fake_mint_with_wrong_witness() {
  418. let wallet = Wallet::new(
  419. MINT_URL,
  420. CurrencyUnit::Sat,
  421. Arc::new(memory::empty().await.unwrap()),
  422. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  423. None,
  424. )
  425. .expect("failed to create new wallet");
  426. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  427. let mut payment_streams = wallet.payment_stream(&mint_quote);
  428. payment_streams
  429. .next()
  430. .await
  431. .expect("payment")
  432. .expect("no error");
  433. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  434. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  435. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  436. let premint_secrets = PreMintSecrets::random(
  437. active_keyset_id,
  438. 100.into(),
  439. &SplitTarget::default(),
  440. &fee_and_amounts,
  441. )
  442. .unwrap();
  443. let mut request = MintRequest {
  444. quote: mint_quote.id,
  445. outputs: premint_secrets.blinded_messages(),
  446. signature: None,
  447. };
  448. let secret_key = SecretKey::generate();
  449. request
  450. .sign(secret_key)
  451. .expect("failed to sign the mint request");
  452. let response = http_client.post_mint(request.clone()).await;
  453. match response {
  454. Err(cdk::error::Error::SignatureMissingOrInvalid) => {} //pass
  455. Err(err) => panic!("Wrong mint response for minting without witness: {}", err),
  456. Ok(_) => panic!("Minting should not have succeed without a witness"),
  457. }
  458. }
  459. /// Tests that attempting to mint more tokens than allowed by the quote fails
  460. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  461. async fn test_fake_mint_inflated() {
  462. let wallet = Wallet::new(
  463. MINT_URL,
  464. CurrencyUnit::Sat,
  465. Arc::new(memory::empty().await.unwrap()),
  466. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  467. None,
  468. )
  469. .expect("failed to create new wallet");
  470. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  471. let mut payment_streams = wallet.payment_stream(&mint_quote);
  472. payment_streams
  473. .next()
  474. .await
  475. .expect("payment")
  476. .expect("no error");
  477. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  478. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  479. let pre_mint = PreMintSecrets::random(
  480. active_keyset_id,
  481. 500.into(),
  482. &SplitTarget::None,
  483. &fee_and_amounts,
  484. )
  485. .unwrap();
  486. let quote_info = wallet
  487. .localstore
  488. .get_mint_quote(&mint_quote.id)
  489. .await
  490. .unwrap()
  491. .expect("there is a quote");
  492. let mut mint_request = MintRequest {
  493. quote: mint_quote.id,
  494. outputs: pre_mint.blinded_messages(),
  495. signature: None,
  496. };
  497. if let Some(secret_key) = quote_info.secret_key {
  498. mint_request
  499. .sign(secret_key)
  500. .expect("failed to sign the mint request");
  501. }
  502. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  503. let response = http_client.post_mint(mint_request.clone()).await;
  504. match response {
  505. Err(err) => match err {
  506. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  507. err => {
  508. panic!("Wrong mint error returned: {}", err);
  509. }
  510. },
  511. Ok(_) => {
  512. panic!("Should not have allowed second payment");
  513. }
  514. }
  515. }
  516. /// Tests that attempting to mint with multiple currency units in the same request fails
  517. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  518. async fn test_fake_mint_multiple_units() {
  519. let wallet = Wallet::new(
  520. MINT_URL,
  521. CurrencyUnit::Sat,
  522. Arc::new(memory::empty().await.unwrap()),
  523. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  524. None,
  525. )
  526. .expect("failed to create new wallet");
  527. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  528. let mut payment_streams = wallet.payment_stream(&mint_quote);
  529. payment_streams
  530. .next()
  531. .await
  532. .expect("payment")
  533. .expect("no error");
  534. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  535. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  536. let pre_mint = PreMintSecrets::random(
  537. active_keyset_id,
  538. 50.into(),
  539. &SplitTarget::None,
  540. &fee_and_amounts,
  541. )
  542. .unwrap();
  543. let wallet_usd = Wallet::new(
  544. MINT_URL,
  545. CurrencyUnit::Usd,
  546. Arc::new(memory::empty().await.unwrap()),
  547. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  548. None,
  549. )
  550. .expect("failed to create new wallet");
  551. let active_keyset_id = wallet_usd.fetch_active_keyset().await.unwrap().id;
  552. let usd_pre_mint = PreMintSecrets::random(
  553. active_keyset_id,
  554. 50.into(),
  555. &SplitTarget::None,
  556. &fee_and_amounts,
  557. )
  558. .unwrap();
  559. let quote_info = wallet
  560. .localstore
  561. .get_mint_quote(&mint_quote.id)
  562. .await
  563. .unwrap()
  564. .expect("there is a quote");
  565. let mut sat_outputs = pre_mint.blinded_messages();
  566. let mut usd_outputs = usd_pre_mint.blinded_messages();
  567. sat_outputs.append(&mut usd_outputs);
  568. let mut mint_request = MintRequest {
  569. quote: mint_quote.id,
  570. outputs: sat_outputs,
  571. signature: None,
  572. };
  573. if let Some(secret_key) = quote_info.secret_key {
  574. mint_request
  575. .sign(secret_key)
  576. .expect("failed to sign the mint request");
  577. }
  578. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  579. let response = http_client.post_mint(mint_request.clone()).await;
  580. match response {
  581. Err(err) => match err {
  582. cdk::Error::MultipleUnits => (),
  583. err => {
  584. panic!("Wrong mint error returned: {}", err);
  585. }
  586. },
  587. Ok(_) => {
  588. panic!("Should not have allowed to mint with multiple units");
  589. }
  590. }
  591. }
  592. /// Tests that attempting to swap tokens with multiple currency units fails
  593. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  594. async fn test_fake_mint_multiple_unit_swap() {
  595. let wallet = Wallet::new(
  596. MINT_URL,
  597. CurrencyUnit::Sat,
  598. Arc::new(memory::empty().await.unwrap()),
  599. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  600. None,
  601. )
  602. .expect("failed to create new wallet");
  603. wallet.refresh_keysets().await.unwrap();
  604. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  605. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  606. let proofs = proof_streams
  607. .next()
  608. .await
  609. .expect("payment")
  610. .expect("no error");
  611. let wallet_usd = Wallet::new(
  612. MINT_URL,
  613. CurrencyUnit::Usd,
  614. Arc::new(memory::empty().await.unwrap()),
  615. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  616. None,
  617. )
  618. .expect("failed to create usd wallet");
  619. wallet_usd.refresh_keysets().await.unwrap();
  620. let mint_quote = wallet_usd.mint_quote(100.into(), None).await.unwrap();
  621. let mut proof_streams =
  622. wallet_usd.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  623. let usd_proofs = proof_streams
  624. .next()
  625. .await
  626. .expect("payment")
  627. .expect("no error");
  628. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  629. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  630. {
  631. let inputs: Proofs = vec![
  632. proofs.first().expect("There is a proof").clone(),
  633. usd_proofs.first().expect("There is a proof").clone(),
  634. ];
  635. let pre_mint = PreMintSecrets::random(
  636. active_keyset_id,
  637. inputs.total_amount().unwrap(),
  638. &SplitTarget::None,
  639. &fee_and_amounts,
  640. )
  641. .unwrap();
  642. let swap_request = SwapRequest::new(inputs, pre_mint.blinded_messages());
  643. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  644. let response = http_client.post_swap(swap_request.clone()).await;
  645. match response {
  646. Err(err) => match err {
  647. cdk::Error::MultipleUnits => (),
  648. err => {
  649. panic!("Wrong mint error returned: {}", err);
  650. }
  651. },
  652. Ok(_) => {
  653. panic!("Should not have allowed to mint with multiple units");
  654. }
  655. }
  656. }
  657. {
  658. let usd_active_keyset_id = wallet_usd.fetch_active_keyset().await.unwrap().id;
  659. let inputs: Proofs = proofs.into_iter().take(2).collect();
  660. let total_inputs = inputs.total_amount().unwrap();
  661. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  662. let half = total_inputs / 2.into();
  663. let usd_pre_mint = PreMintSecrets::random(
  664. usd_active_keyset_id,
  665. half,
  666. &SplitTarget::None,
  667. &fee_and_amounts,
  668. )
  669. .unwrap();
  670. let pre_mint = PreMintSecrets::random(
  671. active_keyset_id,
  672. total_inputs - half,
  673. &SplitTarget::None,
  674. &fee_and_amounts,
  675. )
  676. .unwrap();
  677. let mut usd_outputs = usd_pre_mint.blinded_messages();
  678. let mut sat_outputs = pre_mint.blinded_messages();
  679. usd_outputs.append(&mut sat_outputs);
  680. let swap_request = SwapRequest::new(inputs, usd_outputs);
  681. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  682. let response = http_client.post_swap(swap_request.clone()).await;
  683. match response {
  684. Err(err) => match err {
  685. cdk::Error::MultipleUnits => (),
  686. err => {
  687. panic!("Wrong mint error returned: {}", err);
  688. }
  689. },
  690. Ok(_) => {
  691. panic!("Should not have allowed to mint with multiple units");
  692. }
  693. }
  694. }
  695. }
  696. /// Tests that attempting to melt tokens with multiple currency units fails
  697. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  698. async fn test_fake_mint_multiple_unit_melt() {
  699. let wallet = Wallet::new(
  700. MINT_URL,
  701. CurrencyUnit::Sat,
  702. Arc::new(memory::empty().await.unwrap()),
  703. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  704. None,
  705. )
  706. .expect("failed to create new wallet");
  707. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  708. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  709. let mut proofs = proof_streams
  710. .next()
  711. .await
  712. .expect("payment")
  713. .expect("no error");
  714. println!("Minted sat");
  715. let wallet_usd = Wallet::new(
  716. MINT_URL,
  717. CurrencyUnit::Usd,
  718. Arc::new(memory::empty().await.unwrap()),
  719. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  720. None,
  721. )
  722. .expect("failed to create new wallet");
  723. let mint_quote = wallet_usd.mint_quote(100.into(), None).await.unwrap();
  724. println!("Minted quote usd");
  725. let mut proof_streams =
  726. wallet_usd.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  727. let mut usd_proofs = proof_streams
  728. .next()
  729. .await
  730. .expect("payment")
  731. .expect("no error");
  732. usd_proofs.reverse();
  733. proofs.reverse();
  734. {
  735. let inputs: Proofs = vec![
  736. proofs.first().expect("There is a proof").clone(),
  737. usd_proofs.first().expect("There is a proof").clone(),
  738. ];
  739. let input_amount: u64 = inputs.total_amount().unwrap().into();
  740. let invoice = create_fake_invoice((input_amount - 1) * 1000, "".to_string());
  741. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  742. let melt_request = MeltRequest::new(melt_quote.id, inputs, None);
  743. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  744. let response = http_client.post_melt(melt_request.clone()).await;
  745. match response {
  746. Err(err) => match err {
  747. cdk::Error::MultipleUnits => (),
  748. err => {
  749. panic!("Wrong mint error returned: {}", err);
  750. }
  751. },
  752. Ok(_) => {
  753. panic!("Should not have allowed to melt with multiple units");
  754. }
  755. }
  756. }
  757. {
  758. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  759. let inputs: Proofs = vec![proofs.first().expect("There is a proof").clone()];
  760. let input_amount: u64 = inputs.total_amount().unwrap().into();
  761. let invoice = create_fake_invoice((input_amount - 1) * 1000, "".to_string());
  762. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  763. let usd_active_keyset_id = wallet_usd.fetch_active_keyset().await.unwrap().id;
  764. let usd_pre_mint = PreMintSecrets::random(
  765. usd_active_keyset_id,
  766. inputs.total_amount().unwrap() + 100.into(),
  767. &SplitTarget::None,
  768. &fee_and_amounts,
  769. )
  770. .unwrap();
  771. let pre_mint = PreMintSecrets::random(
  772. active_keyset_id,
  773. 100.into(),
  774. &SplitTarget::None,
  775. &fee_and_amounts,
  776. )
  777. .unwrap();
  778. let mut usd_outputs = usd_pre_mint.blinded_messages();
  779. let mut sat_outputs = pre_mint.blinded_messages();
  780. usd_outputs.append(&mut sat_outputs);
  781. let quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  782. let melt_request = MeltRequest::new(quote.id, inputs, Some(usd_outputs));
  783. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  784. let response = http_client.post_melt(melt_request.clone()).await;
  785. match response {
  786. Err(err) => match err {
  787. cdk::Error::MultipleUnits => (),
  788. err => {
  789. panic!("Wrong mint error returned: {}", err);
  790. }
  791. },
  792. Ok(_) => {
  793. panic!("Should not have allowed to melt with multiple units");
  794. }
  795. }
  796. }
  797. }
  798. /// Tests that swapping tokens where input unit doesn't match output unit fails
  799. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  800. async fn test_fake_mint_input_output_mismatch() {
  801. let wallet = Wallet::new(
  802. MINT_URL,
  803. CurrencyUnit::Sat,
  804. Arc::new(memory::empty().await.unwrap()),
  805. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  806. None,
  807. )
  808. .expect("failed to create new wallet");
  809. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  810. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  811. let proofs = proof_streams
  812. .next()
  813. .await
  814. .expect("payment")
  815. .expect("no error");
  816. let wallet_usd = Wallet::new(
  817. MINT_URL,
  818. CurrencyUnit::Usd,
  819. Arc::new(memory::empty().await.unwrap()),
  820. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  821. None,
  822. )
  823. .expect("failed to create new usd wallet");
  824. let usd_active_keyset_id = wallet_usd.fetch_active_keyset().await.unwrap().id;
  825. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  826. let inputs = proofs;
  827. let pre_mint = PreMintSecrets::random(
  828. usd_active_keyset_id,
  829. inputs.total_amount().unwrap(),
  830. &SplitTarget::None,
  831. &fee_and_amounts,
  832. )
  833. .unwrap();
  834. let swap_request = SwapRequest::new(inputs, pre_mint.blinded_messages());
  835. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  836. let response = http_client.post_swap(swap_request.clone()).await;
  837. match response {
  838. Err(err) => match err {
  839. cdk::Error::UnitMismatch => (),
  840. err => panic!("Wrong error returned: {}", err),
  841. },
  842. Ok(_) => {
  843. panic!("Should not have allowed to mint with multiple units");
  844. }
  845. }
  846. }
  847. /// Tests that swapping tokens where output amount is greater than input amount fails
  848. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  849. async fn test_fake_mint_swap_inflated() {
  850. let wallet = Wallet::new(
  851. MINT_URL,
  852. CurrencyUnit::Sat,
  853. Arc::new(memory::empty().await.unwrap()),
  854. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  855. None,
  856. )
  857. .expect("failed to create new wallet");
  858. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  859. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  860. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  861. let proofs = proof_streams
  862. .next()
  863. .await
  864. .expect("payment")
  865. .expect("no error");
  866. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  867. let pre_mint = PreMintSecrets::random(
  868. active_keyset_id,
  869. 101.into(),
  870. &SplitTarget::None,
  871. &fee_and_amounts,
  872. )
  873. .unwrap();
  874. let swap_request = SwapRequest::new(proofs, pre_mint.blinded_messages());
  875. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  876. let response = http_client.post_swap(swap_request.clone()).await;
  877. match response {
  878. Err(err) => match err {
  879. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  880. err => {
  881. panic!("Wrong mint error returned: {}", err);
  882. }
  883. },
  884. Ok(_) => {
  885. panic!("Should not have allowed to mint with multiple units");
  886. }
  887. }
  888. }
  889. /// Tests that tokens cannot be spent again after a failed swap attempt
  890. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  891. async fn test_fake_mint_swap_spend_after_fail() {
  892. let wallet = Wallet::new(
  893. MINT_URL,
  894. CurrencyUnit::Sat,
  895. Arc::new(memory::empty().await.unwrap()),
  896. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  897. None,
  898. )
  899. .expect("failed to create new wallet");
  900. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  901. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  902. let proofs = proof_streams
  903. .next()
  904. .await
  905. .expect("payment")
  906. .expect("no error");
  907. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  908. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  909. let pre_mint = PreMintSecrets::random(
  910. active_keyset_id,
  911. 100.into(),
  912. &SplitTarget::None,
  913. &fee_and_amounts,
  914. )
  915. .unwrap();
  916. let swap_request = SwapRequest::new(proofs.clone(), pre_mint.blinded_messages());
  917. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  918. let response = http_client.post_swap(swap_request.clone()).await;
  919. assert!(response.is_ok());
  920. let pre_mint = PreMintSecrets::random(
  921. active_keyset_id,
  922. 101.into(),
  923. &SplitTarget::None,
  924. &fee_and_amounts,
  925. )
  926. .unwrap();
  927. let swap_request = SwapRequest::new(proofs.clone(), pre_mint.blinded_messages());
  928. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  929. let response = http_client.post_swap(swap_request.clone()).await;
  930. match response {
  931. Err(err) => match err {
  932. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  933. err => panic!("Wrong mint error returned expected TransactionUnbalanced, got: {err}"),
  934. },
  935. Ok(_) => panic!("Should not have allowed swap with unbalanced"),
  936. }
  937. let pre_mint = PreMintSecrets::random(
  938. active_keyset_id,
  939. 100.into(),
  940. &SplitTarget::None,
  941. &fee_and_amounts,
  942. )
  943. .unwrap();
  944. let swap_request = SwapRequest::new(proofs, pre_mint.blinded_messages());
  945. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  946. let response = http_client.post_swap(swap_request.clone()).await;
  947. match response {
  948. Err(err) => match err {
  949. cdk::Error::TokenAlreadySpent => (),
  950. err => {
  951. panic!("Wrong mint error returned: {}", err);
  952. }
  953. },
  954. Ok(_) => {
  955. panic!("Should not have allowed to mint with multiple units");
  956. }
  957. }
  958. }
  959. /// Tests that tokens cannot be melted after a failed swap attempt
  960. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  961. async fn test_fake_mint_melt_spend_after_fail() {
  962. let wallet = Wallet::new(
  963. MINT_URL,
  964. CurrencyUnit::Sat,
  965. Arc::new(memory::empty().await.unwrap()),
  966. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  967. None,
  968. )
  969. .expect("failed to create new wallet");
  970. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  971. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  972. let proofs = proof_streams
  973. .next()
  974. .await
  975. .expect("payment")
  976. .expect("no error");
  977. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  978. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  979. let pre_mint = PreMintSecrets::random(
  980. active_keyset_id,
  981. 100.into(),
  982. &SplitTarget::None,
  983. &fee_and_amounts,
  984. )
  985. .unwrap();
  986. let swap_request = SwapRequest::new(proofs.clone(), pre_mint.blinded_messages());
  987. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  988. let response = http_client.post_swap(swap_request.clone()).await;
  989. assert!(response.is_ok());
  990. let pre_mint = PreMintSecrets::random(
  991. active_keyset_id,
  992. 101.into(),
  993. &SplitTarget::None,
  994. &fee_and_amounts,
  995. )
  996. .unwrap();
  997. let swap_request = SwapRequest::new(proofs.clone(), pre_mint.blinded_messages());
  998. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  999. let response = http_client.post_swap(swap_request.clone()).await;
  1000. match response {
  1001. Err(err) => match err {
  1002. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  1003. err => panic!("Wrong mint error returned expected TransactionUnbalanced, got: {err}"),
  1004. },
  1005. Ok(_) => panic!("Should not have allowed swap with unbalanced"),
  1006. }
  1007. let input_amount: u64 = proofs.total_amount().unwrap().into();
  1008. let invoice = create_fake_invoice((input_amount - 1) * 1000, "".to_string());
  1009. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  1010. let melt_request = MeltRequest::new(melt_quote.id, proofs, None);
  1011. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1012. let response = http_client.post_melt(melt_request.clone()).await;
  1013. match response {
  1014. Err(err) => match err {
  1015. cdk::Error::TokenAlreadySpent => (),
  1016. err => {
  1017. panic!("Wrong mint error returned: {}", err);
  1018. }
  1019. },
  1020. Ok(_) => {
  1021. panic!("Should not have allowed to melt with multiple units");
  1022. }
  1023. }
  1024. }
  1025. /// Tests that attempting to swap with duplicate proofs fails
  1026. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1027. async fn test_fake_mint_duplicate_proofs_swap() {
  1028. let wallet = Wallet::new(
  1029. MINT_URL,
  1030. CurrencyUnit::Sat,
  1031. Arc::new(memory::empty().await.unwrap()),
  1032. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1033. None,
  1034. )
  1035. .expect("failed to create new wallet");
  1036. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  1037. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1038. let proofs = proof_streams
  1039. .next()
  1040. .await
  1041. .expect("payment")
  1042. .expect("no error");
  1043. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  1044. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  1045. let inputs = vec![proofs[0].clone(), proofs[0].clone()];
  1046. let pre_mint = PreMintSecrets::random(
  1047. active_keyset_id,
  1048. inputs.total_amount().unwrap(),
  1049. &SplitTarget::None,
  1050. &fee_and_amounts,
  1051. )
  1052. .unwrap();
  1053. let swap_request = SwapRequest::new(inputs.clone(), pre_mint.blinded_messages());
  1054. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1055. let response = http_client.post_swap(swap_request.clone()).await;
  1056. match response {
  1057. Err(err) => match err {
  1058. cdk::Error::DuplicateInputs => (),
  1059. err => {
  1060. panic!(
  1061. "Wrong mint error returned, expected duplicate inputs: {}",
  1062. err
  1063. );
  1064. }
  1065. },
  1066. Ok(_) => {
  1067. panic!("Should not have allowed duplicate inputs");
  1068. }
  1069. }
  1070. let blinded_message = pre_mint.blinded_messages();
  1071. let inputs = vec![proofs[0].clone()];
  1072. let outputs = vec![blinded_message[0].clone(), blinded_message[0].clone()];
  1073. let swap_request = SwapRequest::new(inputs, outputs);
  1074. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1075. let response = http_client.post_swap(swap_request.clone()).await;
  1076. match response {
  1077. Err(err) => match err {
  1078. cdk::Error::DuplicateOutputs => (),
  1079. err => {
  1080. panic!(
  1081. "Wrong mint error returned, expected duplicate outputs: {}",
  1082. err
  1083. );
  1084. }
  1085. },
  1086. Ok(_) => {
  1087. panic!("Should not have allow duplicate inputs");
  1088. }
  1089. }
  1090. }
  1091. /// Tests that attempting to melt with duplicate proofs fails
  1092. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1093. async fn test_fake_mint_duplicate_proofs_melt() {
  1094. let wallet = Wallet::new(
  1095. MINT_URL,
  1096. CurrencyUnit::Sat,
  1097. Arc::new(memory::empty().await.unwrap()),
  1098. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1099. None,
  1100. )
  1101. .expect("failed to create new wallet");
  1102. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  1103. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1104. let proofs = proof_streams
  1105. .next()
  1106. .await
  1107. .expect("payment")
  1108. .expect("no error");
  1109. let inputs = vec![proofs[0].clone(), proofs[0].clone()];
  1110. let invoice = create_fake_invoice(7000, "".to_string());
  1111. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  1112. let melt_request = MeltRequest::new(melt_quote.id, inputs, None);
  1113. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1114. let response = http_client.post_melt(melt_request.clone()).await;
  1115. match response {
  1116. Err(err) => match err {
  1117. cdk::Error::DuplicateInputs => (),
  1118. err => {
  1119. panic!("Wrong mint error returned: {}", err);
  1120. }
  1121. },
  1122. Ok(_) => {
  1123. panic!("Should not have allow duplicate inputs");
  1124. }
  1125. }
  1126. }
  1127. /// Tests that wallet automatically recovers proofs after a failed melt operation
  1128. /// by swapping them to new proofs, preventing loss of funds
  1129. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1130. async fn test_wallet_proof_recovery_after_failed_melt() {
  1131. let wallet = Wallet::new(
  1132. MINT_URL,
  1133. CurrencyUnit::Sat,
  1134. Arc::new(memory::empty().await.unwrap()),
  1135. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1136. None,
  1137. )
  1138. .expect("failed to create new wallet");
  1139. // Mint 100 sats
  1140. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  1141. let _roof_streams = wallet
  1142. .wait_and_mint_quote(
  1143. mint_quote.clone(),
  1144. SplitTarget::default(),
  1145. None,
  1146. Duration::from_secs(1000),
  1147. )
  1148. .await;
  1149. assert_eq!(wallet.total_balance().await.unwrap(), Amount::from(100));
  1150. // Create a melt quote that will fail
  1151. let fake_description = FakeInvoiceDescription {
  1152. pay_invoice_state: MeltQuoteState::Unknown,
  1153. check_payment_state: MeltQuoteState::Unpaid,
  1154. pay_err: true,
  1155. check_err: false,
  1156. };
  1157. let invoice = create_fake_invoice(1000, serde_json::to_string(&fake_description).unwrap());
  1158. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  1159. // Attempt to melt - this should fail but trigger proof recovery
  1160. let melt_result = wallet.melt(&melt_quote.id).await;
  1161. assert!(melt_result.is_err(), "Melt should have failed");
  1162. // Verify wallet still has balance (proofs recovered)
  1163. assert_eq!(
  1164. wallet.total_balance().await.unwrap(),
  1165. Amount::from(100),
  1166. "Balance should be recovered"
  1167. );
  1168. // Verify we can still spend the recovered proofs
  1169. let valid_invoice = create_fake_invoice(7000, "".to_string());
  1170. let valid_melt_quote = wallet
  1171. .melt_quote(valid_invoice.to_string(), None)
  1172. .await
  1173. .unwrap();
  1174. let successful_melt = wallet.melt(&valid_melt_quote.id).await;
  1175. assert!(
  1176. successful_melt.is_ok(),
  1177. "Should be able to spend recovered proofs"
  1178. );
  1179. }
  1180. /// Tests that concurrent melt attempts for the same invoice result in exactly one success
  1181. ///
  1182. /// This test verifies the race condition protection: when multiple melt quotes exist for the
  1183. /// same invoice and all are attempted concurrently, only one should succeed due to
  1184. /// the FOR UPDATE locking on quotes with the same request_lookup_id.
  1185. #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
  1186. async fn test_concurrent_melt_same_invoice() {
  1187. const NUM_WALLETS: usize = 4;
  1188. // Create multiple wallets to simulate concurrent requests
  1189. let mut wallets = Vec::with_capacity(NUM_WALLETS);
  1190. for i in 0..NUM_WALLETS {
  1191. let wallet = Arc::new(
  1192. Wallet::new(
  1193. MINT_URL,
  1194. CurrencyUnit::Sat,
  1195. Arc::new(memory::empty().await.unwrap()),
  1196. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1197. None,
  1198. )
  1199. .expect(&format!("failed to create wallet {}", i)),
  1200. );
  1201. wallets.push(wallet);
  1202. }
  1203. // Mint proofs for all wallets
  1204. for (i, wallet) in wallets.iter().enumerate() {
  1205. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  1206. let mut proof_streams =
  1207. wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1208. proof_streams
  1209. .next()
  1210. .await
  1211. .expect(&format!("payment for wallet {}", i))
  1212. .expect("no error");
  1213. }
  1214. // Create a single invoice that all wallets will try to pay
  1215. let fake_description = FakeInvoiceDescription::default();
  1216. let invoice = create_fake_invoice(9000, serde_json::to_string(&fake_description).unwrap());
  1217. // All wallets create melt quotes for the same invoice
  1218. let mut melt_quotes = Vec::with_capacity(NUM_WALLETS);
  1219. for wallet in &wallets {
  1220. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  1221. melt_quotes.push(melt_quote);
  1222. }
  1223. // Verify all quotes have the same request (same invoice = same lookup_id)
  1224. for quote in &melt_quotes[1..] {
  1225. assert_eq!(
  1226. melt_quotes[0].request, quote.request,
  1227. "All quotes should be for the same invoice"
  1228. );
  1229. }
  1230. // Attempt all melts concurrently
  1231. let mut handles = Vec::with_capacity(NUM_WALLETS);
  1232. for (wallet, quote) in wallets.iter().zip(melt_quotes.iter()) {
  1233. let wallet_clone = Arc::clone(wallet);
  1234. let quote_id = quote.id.clone();
  1235. handles.push(tokio::spawn(
  1236. async move { wallet_clone.melt(&quote_id).await },
  1237. ));
  1238. }
  1239. // Collect results
  1240. let mut results = Vec::with_capacity(NUM_WALLETS);
  1241. for handle in handles {
  1242. results.push(handle.await.expect("task panicked"));
  1243. }
  1244. // Count successes and failures
  1245. let success_count = results.iter().filter(|r| r.is_ok()).count();
  1246. let failure_count = results.iter().filter(|r| r.is_err()).count();
  1247. assert_eq!(
  1248. success_count, 1,
  1249. "Expected exactly one successful melt, got {}. Results: {:?}",
  1250. success_count, results
  1251. );
  1252. assert_eq!(
  1253. failure_count,
  1254. NUM_WALLETS - 1,
  1255. "Expected {} failed melts, got {}",
  1256. NUM_WALLETS - 1,
  1257. failure_count
  1258. );
  1259. // Verify all failures were due to duplicate detection
  1260. for result in &results {
  1261. if let Err(err) = result {
  1262. let err_str = err.to_string().to_lowercase();
  1263. assert!(
  1264. err_str.contains("duplicate")
  1265. || err_str.contains("already paid")
  1266. || err_str.contains("pending"),
  1267. "Expected duplicate/already paid/pending error, got: {}",
  1268. err
  1269. );
  1270. }
  1271. }
  1272. }
  1273. /// Tests that wallet automatically recovers proofs after a failed swap operation
  1274. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1275. async fn test_wallet_proof_recovery_after_failed_swap() {
  1276. let wallet = Wallet::new(
  1277. MINT_URL,
  1278. CurrencyUnit::Sat,
  1279. Arc::new(memory::empty().await.unwrap()),
  1280. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1281. None,
  1282. )
  1283. .expect("failed to create new wallet");
  1284. // Mint 100 sats
  1285. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  1286. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1287. let initial_proofs = proof_streams
  1288. .next()
  1289. .await
  1290. .expect("payment")
  1291. .expect("no error");
  1292. let initial_ys: Vec<_> = initial_proofs.iter().map(|p| p.y().unwrap()).collect();
  1293. assert_eq!(wallet.total_balance().await.unwrap(), Amount::from(100));
  1294. let unspent_proofs = wallet.get_unspent_proofs().await.unwrap();
  1295. // Create an invalid swap by manually constructing a request that will fail
  1296. // We'll use the wallet's swap with invalid parameters to trigger a failure
  1297. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  1298. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  1299. // Create invalid swap request (requesting more than we have)
  1300. let preswap = PreMintSecrets::random(
  1301. active_keyset_id,
  1302. 1000.into(), // More than the 100 we have
  1303. &SplitTarget::default(),
  1304. &fee_and_amounts,
  1305. )
  1306. .unwrap();
  1307. let swap_request = SwapRequest::new(unspent_proofs.clone(), preswap.blinded_messages());
  1308. // Use HTTP client directly to bypass wallet's validation and trigger recovery
  1309. let http_client = HttpClient::new(MINT_URL.parse().unwrap(), None);
  1310. let response = http_client.post_swap(swap_request).await;
  1311. assert!(response.is_err(), "Swap should have failed");
  1312. // Note: The HTTP client doesn't trigger the wallet's try_proof_operation wrapper
  1313. // So we need to test through the wallet's own methods
  1314. // After the failed HTTP request, the proofs are still in the wallet's database
  1315. // Verify balance is still available after the failed operation
  1316. assert_eq!(
  1317. wallet.total_balance().await.unwrap(),
  1318. Amount::from(100),
  1319. "Balance should still be available"
  1320. );
  1321. // Verify we can perform a successful swap operation
  1322. let successful_swap = wallet
  1323. .swap(None, SplitTarget::None, unspent_proofs, None, false)
  1324. .await;
  1325. assert!(
  1326. successful_swap.is_ok(),
  1327. "Should be able to swap after failed operation"
  1328. );
  1329. // Verify the proofs were swapped to new ones
  1330. let final_proofs = wallet.get_unspent_proofs().await.unwrap();
  1331. let final_ys: Vec<_> = final_proofs.iter().map(|p| p.y().unwrap()).collect();
  1332. // The Ys should be different after the successful swap
  1333. assert!(
  1334. initial_ys.iter().any(|y| !final_ys.contains(y)),
  1335. "Proofs should have been swapped to new ones"
  1336. );
  1337. }
  1338. /// Tests that melt_proofs works correctly with proofs that are not already in the wallet's database.
  1339. /// This is similar to the receive flow where proofs come from an external source.
  1340. ///
  1341. /// Flow:
  1342. /// 1. Wallet A mints proofs (proofs ARE in Wallet A's database)
  1343. /// 2. Wallet B creates a melt quote
  1344. /// 3. Wallet B calls melt_proofs with proofs from Wallet A (proofs are NOT in Wallet B's database)
  1345. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1346. async fn test_melt_proofs_external() {
  1347. // Create sender wallet (Wallet A) and mint some proofs
  1348. let wallet_sender = Wallet::new(
  1349. MINT_URL,
  1350. CurrencyUnit::Sat,
  1351. Arc::new(memory::empty().await.unwrap()),
  1352. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1353. None,
  1354. )
  1355. .expect("failed to create sender wallet");
  1356. let mint_quote = wallet_sender.mint_quote(100.into(), None).await.unwrap();
  1357. let mut proof_streams =
  1358. wallet_sender.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1359. let proofs = proof_streams
  1360. .next()
  1361. .await
  1362. .expect("payment")
  1363. .expect("no error");
  1364. assert_eq!(proofs.total_amount().unwrap(), Amount::from(100));
  1365. // Create receiver/melter wallet (Wallet B) with a separate database
  1366. // These proofs are NOT in Wallet B's database
  1367. let wallet_melter = Wallet::new(
  1368. MINT_URL,
  1369. CurrencyUnit::Sat,
  1370. Arc::new(memory::empty().await.unwrap()),
  1371. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1372. None,
  1373. )
  1374. .expect("failed to create melter wallet");
  1375. // Verify proofs are not in the melter wallet's database
  1376. let melter_proofs = wallet_melter.get_unspent_proofs().await.unwrap();
  1377. assert!(
  1378. melter_proofs.is_empty(),
  1379. "Melter wallet should have no proofs initially"
  1380. );
  1381. // Create a fake invoice for melting
  1382. let fake_description = FakeInvoiceDescription::default();
  1383. let invoice = create_fake_invoice(9000, serde_json::to_string(&fake_description).unwrap());
  1384. // Wallet B creates a melt quote
  1385. let melt_quote = wallet_melter
  1386. .melt_quote(invoice.to_string(), None)
  1387. .await
  1388. .unwrap();
  1389. // Wallet B calls melt_proofs with external proofs (from Wallet A)
  1390. // These proofs are NOT in wallet_melter's database
  1391. let melted = wallet_melter
  1392. .melt_proofs(&melt_quote.id, proofs.clone())
  1393. .await
  1394. .unwrap();
  1395. // Verify the melt succeeded
  1396. assert_eq!(melted.amount, Amount::from(9));
  1397. assert_eq!(melted.fee_paid, 1.into());
  1398. // Verify change was returned (100 input - 9 melt amount = 91 change, minus fee reserve)
  1399. assert!(melted.change.is_some());
  1400. let change_amount = melted.change.unwrap().total_amount().unwrap();
  1401. assert!(change_amount > Amount::ZERO, "Should have received change");
  1402. // Verify the melter wallet now has the change proofs
  1403. let melter_balance = wallet_melter.total_balance().await.unwrap();
  1404. assert_eq!(melter_balance, change_amount);
  1405. // Verify a transaction was recorded
  1406. let transactions = wallet_melter
  1407. .list_transactions(Some(TransactionDirection::Outgoing))
  1408. .await
  1409. .unwrap();
  1410. assert_eq!(transactions.len(), 1);
  1411. assert_eq!(transactions[0].amount, Amount::from(9));
  1412. }
  1413. /// Tests that melt automatically performs a swap when proofs don't exactly match
  1414. /// the required amount (quote + fee_reserve + input_fee).
  1415. ///
  1416. /// This test verifies the swap-before-melt optimization:
  1417. /// 1. Mint proofs that will NOT exactly match a melt amount
  1418. /// 2. Create a melt quote for a specific amount
  1419. /// 3. Call melt() - it should automatically swap proofs to get exact denominations
  1420. /// 4. Verify the melt succeeded
  1421. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1422. async fn test_melt_with_swap_for_exact_amount() {
  1423. let wallet = Wallet::new(
  1424. MINT_URL,
  1425. CurrencyUnit::Sat,
  1426. Arc::new(memory::empty().await.unwrap()),
  1427. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1428. None,
  1429. )
  1430. .expect("failed to create new wallet");
  1431. // Mint 100 sats - this will give us proofs in standard denominations
  1432. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  1433. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1434. let proofs = proof_streams
  1435. .next()
  1436. .await
  1437. .expect("payment")
  1438. .expect("no error");
  1439. let initial_balance = wallet.total_balance().await.unwrap();
  1440. assert_eq!(initial_balance, Amount::from(100));
  1441. // Log the proof denominations we received
  1442. let proof_amounts: Vec<u64> = proofs.iter().map(|p| u64::from(p.amount)).collect();
  1443. tracing::info!("Initial proof denominations: {:?}", proof_amounts);
  1444. // Create a melt quote for an amount that likely won't match our proof denominations exactly
  1445. // Using 7 sats (7000 msats) which requires specific denominations
  1446. let fake_description = FakeInvoiceDescription::default();
  1447. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  1448. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  1449. tracing::info!(
  1450. "Melt quote: amount={}, fee_reserve={}",
  1451. melt_quote.amount,
  1452. melt_quote.fee_reserve
  1453. );
  1454. // Call melt() - this should trigger swap-before-melt if proofs don't match exactly
  1455. let melted = wallet.melt(&melt_quote.id).await.unwrap();
  1456. // Verify the melt succeeded
  1457. assert_eq!(melted.amount, Amount::from(7));
  1458. tracing::info!(
  1459. "Melt completed: amount={}, fee_paid={}",
  1460. melted.amount,
  1461. melted.fee_paid
  1462. );
  1463. // Verify final balance is correct (initial - melt_amount - fees)
  1464. let final_balance = wallet.total_balance().await.unwrap();
  1465. tracing::info!(
  1466. "Balance: initial={}, final={}, paid={}",
  1467. initial_balance,
  1468. final_balance,
  1469. melted.amount + melted.fee_paid
  1470. );
  1471. assert!(
  1472. final_balance < initial_balance,
  1473. "Balance should have decreased after melt"
  1474. );
  1475. assert_eq!(
  1476. final_balance,
  1477. initial_balance - melted.amount - melted.fee_paid,
  1478. "Final balance should be initial - amount - fees"
  1479. );
  1480. }
  1481. /// Tests that melt works correctly when proofs already exactly match the required amount.
  1482. /// In this case, no swap should be needed.
  1483. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  1484. async fn test_melt_exact_proofs_no_swap_needed() {
  1485. let wallet = Wallet::new(
  1486. MINT_URL,
  1487. CurrencyUnit::Sat,
  1488. Arc::new(memory::empty().await.unwrap()),
  1489. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  1490. None,
  1491. )
  1492. .expect("failed to create new wallet");
  1493. // Mint a larger amount to have more denomination options
  1494. let mint_quote = wallet.mint_quote(1000.into(), None).await.unwrap();
  1495. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  1496. let _proofs = proof_streams
  1497. .next()
  1498. .await
  1499. .expect("payment")
  1500. .expect("no error");
  1501. let initial_balance = wallet.total_balance().await.unwrap();
  1502. assert_eq!(initial_balance, Amount::from(1000));
  1503. // Create a melt for a power-of-2 amount that's more likely to match existing denominations
  1504. let fake_description = FakeInvoiceDescription::default();
  1505. let invoice = create_fake_invoice(64_000, serde_json::to_string(&fake_description).unwrap()); // 64 sats
  1506. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  1507. // Melt should succeed
  1508. let melted = wallet.melt(&melt_quote.id).await.unwrap();
  1509. assert_eq!(melted.amount, Amount::from(64));
  1510. let final_balance = wallet.total_balance().await.unwrap();
  1511. assert_eq!(
  1512. final_balance,
  1513. initial_balance - melted.amount - melted.fee_paid
  1514. );
  1515. }