happy_path_mint_wallet.rs 16 KB

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