happy_path_mint_wallet.rs 32 KB

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