happy_path_mint_wallet.rs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  1. //! Integration tests for mint-wallet interactions that should work across all mint implementations
  2. //!
  3. //! These tests verify the core functionality of the wallet-mint interaction protocol,
  4. //! including minting, melting, and wallet restoration. They are designed to be
  5. //! implementation-agnostic and should pass against any compliant Cashu mint,
  6. //! including Nutshell, CDK, and other implementations that follow the Cashu NUTs.
  7. //!
  8. //! The tests use environment variables to determine which mint to connect to and
  9. //! whether to use real Lightning Network payments (regtest mode) or simulated payments.
  10. use core::panic;
  11. use std::collections::HashMap;
  12. use std::env;
  13. use std::fmt::Debug;
  14. use std::path::PathBuf;
  15. use std::str::FromStr;
  16. use std::sync::Arc;
  17. use std::time::Duration;
  18. use bip39::Mnemonic;
  19. use cashu::{MeltRequest, PreMintSecrets};
  20. use cdk::amount::{Amount, SplitTarget};
  21. use cdk::mint_url::MintUrl;
  22. use cdk::nuts::nut00::ProofsMethods;
  23. use cdk::nuts::{CurrencyUnit, MeltQuoteState, NotificationPayload, State};
  24. use cdk::wallet::{HttpClient, MintConnector, MultiMintWallet, Wallet};
  25. use cdk_integration_tests::{create_invoice_for_env, get_mint_url_from_env, pay_if_regtest};
  26. use cdk_sqlite::wallet::memory;
  27. use futures::{SinkExt, StreamExt};
  28. use lightning_invoice::Bolt11Invoice;
  29. use serde_json::json;
  30. use tokio::time::timeout;
  31. use tokio_tungstenite::connect_async;
  32. use tokio_tungstenite::tungstenite::protocol::Message;
  33. // Helper function to get temp directory from environment or fallback
  34. fn get_test_temp_dir() -> PathBuf {
  35. match env::var("CDK_ITESTS_DIR") {
  36. Ok(dir) => PathBuf::from(dir),
  37. Err(_) => panic!("Unknown test dir"),
  38. }
  39. }
  40. async fn get_notifications<T: StreamExt<Item = Result<Message, E>> + Unpin, E: Debug>(
  41. reader: &mut T,
  42. timeout_to_wait: Duration,
  43. total: usize,
  44. ) -> Vec<(String, NotificationPayload<String>)> {
  45. let mut results = Vec::new();
  46. for _ in 0..total {
  47. let msg = timeout(timeout_to_wait, reader.next())
  48. .await
  49. .expect("timeout")
  50. .unwrap()
  51. .unwrap();
  52. let mut response: serde_json::Value =
  53. serde_json::from_str(msg.to_text().unwrap()).expect("valid json");
  54. let mut params_raw = response
  55. .as_object_mut()
  56. .expect("object")
  57. .remove("params")
  58. .expect("valid params");
  59. let params_map = params_raw.as_object_mut().expect("params is object");
  60. results.push((
  61. params_map
  62. .remove("subId")
  63. .unwrap()
  64. .as_str()
  65. .unwrap()
  66. .to_string(),
  67. serde_json::from_value(params_map.remove("payload").unwrap()).unwrap(),
  68. ))
  69. }
  70. results
  71. }
  72. /// Tests a complete mint-melt round trip with WebSocket notifications
  73. ///
  74. /// This test verifies the full lifecycle of tokens:
  75. /// 1. Creates a mint quote and pays the invoice
  76. /// 2. Mints tokens and verifies the correct amount
  77. /// 3. Creates a melt quote to spend tokens
  78. /// 4. Subscribes to WebSocket notifications for the melt process
  79. /// 5. Executes the melt and verifies the payment was successful
  80. /// 6. Validates all WebSocket notifications received during the process
  81. ///
  82. /// This ensures the entire mint-melt flow works correctly and that
  83. /// WebSocket notifications are properly sent at each state transition.
  84. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  85. async fn test_happy_mint_melt_round_trip() {
  86. let wallet = Wallet::new(
  87. &get_mint_url_from_env(),
  88. CurrencyUnit::Sat,
  89. Arc::new(memory::empty().await.unwrap()),
  90. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  91. None,
  92. )
  93. .expect("failed to create new wallet");
  94. let (ws_stream, _) = connect_async(format!(
  95. "{}/v1/ws",
  96. get_mint_url_from_env().replace("http", "ws")
  97. ))
  98. .await
  99. .expect("Failed to connect");
  100. let (mut write, mut reader) = ws_stream.split();
  101. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  102. let invoice = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
  103. pay_if_regtest(&get_test_temp_dir(), &invoice)
  104. .await
  105. .unwrap();
  106. let proofs = wallet
  107. .wait_and_mint_quote(
  108. mint_quote.clone(),
  109. SplitTarget::default(),
  110. None,
  111. tokio::time::Duration::from_secs(60),
  112. )
  113. .await
  114. .expect("payment");
  115. let mint_amount = proofs.total_amount().unwrap();
  116. assert!(mint_amount == 100.into());
  117. let invoice = create_invoice_for_env(Some(50)).await.unwrap();
  118. let melt = wallet.melt_quote(invoice, None).await.unwrap();
  119. write
  120. .send(Message::Text(
  121. serde_json::to_string(&json!({
  122. "jsonrpc": "2.0",
  123. "id": 2,
  124. "method": "subscribe",
  125. "params": {
  126. "kind": "bolt11_melt_quote",
  127. "filters": [
  128. melt.id.clone(),
  129. ],
  130. "subId": "test-sub",
  131. }
  132. }))
  133. .unwrap()
  134. .into(),
  135. ))
  136. .await
  137. .unwrap();
  138. // Parse both JSON strings to objects and compare them instead of comparing strings directly
  139. let binding = reader.next().await.unwrap().unwrap();
  140. let response_str = binding.to_text().unwrap();
  141. let response_json: serde_json::Value =
  142. serde_json::from_str(response_str).expect("Valid JSON response");
  143. let expected_json: serde_json::Value = serde_json::from_str(
  144. r#"{"jsonrpc":"2.0","result":{"status":"OK","subId":"test-sub"},"id":2}"#,
  145. )
  146. .expect("Valid JSON expected");
  147. assert_eq!(response_json, expected_json);
  148. // Read the initial state notification before starting the melt to ensure we capture Unpaid
  149. let initial_notification =
  150. get_notifications(&mut reader, Duration::from_millis(15000), 1).await;
  151. let (sub_id, payload) = &initial_notification[0];
  152. assert_eq!("test-sub", sub_id);
  153. let initial_melt = match payload {
  154. NotificationPayload::MeltQuoteBolt11Response(m) => m,
  155. _ => panic!("Wrong payload"),
  156. };
  157. assert_eq!(initial_melt.state, MeltQuoteState::Unpaid);
  158. assert_eq!(initial_melt.quote.to_string(), melt.id);
  159. // Now start the melt
  160. let mut metadata = HashMap::new();
  161. metadata.insert("test".to_string(), "value".to_string());
  162. let melt_response = wallet
  163. .melt_with_metadata(&melt.id, metadata.clone())
  164. .await
  165. .unwrap();
  166. assert!(melt_response.preimage.is_some());
  167. assert_eq!(melt_response.state, MeltQuoteState::Paid);
  168. let txs = wallet.list_transactions(None).await.unwrap();
  169. let tx = txs
  170. .into_iter()
  171. .find(|tx| tx.quote_id == Some(melt.id.clone()))
  172. .unwrap();
  173. assert_eq!(tx.amount, melt.amount);
  174. assert_eq!(tx.metadata, metadata);
  175. // Read remaining notifications (Pending -> Paid)
  176. let notifications = get_notifications(&mut reader, Duration::from_millis(15000), 2).await;
  177. let (sub_id, payload) = &notifications[0];
  178. assert_eq!("test-sub", sub_id);
  179. let pending_melt = match payload {
  180. NotificationPayload::MeltQuoteBolt11Response(m) => m,
  181. _ => panic!("Wrong payload"),
  182. };
  183. assert_eq!(pending_melt.state, MeltQuoteState::Pending);
  184. assert_eq!(pending_melt.quote.to_string(), melt.id);
  185. let (sub_id, payload) = &notifications[1];
  186. assert_eq!("test-sub", sub_id);
  187. let final_melt = match payload {
  188. NotificationPayload::MeltQuoteBolt11Response(m) => m,
  189. _ => panic!("Wrong payload"),
  190. };
  191. assert_eq!(final_melt.state, MeltQuoteState::Paid);
  192. assert_eq!(final_melt.amount, 50.into());
  193. assert_eq!(final_melt.quote.to_string(), melt.id);
  194. }
  195. /// Tests basic minting functionality with payment verification
  196. ///
  197. /// This test focuses on the core minting process:
  198. /// 1. Creates a mint quote for a specific amount (100 sats)
  199. /// 2. Verifies the quote has the correct amount
  200. /// 3. Pays the invoice (or simulates payment in non-regtest environments)
  201. /// 4. Waits for the mint to recognize the payment
  202. /// 5. Mints tokens and verifies the correct amount was received
  203. ///
  204. /// This ensures the basic minting flow works correctly from quote to token issuance.
  205. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  206. async fn test_happy_mint() {
  207. let wallet = Wallet::new(
  208. &get_mint_url_from_env(),
  209. CurrencyUnit::Sat,
  210. Arc::new(memory::empty().await.unwrap()),
  211. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  212. None,
  213. )
  214. .expect("failed to create new wallet");
  215. let mint_amount = Amount::from(100);
  216. let mint_quote = wallet.mint_quote(mint_amount, None).await.unwrap();
  217. assert_eq!(mint_quote.amount, Some(mint_amount));
  218. let invoice = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
  219. pay_if_regtest(&get_test_temp_dir(), &invoice)
  220. .await
  221. .unwrap();
  222. let proofs = wallet
  223. .wait_and_mint_quote(
  224. mint_quote.clone(),
  225. SplitTarget::default(),
  226. None,
  227. tokio::time::Duration::from_secs(60),
  228. )
  229. .await
  230. .expect("payment");
  231. let mint_amount = proofs.total_amount().unwrap();
  232. assert!(mint_amount == 100.into());
  233. }
  234. /// Tests wallet restoration and proof state verification
  235. ///
  236. /// This test verifies the wallet restoration process:
  237. /// 1. Creates a wallet with a specific seed and mints tokens
  238. /// 2. Verifies the wallet has the expected balance
  239. /// 3. Creates a new wallet instance with the same seed but empty storage
  240. /// 4. Confirms the new wallet starts with zero balance
  241. /// 5. Restores the wallet state from the mint
  242. /// 6. Swaps the proofs to ensure they're valid
  243. /// 7. Verifies the restored wallet has the correct balance
  244. /// 8. Checks that the original proofs are now marked as spent
  245. ///
  246. /// This ensures wallet restoration works correctly and that
  247. /// the mint properly tracks spent proofs across wallet instances.
  248. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  249. async fn test_restore() {
  250. let seed = Mnemonic::generate(12).unwrap().to_seed_normalized("");
  251. let wallet = Wallet::new(
  252. &get_mint_url_from_env(),
  253. CurrencyUnit::Sat,
  254. Arc::new(memory::empty().await.unwrap()),
  255. seed,
  256. None,
  257. )
  258. .expect("failed to create new wallet");
  259. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  260. let invoice = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
  261. pay_if_regtest(&get_test_temp_dir(), &invoice)
  262. .await
  263. .unwrap();
  264. let _proofs = wallet
  265. .wait_and_mint_quote(
  266. mint_quote.clone(),
  267. SplitTarget::default(),
  268. None,
  269. tokio::time::Duration::from_secs(60),
  270. )
  271. .await
  272. .expect("payment");
  273. assert_eq!(wallet.total_balance().await.unwrap(), 100.into());
  274. let wallet_2 = Wallet::new(
  275. &get_mint_url_from_env(),
  276. CurrencyUnit::Sat,
  277. Arc::new(memory::empty().await.unwrap()),
  278. seed,
  279. None,
  280. )
  281. .expect("failed to create new wallet");
  282. assert_eq!(wallet_2.total_balance().await.unwrap(), 0.into());
  283. let restored = wallet_2.restore().await.unwrap();
  284. let proofs = wallet_2.get_unspent_proofs().await.unwrap();
  285. assert!(!proofs.is_empty());
  286. let expected_fee = wallet.get_proofs_fee(&proofs).await.unwrap().total;
  287. wallet_2
  288. .swap(None, SplitTarget::default(), proofs, None, false)
  289. .await
  290. .unwrap();
  291. assert_eq!(restored, 100.into());
  292. // Since we have to do a swap we expect to restore amount - fee
  293. assert_eq!(
  294. wallet_2.total_balance().await.unwrap(),
  295. Amount::from(100) - expected_fee
  296. );
  297. let proofs = wallet.get_unspent_proofs().await.unwrap();
  298. let states = wallet.check_proofs_spent(proofs).await.unwrap();
  299. for state in states {
  300. if state.state != State::Spent {
  301. panic!("All proofs should be spent");
  302. }
  303. }
  304. }
  305. /// Tests wallet restoration with a large number of proofs (3000)
  306. ///
  307. /// This test verifies the restore process works correctly with many proofs,
  308. /// which is important for testing database performance (especially PostgreSQL)
  309. /// and ensuring the restore batching logic handles large proof sets:
  310. /// 1. Creates a wallet and mints 3000 sats as individual 1-sat proofs
  311. /// 2. Creates a new wallet instance with the same seed but empty storage
  312. /// 3. Restores the wallet state from the mint (requires ~30 restore batches)
  313. /// 4. Verifies all 3000 proofs are correctly restored
  314. /// 5. Swaps the proofs to ensure they're valid
  315. /// 6. Checks that the original proofs are now marked as spent
  316. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  317. async fn test_restore_large_proof_count() {
  318. let seed = Mnemonic::generate(12).unwrap().to_seed_normalized("");
  319. let wallet = Wallet::new(
  320. &get_mint_url_from_env(),
  321. CurrencyUnit::Sat,
  322. Arc::new(memory::empty().await.unwrap()),
  323. seed,
  324. None,
  325. )
  326. .expect("failed to create new wallet");
  327. let mint_amount: u64 = 3000;
  328. let batch_size: u64 = 999; // Keep under 1000 outputs per request
  329. // Mint in batches to avoid exceeding the 1000 output limit per request
  330. let mut total_proofs = 0usize;
  331. let mut remaining = mint_amount;
  332. while remaining > 0 {
  333. let batch = remaining.min(batch_size);
  334. let mint_quote = wallet.mint_quote(batch.into(), None).await.unwrap();
  335. let invoice = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
  336. pay_if_regtest(&get_test_temp_dir(), &invoice)
  337. .await
  338. .unwrap();
  339. // Mint with SplitTarget::Value(1) to create individual 1-sat proofs
  340. let proofs = wallet
  341. .wait_and_mint_quote(
  342. mint_quote.clone(),
  343. SplitTarget::Value(1.into()),
  344. None,
  345. tokio::time::Duration::from_secs(120),
  346. )
  347. .await
  348. .expect("payment");
  349. total_proofs += proofs.len();
  350. remaining -= batch;
  351. }
  352. assert_eq!(total_proofs, mint_amount as usize);
  353. assert_eq!(wallet.total_balance().await.unwrap(), mint_amount.into());
  354. let wallet_2 = Wallet::new(
  355. &get_mint_url_from_env(),
  356. CurrencyUnit::Sat,
  357. Arc::new(memory::empty().await.unwrap()),
  358. seed,
  359. None,
  360. )
  361. .expect("failed to create new wallet");
  362. assert_eq!(wallet_2.total_balance().await.unwrap(), 0.into());
  363. let restored = wallet_2.restore().await.unwrap();
  364. let proofs = wallet_2.get_unspent_proofs().await.unwrap();
  365. assert_eq!(proofs.len(), mint_amount as usize);
  366. assert_eq!(restored, mint_amount.into());
  367. // Swap in batches to avoid exceeding the 1000 input limit per request
  368. let mut total_fee = Amount::ZERO;
  369. for batch in proofs.chunks(batch_size as usize) {
  370. let batch_vec = batch.to_vec();
  371. let batch_fee = wallet_2.get_proofs_fee(&batch_vec).await.unwrap().total;
  372. total_fee += batch_fee;
  373. wallet_2
  374. .swap(None, SplitTarget::default(), batch.to_vec(), None, false)
  375. .await
  376. .unwrap();
  377. }
  378. // Since we have to do a swap we expect to restore amount - fee
  379. assert_eq!(
  380. wallet_2.total_balance().await.unwrap(),
  381. Amount::from(mint_amount) - total_fee
  382. );
  383. let proofs = wallet.get_unspent_proofs().await.unwrap();
  384. // Check proofs in batches to avoid large queries
  385. for batch in proofs.chunks(100) {
  386. let states = wallet.check_proofs_spent(batch.to_vec()).await.unwrap();
  387. for state in states {
  388. if state.state != State::Spent {
  389. panic!("All proofs should be spent");
  390. }
  391. }
  392. }
  393. }
  394. /// Tests that wallet restore correctly handles non-sequential counter values
  395. ///
  396. /// This test verifies that after restoring a wallet where there were gaps in the
  397. /// counter sequence (e.g., due to failed operations or multi-device usage), the
  398. /// wallet can continue to operate without errors.
  399. ///
  400. /// Test scenario:
  401. /// 1. Wallet mints proofs using counters 0-N
  402. /// 2. Counter is incremented to simulate failed operations that consumed counter values
  403. /// 3. Wallet mints more proofs using counters at higher values
  404. /// 4. New wallet restores from seed and finds proofs at non-sequential counter positions
  405. /// 5. Wallet should be able to continue normal operations (swaps) after restore
  406. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  407. async fn test_restore_with_counter_gap() {
  408. let seed = Mnemonic::generate(12).unwrap().to_seed_normalized("");
  409. let wallet = Wallet::new(
  410. &get_mint_url_from_env(),
  411. CurrencyUnit::Sat,
  412. Arc::new(memory::empty().await.unwrap()),
  413. seed,
  414. None,
  415. )
  416. .expect("failed to create new wallet");
  417. // Mint first batch of proofs (uses counters starting at 0)
  418. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  419. let invoice = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
  420. pay_if_regtest(&get_test_temp_dir(), &invoice)
  421. .await
  422. .unwrap();
  423. let _proofs1 = wallet
  424. .wait_and_mint_quote(
  425. mint_quote.clone(),
  426. SplitTarget::default(),
  427. None,
  428. tokio::time::Duration::from_secs(60),
  429. )
  430. .await
  431. .expect("first mint failed");
  432. assert_eq!(wallet.total_balance().await.unwrap(), 100.into());
  433. // Get the active keyset ID to increment counter
  434. let active_keyset = wallet.fetch_active_keyset().await.unwrap();
  435. let keyset_id = active_keyset.id;
  436. // Create a gap in the counter sequence
  437. // This simulates failed operations or multi-device usage where counter values
  438. // were consumed but no signatures were obtained
  439. let gap_size = 50u32;
  440. wallet
  441. .localstore
  442. .increment_keyset_counter(&keyset_id, gap_size)
  443. .await
  444. .unwrap();
  445. // Mint second batch of proofs (uses counters after the gap)
  446. let mint_quote2 = wallet.mint_quote(100.into(), None).await.unwrap();
  447. let invoice2 = Bolt11Invoice::from_str(&mint_quote2.request).unwrap();
  448. pay_if_regtest(&get_test_temp_dir(), &invoice2)
  449. .await
  450. .unwrap();
  451. let _proofs2 = wallet
  452. .wait_and_mint_quote(
  453. mint_quote2.clone(),
  454. SplitTarget::default(),
  455. None,
  456. tokio::time::Duration::from_secs(60),
  457. )
  458. .await
  459. .expect("second mint failed");
  460. assert_eq!(wallet.total_balance().await.unwrap(), 200.into());
  461. // Create a new wallet with the same seed (simulating wallet restore scenario)
  462. let wallet_restored = Wallet::new(
  463. &get_mint_url_from_env(),
  464. CurrencyUnit::Sat,
  465. Arc::new(memory::empty().await.unwrap()),
  466. seed,
  467. None,
  468. )
  469. .expect("failed to create restored wallet");
  470. assert_eq!(wallet_restored.total_balance().await.unwrap(), 0.into());
  471. // Restore the wallet - this should find proofs at non-sequential counter positions
  472. let restored = wallet_restored.restore().await.unwrap();
  473. assert_eq!(restored, 200.into());
  474. let proofs = wallet_restored.get_unspent_proofs().await.unwrap();
  475. assert!(!proofs.is_empty());
  476. // Swap the restored proofs to verify they are valid
  477. let expected_fee = wallet_restored.get_proofs_fee(&proofs).await.unwrap().total;
  478. wallet_restored
  479. .swap(None, SplitTarget::default(), proofs, None, false)
  480. .await
  481. .expect("first swap after restore failed");
  482. let balance_after_first_swap = Amount::from(200) - expected_fee;
  483. assert_eq!(
  484. wallet_restored.total_balance().await.unwrap(),
  485. balance_after_first_swap
  486. );
  487. // Perform multiple swaps to verify the wallet can continue operating
  488. // after restore with non-sequential counter values
  489. for i in 0..gap_size {
  490. let proofs = wallet_restored.get_unspent_proofs().await.unwrap();
  491. if proofs.is_empty() {
  492. break;
  493. }
  494. let swap_result = wallet_restored
  495. .swap(None, SplitTarget::default(), proofs.clone(), None, false)
  496. .await;
  497. match swap_result {
  498. Ok(_) => {
  499. // Swap succeeded, continue
  500. }
  501. Err(e) => {
  502. let error_str = format!("{:?}", e);
  503. if error_str.contains("BlindedMessageAlreadySigned") {
  504. panic!(
  505. "Got 'blinded message already signed' error on swap {} after restore. \
  506. Counter was not correctly set after restoring with non-sequential values.",
  507. i + 1
  508. );
  509. } else {
  510. // Some other error - might be expected (e.g., insufficient funds due to fees)
  511. break;
  512. }
  513. }
  514. }
  515. }
  516. }
  517. /// Tests that the melt quote status can be checked after a melt has completed
  518. ///
  519. /// This test verifies:
  520. /// 1. Mint tokens
  521. /// 2. Create a melt quote and execute the melt
  522. /// 3. Check the melt quote status via the wallet
  523. /// 4. Verify the quote is in the Paid state
  524. ///
  525. /// This ensures the mint correctly reports the melt quote status after completion.
  526. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  527. async fn test_melt_quote_status_after_melt() {
  528. let wallet = Wallet::new(
  529. &get_mint_url_from_env(),
  530. CurrencyUnit::Sat,
  531. Arc::new(memory::empty().await.unwrap()),
  532. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  533. None,
  534. )
  535. .expect("failed to create new wallet");
  536. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  537. let invoice = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
  538. pay_if_regtest(&get_test_temp_dir(), &invoice)
  539. .await
  540. .unwrap();
  541. let proofs = wallet
  542. .wait_and_mint_quote(
  543. mint_quote.clone(),
  544. SplitTarget::default(),
  545. None,
  546. tokio::time::Duration::from_secs(60),
  547. )
  548. .await
  549. .expect("mint failed");
  550. let mint_amount = proofs.total_amount().unwrap();
  551. assert_eq!(mint_amount, 100.into());
  552. let invoice = create_invoice_for_env(Some(50)).await.unwrap();
  553. let melt_quote = wallet.melt_quote(invoice, None).await.unwrap();
  554. let melt_response = wallet.melt(&melt_quote.id).await.unwrap();
  555. assert_eq!(melt_response.state, MeltQuoteState::Paid);
  556. let quote_status = wallet.melt_quote_status(&melt_quote.id).await.unwrap();
  557. assert_eq!(
  558. quote_status.state,
  559. MeltQuoteState::Paid,
  560. "Melt quote should be in Paid state after successful melt"
  561. );
  562. let db_quote = wallet
  563. .localstore
  564. .get_melt_quote(&melt_quote.id)
  565. .await
  566. .unwrap()
  567. .unwrap();
  568. assert_eq!(
  569. db_quote.state,
  570. MeltQuoteState::Paid,
  571. "Melt quote should be in Paid state after successful melt"
  572. );
  573. }
  574. /// Tests that the melt quote status can be checked via MultiMintWallet after a melt has completed
  575. ///
  576. /// This test verifies the same flow as test_melt_quote_status_after_melt but using
  577. /// the MultiMintWallet abstraction:
  578. /// 1. Create a MultiMintWallet and add a mint
  579. /// 2. Mint tokens via the multi mint wallet
  580. /// 3. Create a melt quote and execute the melt
  581. /// 4. Check the melt quote status via check_melt_quote
  582. /// 5. Verify the quote is in the Paid state
  583. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  584. async fn test_melt_quote_status_after_melt_multi_mint_wallet() {
  585. let seed = Mnemonic::generate(12).unwrap().to_seed_normalized("");
  586. let localstore = Arc::new(memory::empty().await.unwrap());
  587. let multi_mint_wallet = MultiMintWallet::new(localstore.clone(), seed, CurrencyUnit::Sat)
  588. .await
  589. .expect("failed to create multi mint wallet");
  590. let mint_url = MintUrl::from_str(&get_mint_url_from_env()).expect("invalid mint url");
  591. multi_mint_wallet
  592. .add_mint(mint_url.clone())
  593. .await
  594. .expect("failed to add mint");
  595. let mint_quote = multi_mint_wallet
  596. .mint_quote(&mint_url, 100.into(), None)
  597. .await
  598. .unwrap();
  599. let invoice = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
  600. pay_if_regtest(&get_test_temp_dir(), &invoice)
  601. .await
  602. .unwrap();
  603. let _proofs = multi_mint_wallet
  604. .wait_for_mint_quote(&mint_url, &mint_quote.id, SplitTarget::default(), None, 60)
  605. .await
  606. .expect("mint failed");
  607. let balance = multi_mint_wallet.total_balance().await.unwrap();
  608. assert_eq!(balance, 100.into());
  609. let invoice = create_invoice_for_env(Some(50)).await.unwrap();
  610. let melt_quote = multi_mint_wallet
  611. .melt_quote(&mint_url, invoice, None)
  612. .await
  613. .unwrap();
  614. let melt_response = multi_mint_wallet
  615. .melt_with_mint(&mint_url, &melt_quote.id)
  616. .await
  617. .unwrap();
  618. assert_eq!(melt_response.state, MeltQuoteState::Paid);
  619. let quote_status = multi_mint_wallet
  620. .check_melt_quote(&mint_url, &melt_quote.id)
  621. .await
  622. .unwrap();
  623. assert_eq!(
  624. quote_status.state,
  625. MeltQuoteState::Paid,
  626. "Melt quote should be in Paid state after successful melt (via MultiMintWallet)"
  627. );
  628. use cdk_common::database::WalletDatabase;
  629. let db_quote = localstore
  630. .get_melt_quote(&melt_quote.id)
  631. .await
  632. .unwrap()
  633. .unwrap();
  634. assert_eq!(
  635. db_quote.state,
  636. MeltQuoteState::Paid,
  637. "Melt quote should be in Paid state after successful melt"
  638. );
  639. }
  640. /// Tests that change outputs in a melt quote are correctly handled
  641. ///
  642. /// This test verifies the following workflow:
  643. /// 1. Mint 100 sats of tokens
  644. /// 2. Create a melt quote for 9 sats (which requires 100 sats input with 91 sats change)
  645. /// 3. Manually construct a melt request with proofs and blinded messages for change
  646. /// 4. Verify that the change proofs in the response match what's reported by the quote status
  647. ///
  648. /// This ensures the mint correctly processes change outputs during melting operations
  649. /// and that the wallet can properly verify the change amounts match expectations.
  650. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  651. async fn test_fake_melt_change_in_quote() {
  652. let wallet = Wallet::new(
  653. &get_mint_url_from_env(),
  654. CurrencyUnit::Sat,
  655. Arc::new(memory::empty().await.unwrap()),
  656. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  657. None,
  658. )
  659. .expect("failed to create new wallet");
  660. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  661. let bolt11 = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
  662. pay_if_regtest(&get_test_temp_dir(), &bolt11).await.unwrap();
  663. let _proofs = wallet
  664. .wait_and_mint_quote(
  665. mint_quote.clone(),
  666. SplitTarget::default(),
  667. None,
  668. tokio::time::Duration::from_secs(60),
  669. )
  670. .await
  671. .expect("payment");
  672. let invoice = create_invoice_for_env(Some(9)).await.unwrap();
  673. let proofs = wallet.get_unspent_proofs().await.unwrap();
  674. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  675. let keyset = wallet.fetch_active_keyset().await.unwrap();
  676. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  677. let premint_secrets = PreMintSecrets::random(
  678. keyset.id,
  679. 100.into(),
  680. &SplitTarget::default(),
  681. &fee_and_amounts,
  682. )
  683. .unwrap();
  684. let client = HttpClient::new(get_mint_url_from_env().parse().unwrap(), None);
  685. let melt_request = MeltRequest::new(
  686. melt_quote.id.clone(),
  687. proofs.clone(),
  688. Some(premint_secrets.blinded_messages()),
  689. );
  690. let melt_response = client.post_melt(melt_request).await.unwrap();
  691. assert!(melt_response.change.is_some());
  692. let check = wallet.melt_quote_status(&melt_quote.id).await.unwrap();
  693. let mut melt_change = melt_response.change.unwrap();
  694. melt_change.sort_by(|a, b| a.amount.cmp(&b.amount));
  695. let mut check = check.change.unwrap();
  696. check.sort_by(|a, b| a.amount.cmp(&b.amount));
  697. assert_eq!(melt_change, check);
  698. }
  699. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  700. async fn test_pay_invoice_twice() {
  701. let ln_backend = match env::var("LN_BACKEND") {
  702. Ok(val) => Some(val),
  703. Err(_) => env::var("CDK_MINTD_LN_BACKEND").ok(),
  704. };
  705. if ln_backend.map(|ln| ln.to_uppercase()) == Some("FAKEWALLET".to_string()) {
  706. // We can only perform this test on regtest backends as fake wallet just marks the quote as paid
  707. return;
  708. }
  709. let wallet = Wallet::new(
  710. &get_mint_url_from_env(),
  711. CurrencyUnit::Sat,
  712. Arc::new(memory::empty().await.unwrap()),
  713. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  714. None,
  715. )
  716. .expect("failed to create new wallet");
  717. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  718. pay_if_regtest(&get_test_temp_dir(), &mint_quote.request.parse().unwrap())
  719. .await
  720. .unwrap();
  721. let proofs = wallet
  722. .wait_and_mint_quote(
  723. mint_quote.clone(),
  724. SplitTarget::default(),
  725. None,
  726. tokio::time::Duration::from_secs(60),
  727. )
  728. .await
  729. .expect("payment");
  730. let mint_amount = proofs.total_amount().unwrap();
  731. assert_eq!(mint_amount, 100.into());
  732. let invoice = create_invoice_for_env(Some(25)).await.unwrap();
  733. let melt_quote = wallet.melt_quote(invoice.clone(), None).await.unwrap();
  734. let melt = wallet.melt(&melt_quote.id).await.unwrap();
  735. // Creating a second quote for the same invoice is allowed
  736. let melt_quote_two = wallet.melt_quote(invoice, None).await.unwrap();
  737. // But attempting to melt (pay) the second quote should fail
  738. // since the first quote with the same lookup_id is already paid
  739. let melt_two = wallet.melt(&melt_quote_two.id).await;
  740. match melt_two {
  741. Err(err) => {
  742. let err_str = err.to_string().to_lowercase();
  743. if !err_str.contains("duplicate")
  744. && !err_str.contains("already paid")
  745. && !err_str.contains("request already paid")
  746. {
  747. panic!(
  748. "Expected duplicate/already paid error, got: {}",
  749. err.to_string()
  750. );
  751. }
  752. }
  753. Ok(_) => {
  754. panic!("Should not have allowed second payment");
  755. }
  756. }
  757. let balance = wallet.total_balance().await.unwrap();
  758. assert_eq!(balance, (Amount::from(100) - melt.fee_paid - melt.amount));
  759. }