happy_path_mint_wallet.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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::env;
  12. use std::fmt::Debug;
  13. use std::path::PathBuf;
  14. use std::str::FromStr;
  15. use std::sync::Arc;
  16. use std::time::Duration;
  17. use bip39::Mnemonic;
  18. use cashu::{MeltRequest, PreMintSecrets};
  19. use cdk::amount::{Amount, SplitTarget};
  20. use cdk::nuts::nut00::ProofsMethods;
  21. use cdk::nuts::{CurrencyUnit, MeltQuoteState, NotificationPayload, State};
  22. use cdk::wallet::{HttpClient, MintConnector, Wallet};
  23. use cdk_integration_tests::{create_invoice_for_env, get_mint_url_from_env, pay_if_regtest};
  24. use cdk_sqlite::wallet::memory;
  25. use futures::{SinkExt, StreamExt};
  26. use lightning_invoice::Bolt11Invoice;
  27. use serde_json::json;
  28. use tokio::time::timeout;
  29. use tokio_tungstenite::connect_async;
  30. use tokio_tungstenite::tungstenite::protocol::Message;
  31. // Helper function to get temp directory from environment or fallback
  32. fn get_test_temp_dir() -> PathBuf {
  33. match env::var("CDK_ITESTS_DIR") {
  34. Ok(dir) => PathBuf::from(dir),
  35. Err(_) => panic!("Unknown test dir"),
  36. }
  37. }
  38. async fn get_notification<T: StreamExt<Item = Result<Message, E>> + Unpin, E: Debug>(
  39. reader: &mut T,
  40. timeout_to_wait: Duration,
  41. ) -> (String, NotificationPayload<String>) {
  42. let msg = timeout(timeout_to_wait, reader.next())
  43. .await
  44. .expect("timeout")
  45. .unwrap()
  46. .unwrap();
  47. let mut response: serde_json::Value =
  48. serde_json::from_str(msg.to_text().unwrap()).expect("valid json");
  49. let mut params_raw = response
  50. .as_object_mut()
  51. .expect("object")
  52. .remove("params")
  53. .expect("valid params");
  54. let params_map = params_raw.as_object_mut().expect("params is object");
  55. (
  56. params_map
  57. .remove("subId")
  58. .unwrap()
  59. .as_str()
  60. .unwrap()
  61. .to_string(),
  62. serde_json::from_value(params_map.remove("payload").unwrap()).unwrap(),
  63. )
  64. }
  65. /// Tests a complete mint-melt round trip with WebSocket notifications
  66. ///
  67. /// This test verifies the full lifecycle of tokens:
  68. /// 1. Creates a mint quote and pays the invoice
  69. /// 2. Mints tokens and verifies the correct amount
  70. /// 3. Creates a melt quote to spend tokens
  71. /// 4. Subscribes to WebSocket notifications for the melt process
  72. /// 5. Executes the melt and verifies the payment was successful
  73. /// 6. Validates all WebSocket notifications received during the process
  74. ///
  75. /// This ensures the entire mint-melt flow works correctly and that
  76. /// WebSocket notifications are properly sent at each state transition.
  77. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  78. async fn test_happy_mint_melt_round_trip() {
  79. let wallet = Wallet::new(
  80. &get_mint_url_from_env(),
  81. CurrencyUnit::Sat,
  82. Arc::new(memory::empty().await.unwrap()),
  83. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  84. None,
  85. )
  86. .expect("failed to create new wallet");
  87. let (ws_stream, _) = connect_async(format!(
  88. "{}/v1/ws",
  89. get_mint_url_from_env().replace("http", "ws")
  90. ))
  91. .await
  92. .expect("Failed to connect");
  93. let (mut write, mut reader) = ws_stream.split();
  94. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  95. let invoice = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
  96. pay_if_regtest(&get_test_temp_dir(), &invoice)
  97. .await
  98. .unwrap();
  99. wallet
  100. .wait_for_payment(&mint_quote, Duration::from_secs(60))
  101. .await
  102. .unwrap();
  103. let proofs = wallet
  104. .mint(&mint_quote.id, SplitTarget::default(), None)
  105. .await
  106. .unwrap();
  107. let mint_amount = proofs.total_amount().unwrap();
  108. assert!(mint_amount == 100.into());
  109. let invoice = create_invoice_for_env(&get_test_temp_dir(), Some(50))
  110. .await
  111. .unwrap();
  112. let melt = wallet.melt_quote(invoice, None).await.unwrap();
  113. write
  114. .send(Message::Text(
  115. serde_json::to_string(&json!({
  116. "jsonrpc": "2.0",
  117. "id": 2,
  118. "method": "subscribe",
  119. "params": {
  120. "kind": "bolt11_melt_quote",
  121. "filters": [
  122. melt.id.clone(),
  123. ],
  124. "subId": "test-sub",
  125. }
  126. }))
  127. .unwrap()
  128. .into(),
  129. ))
  130. .await
  131. .unwrap();
  132. // Parse both JSON strings to objects and compare them instead of comparing strings directly
  133. let binding = reader.next().await.unwrap().unwrap();
  134. let response_str = binding.to_text().unwrap();
  135. let response_json: serde_json::Value =
  136. serde_json::from_str(response_str).expect("Valid JSON response");
  137. let expected_json: serde_json::Value = serde_json::from_str(
  138. r#"{"jsonrpc":"2.0","result":{"status":"OK","subId":"test-sub"},"id":2}"#,
  139. )
  140. .expect("Valid JSON expected");
  141. assert_eq!(response_json, expected_json);
  142. let melt_response = wallet.melt(&melt.id).await.unwrap();
  143. assert!(melt_response.preimage.is_some());
  144. assert!(melt_response.state == MeltQuoteState::Paid);
  145. let (sub_id, payload) = get_notification(&mut reader, Duration::from_millis(15000)).await;
  146. // first message is the current state
  147. assert_eq!("test-sub", sub_id);
  148. let payload = match payload {
  149. NotificationPayload::MeltQuoteBolt11Response(melt) => melt,
  150. _ => panic!("Wrong payload"),
  151. };
  152. // assert_eq!(payload.amount + payload.fee_reserve, 50.into());
  153. assert_eq!(payload.quote.to_string(), melt.id);
  154. assert_eq!(payload.state, MeltQuoteState::Unpaid);
  155. // get current state
  156. let (sub_id, payload) = get_notification(&mut reader, Duration::from_millis(15000)).await;
  157. assert_eq!("test-sub", sub_id);
  158. let payload = match payload {
  159. NotificationPayload::MeltQuoteBolt11Response(melt) => melt,
  160. _ => panic!("Wrong payload"),
  161. };
  162. assert_eq!(payload.quote.to_string(), melt.id);
  163. assert_eq!(payload.state, MeltQuoteState::Pending);
  164. // get current state
  165. let (sub_id, payload) = get_notification(&mut reader, Duration::from_millis(15000)).await;
  166. assert_eq!("test-sub", sub_id);
  167. let payload = match payload {
  168. NotificationPayload::MeltQuoteBolt11Response(melt) => melt,
  169. _ => panic!("Wrong payload"),
  170. };
  171. assert_eq!(payload.amount, 50.into());
  172. assert_eq!(payload.quote.to_string(), melt.id);
  173. assert_eq!(payload.state, MeltQuoteState::Paid);
  174. }
  175. /// Tests basic minting functionality with payment verification
  176. ///
  177. /// This test focuses on the core minting process:
  178. /// 1. Creates a mint quote for a specific amount (100 sats)
  179. /// 2. Verifies the quote has the correct amount
  180. /// 3. Pays the invoice (or simulates payment in non-regtest environments)
  181. /// 4. Waits for the mint to recognize the payment
  182. /// 5. Mints tokens and verifies the correct amount was received
  183. ///
  184. /// This ensures the basic minting flow works correctly from quote to token issuance.
  185. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  186. async fn test_happy_mint() {
  187. let wallet = Wallet::new(
  188. &get_mint_url_from_env(),
  189. CurrencyUnit::Sat,
  190. Arc::new(memory::empty().await.unwrap()),
  191. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  192. None,
  193. )
  194. .expect("failed to create new wallet");
  195. let mint_amount = Amount::from(100);
  196. let mint_quote = wallet.mint_quote(mint_amount, None).await.unwrap();
  197. assert_eq!(mint_quote.amount, Some(mint_amount));
  198. let invoice = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
  199. pay_if_regtest(&get_test_temp_dir(), &invoice)
  200. .await
  201. .unwrap();
  202. wallet
  203. .wait_for_payment(&mint_quote, Duration::from_secs(60))
  204. .await
  205. .unwrap();
  206. let proofs = wallet
  207. .mint(&mint_quote.id, SplitTarget::default(), None)
  208. .await
  209. .unwrap();
  210. let mint_amount = proofs.total_amount().unwrap();
  211. assert!(mint_amount == 100.into());
  212. }
  213. /// Tests wallet restoration and proof state verification
  214. ///
  215. /// This test verifies the wallet restoration process:
  216. /// 1. Creates a wallet with a specific seed and mints tokens
  217. /// 2. Verifies the wallet has the expected balance
  218. /// 3. Creates a new wallet instance with the same seed but empty storage
  219. /// 4. Confirms the new wallet starts with zero balance
  220. /// 5. Restores the wallet state from the mint
  221. /// 6. Swaps the proofs to ensure they're valid
  222. /// 7. Verifies the restored wallet has the correct balance
  223. /// 8. Checks that the original proofs are now marked as spent
  224. ///
  225. /// This ensures wallet restoration works correctly and that
  226. /// the mint properly tracks spent proofs across wallet instances.
  227. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  228. async fn test_restore() {
  229. let seed = Mnemonic::generate(12).unwrap().to_seed_normalized("");
  230. let wallet = Wallet::new(
  231. &get_mint_url_from_env(),
  232. CurrencyUnit::Sat,
  233. Arc::new(memory::empty().await.unwrap()),
  234. seed,
  235. None,
  236. )
  237. .expect("failed to create new wallet");
  238. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  239. let invoice = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
  240. pay_if_regtest(&get_test_temp_dir(), &invoice)
  241. .await
  242. .unwrap();
  243. wallet
  244. .wait_for_payment(&mint_quote, Duration::from_secs(60))
  245. .await
  246. .unwrap();
  247. let _mint_amount = wallet
  248. .mint(&mint_quote.id, SplitTarget::default(), None)
  249. .await
  250. .unwrap();
  251. assert_eq!(wallet.total_balance().await.unwrap(), 100.into());
  252. let wallet_2 = Wallet::new(
  253. &get_mint_url_from_env(),
  254. CurrencyUnit::Sat,
  255. Arc::new(memory::empty().await.unwrap()),
  256. seed,
  257. None,
  258. )
  259. .expect("failed to create new wallet");
  260. assert_eq!(wallet_2.total_balance().await.unwrap(), 0.into());
  261. let restored = wallet_2.restore().await.unwrap();
  262. let proofs = wallet_2.get_unspent_proofs().await.unwrap();
  263. assert!(!proofs.is_empty());
  264. let expected_fee = wallet.get_proofs_fee(&proofs).await.unwrap();
  265. wallet_2
  266. .swap(None, SplitTarget::default(), proofs, None, false)
  267. .await
  268. .unwrap();
  269. assert_eq!(restored, 100.into());
  270. // Since we have to do a swap we expect to restore amount - fee
  271. assert_eq!(
  272. wallet_2.total_balance().await.unwrap(),
  273. Amount::from(100) - expected_fee
  274. );
  275. let proofs = wallet.get_unspent_proofs().await.unwrap();
  276. let states = wallet.check_proofs_spent(proofs).await.unwrap();
  277. for state in states {
  278. if state.state != State::Spent {
  279. panic!("All proofs should be spent");
  280. }
  281. }
  282. }
  283. /// Tests that change outputs in a melt quote are correctly handled
  284. ///
  285. /// This test verifies the following workflow:
  286. /// 1. Mint 100 sats of tokens
  287. /// 2. Create a melt quote for 9 sats (which requires 100 sats input with 91 sats change)
  288. /// 3. Manually construct a melt request with proofs and blinded messages for change
  289. /// 4. Verify that the change proofs in the response match what's reported by the quote status
  290. ///
  291. /// This ensures the mint correctly processes change outputs during melting operations
  292. /// and that the wallet can properly verify the change amounts match expectations.
  293. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  294. async fn test_fake_melt_change_in_quote() {
  295. let wallet = Wallet::new(
  296. &get_mint_url_from_env(),
  297. CurrencyUnit::Sat,
  298. Arc::new(memory::empty().await.unwrap()),
  299. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  300. None,
  301. )
  302. .expect("failed to create new wallet");
  303. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  304. let bolt11 = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
  305. pay_if_regtest(&get_test_temp_dir(), &bolt11).await.unwrap();
  306. wallet
  307. .wait_for_payment(&mint_quote, Duration::from_secs(60))
  308. .await
  309. .unwrap();
  310. let _mint_amount = wallet
  311. .mint(&mint_quote.id, SplitTarget::default(), None)
  312. .await
  313. .unwrap();
  314. let invoice = create_invoice_for_env(&get_test_temp_dir(), Some(9))
  315. .await
  316. .unwrap();
  317. let proofs = wallet.get_unspent_proofs().await.unwrap();
  318. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  319. let keyset = wallet.fetch_active_keyset().await.unwrap();
  320. let premint_secrets =
  321. PreMintSecrets::random(keyset.id, 100.into(), &SplitTarget::default()).unwrap();
  322. let client = HttpClient::new(get_mint_url_from_env().parse().unwrap(), None);
  323. let melt_request = MeltRequest::new(
  324. melt_quote.id.clone(),
  325. proofs.clone(),
  326. Some(premint_secrets.blinded_messages()),
  327. );
  328. let melt_response = client.post_melt(melt_request).await.unwrap();
  329. assert!(melt_response.change.is_some());
  330. let check = wallet.melt_quote_status(&melt_quote.id).await.unwrap();
  331. let mut melt_change = melt_response.change.unwrap();
  332. melt_change.sort_by(|a, b| a.amount.cmp(&b.amount));
  333. let mut check = check.change.unwrap();
  334. check.sort_by(|a, b| a.amount.cmp(&b.amount));
  335. assert_eq!(melt_change, check);
  336. }
  337. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  338. async fn test_pay_invoice_twice() {
  339. let ln_backend = match env::var("LN_BACKEND") {
  340. Ok(val) => Some(val),
  341. Err(_) => env::var("CDK_MINTD_LN_BACKEND").ok(),
  342. };
  343. if ln_backend.map(|ln| ln.to_uppercase()) == Some("FAKEWALLET".to_string()) {
  344. // We can only perform this test on regtest backends as fake wallet just marks the quote as paid
  345. return;
  346. }
  347. let wallet = Wallet::new(
  348. &get_mint_url_from_env(),
  349. CurrencyUnit::Sat,
  350. Arc::new(memory::empty().await.unwrap()),
  351. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  352. None,
  353. )
  354. .expect("failed to create new wallet");
  355. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  356. pay_if_regtest(&get_test_temp_dir(), &mint_quote.request.parse().unwrap())
  357. .await
  358. .unwrap();
  359. wallet
  360. .wait_for_payment(&mint_quote, Duration::from_secs(60))
  361. .await
  362. .unwrap();
  363. let proofs = wallet
  364. .mint(&mint_quote.id, SplitTarget::default(), None)
  365. .await
  366. .unwrap();
  367. let mint_amount = proofs.total_amount().unwrap();
  368. assert_eq!(mint_amount, 100.into());
  369. let invoice = create_invoice_for_env(&get_test_temp_dir(), Some(25))
  370. .await
  371. .unwrap();
  372. let melt_quote = wallet.melt_quote(invoice.clone(), None).await.unwrap();
  373. let melt = wallet.melt(&melt_quote.id).await.unwrap();
  374. let melt_two = wallet.melt_quote(invoice, None).await;
  375. match melt_two {
  376. Err(err) => match err {
  377. cdk::Error::RequestAlreadyPaid => (),
  378. err => {
  379. if !err.to_string().contains("Duplicate entry") {
  380. panic!("Wrong invoice already paid: {}", err.to_string());
  381. }
  382. }
  383. },
  384. Ok(_) => {
  385. panic!("Should not have allowed second payment");
  386. }
  387. }
  388. let balance = wallet.total_balance().await.unwrap();
  389. assert_eq!(balance, (Amount::from(100) - melt.fee_paid - melt.amount));
  390. }