happy_path_mint_wallet.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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(Some(50)).await.unwrap();
  110. let melt = wallet.melt_quote(invoice, None).await.unwrap();
  111. write
  112. .send(Message::Text(
  113. serde_json::to_string(&json!({
  114. "jsonrpc": "2.0",
  115. "id": 2,
  116. "method": "subscribe",
  117. "params": {
  118. "kind": "bolt11_melt_quote",
  119. "filters": [
  120. melt.id.clone(),
  121. ],
  122. "subId": "test-sub",
  123. }
  124. }))
  125. .unwrap()
  126. .into(),
  127. ))
  128. .await
  129. .unwrap();
  130. // Parse both JSON strings to objects and compare them instead of comparing strings directly
  131. let binding = reader.next().await.unwrap().unwrap();
  132. let response_str = binding.to_text().unwrap();
  133. let response_json: serde_json::Value =
  134. serde_json::from_str(response_str).expect("Valid JSON response");
  135. let expected_json: serde_json::Value = serde_json::from_str(
  136. r#"{"jsonrpc":"2.0","result":{"status":"OK","subId":"test-sub"},"id":2}"#,
  137. )
  138. .expect("Valid JSON expected");
  139. assert_eq!(response_json, expected_json);
  140. let melt_response = wallet.melt(&melt.id).await.unwrap();
  141. assert!(melt_response.preimage.is_some());
  142. assert!(melt_response.state == MeltQuoteState::Paid);
  143. let (sub_id, payload) = get_notification(&mut reader, Duration::from_millis(15000)).await;
  144. // first message is the current state
  145. assert_eq!("test-sub", sub_id);
  146. let payload = match payload {
  147. NotificationPayload::MeltQuoteBolt11Response(melt) => melt,
  148. _ => panic!("Wrong payload"),
  149. };
  150. // assert_eq!(payload.amount + payload.fee_reserve, 50.into());
  151. assert_eq!(payload.quote.to_string(), melt.id);
  152. assert_eq!(payload.state, MeltQuoteState::Unpaid);
  153. // get current state
  154. let (sub_id, payload) = get_notification(&mut reader, Duration::from_millis(15000)).await;
  155. assert_eq!("test-sub", sub_id);
  156. let payload = match payload {
  157. NotificationPayload::MeltQuoteBolt11Response(melt) => melt,
  158. _ => panic!("Wrong payload"),
  159. };
  160. assert_eq!(payload.quote.to_string(), melt.id);
  161. assert_eq!(payload.state, MeltQuoteState::Pending);
  162. // get current state
  163. let (sub_id, payload) = get_notification(&mut reader, Duration::from_millis(15000)).await;
  164. assert_eq!("test-sub", sub_id);
  165. let payload = match payload {
  166. NotificationPayload::MeltQuoteBolt11Response(melt) => melt,
  167. _ => panic!("Wrong payload"),
  168. };
  169. assert_eq!(payload.amount, 50.into());
  170. assert_eq!(payload.quote.to_string(), melt.id);
  171. assert_eq!(payload.state, MeltQuoteState::Paid);
  172. }
  173. /// Tests basic minting functionality with payment verification
  174. ///
  175. /// This test focuses on the core minting process:
  176. /// 1. Creates a mint quote for a specific amount (100 sats)
  177. /// 2. Verifies the quote has the correct amount
  178. /// 3. Pays the invoice (or simulates payment in non-regtest environments)
  179. /// 4. Waits for the mint to recognize the payment
  180. /// 5. Mints tokens and verifies the correct amount was received
  181. ///
  182. /// This ensures the basic minting flow works correctly from quote to token issuance.
  183. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  184. async fn test_happy_mint() {
  185. let wallet = Wallet::new(
  186. &get_mint_url_from_env(),
  187. CurrencyUnit::Sat,
  188. Arc::new(memory::empty().await.unwrap()),
  189. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  190. None,
  191. )
  192. .expect("failed to create new wallet");
  193. let mint_amount = Amount::from(100);
  194. let mint_quote = wallet.mint_quote(mint_amount, None).await.unwrap();
  195. assert_eq!(mint_quote.amount, Some(mint_amount));
  196. let invoice = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
  197. pay_if_regtest(&get_test_temp_dir(), &invoice)
  198. .await
  199. .unwrap();
  200. wallet
  201. .wait_for_payment(&mint_quote, Duration::from_secs(60))
  202. .await
  203. .unwrap();
  204. let proofs = wallet
  205. .mint(&mint_quote.id, SplitTarget::default(), None)
  206. .await
  207. .unwrap();
  208. let mint_amount = proofs.total_amount().unwrap();
  209. assert!(mint_amount == 100.into());
  210. }
  211. /// Tests wallet restoration and proof state verification
  212. ///
  213. /// This test verifies the wallet restoration process:
  214. /// 1. Creates a wallet with a specific seed and mints tokens
  215. /// 2. Verifies the wallet has the expected balance
  216. /// 3. Creates a new wallet instance with the same seed but empty storage
  217. /// 4. Confirms the new wallet starts with zero balance
  218. /// 5. Restores the wallet state from the mint
  219. /// 6. Swaps the proofs to ensure they're valid
  220. /// 7. Verifies the restored wallet has the correct balance
  221. /// 8. Checks that the original proofs are now marked as spent
  222. ///
  223. /// This ensures wallet restoration works correctly and that
  224. /// the mint properly tracks spent proofs across wallet instances.
  225. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  226. async fn test_restore() {
  227. let seed = Mnemonic::generate(12).unwrap().to_seed_normalized("");
  228. let wallet = Wallet::new(
  229. &get_mint_url_from_env(),
  230. CurrencyUnit::Sat,
  231. Arc::new(memory::empty().await.unwrap()),
  232. seed,
  233. None,
  234. )
  235. .expect("failed to create new wallet");
  236. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  237. let invoice = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
  238. pay_if_regtest(&get_test_temp_dir(), &invoice)
  239. .await
  240. .unwrap();
  241. wallet
  242. .wait_for_payment(&mint_quote, Duration::from_secs(60))
  243. .await
  244. .unwrap();
  245. let _mint_amount = wallet
  246. .mint(&mint_quote.id, SplitTarget::default(), None)
  247. .await
  248. .unwrap();
  249. assert_eq!(wallet.total_balance().await.unwrap(), 100.into());
  250. let wallet_2 = 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. assert_eq!(wallet_2.total_balance().await.unwrap(), 0.into());
  259. let restored = wallet_2.restore().await.unwrap();
  260. let proofs = wallet_2.get_unspent_proofs().await.unwrap();
  261. assert!(!proofs.is_empty());
  262. let expected_fee = wallet.get_proofs_fee(&proofs).await.unwrap();
  263. wallet_2
  264. .swap(None, SplitTarget::default(), proofs, None, false)
  265. .await
  266. .unwrap();
  267. assert_eq!(restored, 100.into());
  268. // Since we have to do a swap we expect to restore amount - fee
  269. assert_eq!(
  270. wallet_2.total_balance().await.unwrap(),
  271. Amount::from(100) - expected_fee
  272. );
  273. let proofs = wallet.get_unspent_proofs().await.unwrap();
  274. let states = wallet.check_proofs_spent(proofs).await.unwrap();
  275. for state in states {
  276. if state.state != State::Spent {
  277. panic!("All proofs should be spent");
  278. }
  279. }
  280. }
  281. /// Tests that change outputs in a melt quote are correctly handled
  282. ///
  283. /// This test verifies the following workflow:
  284. /// 1. Mint 100 sats of tokens
  285. /// 2. Create a melt quote for 9 sats (which requires 100 sats input with 91 sats change)
  286. /// 3. Manually construct a melt request with proofs and blinded messages for change
  287. /// 4. Verify that the change proofs in the response match what's reported by the quote status
  288. ///
  289. /// This ensures the mint correctly processes change outputs during melting operations
  290. /// and that the wallet can properly verify the change amounts match expectations.
  291. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  292. async fn test_fake_melt_change_in_quote() {
  293. let wallet = Wallet::new(
  294. &get_mint_url_from_env(),
  295. CurrencyUnit::Sat,
  296. Arc::new(memory::empty().await.unwrap()),
  297. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  298. None,
  299. )
  300. .expect("failed to create new wallet");
  301. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  302. let bolt11 = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
  303. pay_if_regtest(&get_test_temp_dir(), &bolt11).await.unwrap();
  304. wallet
  305. .wait_for_payment(&mint_quote, Duration::from_secs(60))
  306. .await
  307. .unwrap();
  308. let _mint_amount = wallet
  309. .mint(&mint_quote.id, SplitTarget::default(), None)
  310. .await
  311. .unwrap();
  312. let invoice = create_invoice_for_env(Some(9)).await.unwrap();
  313. let proofs = wallet.get_unspent_proofs().await.unwrap();
  314. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  315. let keyset = wallet.fetch_active_keyset().await.unwrap();
  316. let premint_secrets =
  317. PreMintSecrets::random(keyset.id, 100.into(), &SplitTarget::default()).unwrap();
  318. let client = HttpClient::new(get_mint_url_from_env().parse().unwrap(), None);
  319. let melt_request = MeltRequest::new(
  320. melt_quote.id.clone(),
  321. proofs.clone(),
  322. Some(premint_secrets.blinded_messages()),
  323. );
  324. let melt_response = client.post_melt(melt_request).await.unwrap();
  325. assert!(melt_response.change.is_some());
  326. let check = wallet.melt_quote_status(&melt_quote.id).await.unwrap();
  327. let mut melt_change = melt_response.change.unwrap();
  328. melt_change.sort_by(|a, b| a.amount.cmp(&b.amount));
  329. let mut check = check.change.unwrap();
  330. check.sort_by(|a, b| a.amount.cmp(&b.amount));
  331. assert_eq!(melt_change, check);
  332. }
  333. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  334. async fn test_pay_invoice_twice() {
  335. let ln_backend = match env::var("LN_BACKEND") {
  336. Ok(val) => Some(val),
  337. Err(_) => env::var("CDK_MINTD_LN_BACKEND").ok(),
  338. };
  339. if ln_backend.map(|ln| ln.to_uppercase()) == Some("FAKEWALLET".to_string()) {
  340. // We can only perform this test on regtest backends as fake wallet just marks the quote as paid
  341. return;
  342. }
  343. let wallet = Wallet::new(
  344. &get_mint_url_from_env(),
  345. CurrencyUnit::Sat,
  346. Arc::new(memory::empty().await.unwrap()),
  347. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  348. None,
  349. )
  350. .expect("failed to create new wallet");
  351. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  352. pay_if_regtest(&get_test_temp_dir(), &mint_quote.request.parse().unwrap())
  353. .await
  354. .unwrap();
  355. wallet
  356. .wait_for_payment(&mint_quote, Duration::from_secs(60))
  357. .await
  358. .unwrap();
  359. let proofs = wallet
  360. .mint(&mint_quote.id, SplitTarget::default(), None)
  361. .await
  362. .unwrap();
  363. let mint_amount = proofs.total_amount().unwrap();
  364. assert_eq!(mint_amount, 100.into());
  365. let invoice = create_invoice_for_env(Some(25)).await.unwrap();
  366. let melt_quote = wallet.melt_quote(invoice.clone(), None).await.unwrap();
  367. let melt = wallet.melt(&melt_quote.id).await.unwrap();
  368. let melt_two = wallet.melt_quote(invoice, None).await;
  369. match melt_two {
  370. Err(err) => match err {
  371. cdk::Error::RequestAlreadyPaid => (),
  372. err => {
  373. if !err.to_string().contains("Duplicate entry") {
  374. panic!("Wrong invoice already paid: {}", err.to_string());
  375. }
  376. }
  377. },
  378. Ok(_) => {
  379. panic!("Should not have allowed second payment");
  380. }
  381. }
  382. let balance = wallet.total_balance().await.unwrap();
  383. assert_eq!(balance, (Amount::from(100) - melt.fee_paid - melt.amount));
  384. }