happy_path_mint_wallet.rs 16 KB

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