happy_path_mint_wallet.rs 16 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. let proofs = wallet
  100. .wait_and_mint_quote(
  101. mint_quote.clone(),
  102. SplitTarget::default(),
  103. None,
  104. tokio::time::Duration::from_secs(60),
  105. )
  106. .await
  107. .expect("payment");
  108. let mint_amount = proofs.total_amount().unwrap();
  109. assert!(mint_amount == 100.into());
  110. let invoice = create_invoice_for_env(Some(50)).await.unwrap();
  111. let melt = wallet.melt_quote(invoice, None).await.unwrap();
  112. write
  113. .send(Message::Text(
  114. serde_json::to_string(&json!({
  115. "jsonrpc": "2.0",
  116. "id": 2,
  117. "method": "subscribe",
  118. "params": {
  119. "kind": "bolt11_melt_quote",
  120. "filters": [
  121. melt.id.clone(),
  122. ],
  123. "subId": "test-sub",
  124. }
  125. }))
  126. .unwrap()
  127. .into(),
  128. ))
  129. .await
  130. .unwrap();
  131. // Parse both JSON strings to objects and compare them instead of comparing strings directly
  132. let binding = reader.next().await.unwrap().unwrap();
  133. let response_str = binding.to_text().unwrap();
  134. let response_json: serde_json::Value =
  135. serde_json::from_str(response_str).expect("Valid JSON response");
  136. let expected_json: serde_json::Value = serde_json::from_str(
  137. r#"{"jsonrpc":"2.0","result":{"status":"OK","subId":"test-sub"},"id":2}"#,
  138. )
  139. .expect("Valid JSON expected");
  140. assert_eq!(response_json, expected_json);
  141. let melt_response = wallet.melt(&melt.id).await.unwrap();
  142. assert!(melt_response.preimage.is_some());
  143. assert!(melt_response.state == MeltQuoteState::Paid);
  144. let (sub_id, payload) = get_notification(&mut reader, Duration::from_millis(15000)).await;
  145. // first message is the current state
  146. assert_eq!("test-sub", sub_id);
  147. let payload = match payload {
  148. NotificationPayload::MeltQuoteBolt11Response(melt) => melt,
  149. _ => panic!("Wrong payload"),
  150. };
  151. // assert_eq!(payload.amount + payload.fee_reserve, 50.into());
  152. assert_eq!(payload.quote.to_string(), melt.id);
  153. assert_eq!(payload.state, MeltQuoteState::Unpaid);
  154. // get current state
  155. let (sub_id, payload) = get_notification(&mut reader, Duration::from_millis(15000)).await;
  156. assert_eq!("test-sub", sub_id);
  157. let payload = match payload {
  158. NotificationPayload::MeltQuoteBolt11Response(melt) => melt,
  159. _ => panic!("Wrong payload"),
  160. };
  161. assert_eq!(payload.quote.to_string(), melt.id);
  162. assert_eq!(payload.state, MeltQuoteState::Pending);
  163. // get current state
  164. let (sub_id, payload) = get_notification(&mut reader, Duration::from_millis(15000)).await;
  165. assert_eq!("test-sub", sub_id);
  166. let payload = match payload {
  167. NotificationPayload::MeltQuoteBolt11Response(melt) => melt,
  168. _ => panic!("Wrong payload"),
  169. };
  170. assert_eq!(payload.amount, 50.into());
  171. assert_eq!(payload.quote.to_string(), melt.id);
  172. assert_eq!(payload.state, MeltQuoteState::Paid);
  173. }
  174. /// Tests basic minting functionality with payment verification
  175. ///
  176. /// This test focuses on the core minting process:
  177. /// 1. Creates a mint quote for a specific amount (100 sats)
  178. /// 2. Verifies the quote has the correct amount
  179. /// 3. Pays the invoice (or simulates payment in non-regtest environments)
  180. /// 4. Waits for the mint to recognize the payment
  181. /// 5. Mints tokens and verifies the correct amount was received
  182. ///
  183. /// This ensures the basic minting flow works correctly from quote to token issuance.
  184. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  185. async fn test_happy_mint() {
  186. let wallet = Wallet::new(
  187. &get_mint_url_from_env(),
  188. CurrencyUnit::Sat,
  189. Arc::new(memory::empty().await.unwrap()),
  190. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  191. None,
  192. )
  193. .expect("failed to create new wallet");
  194. let mint_amount = Amount::from(100);
  195. let mint_quote = wallet.mint_quote(mint_amount, None).await.unwrap();
  196. assert_eq!(mint_quote.amount, Some(mint_amount));
  197. let invoice = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
  198. pay_if_regtest(&get_test_temp_dir(), &invoice)
  199. .await
  200. .unwrap();
  201. let proofs = wallet
  202. .wait_and_mint_quote(
  203. mint_quote.clone(),
  204. SplitTarget::default(),
  205. None,
  206. tokio::time::Duration::from_secs(60),
  207. )
  208. .await
  209. .expect("payment");
  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. let _proofs = wallet
  244. .wait_and_mint_quote(
  245. mint_quote.clone(),
  246. SplitTarget::default(),
  247. None,
  248. tokio::time::Duration::from_secs(60),
  249. )
  250. .await
  251. .expect("payment");
  252. assert_eq!(wallet.total_balance().await.unwrap(), 100.into());
  253. let wallet_2 = Wallet::new(
  254. &get_mint_url_from_env(),
  255. CurrencyUnit::Sat,
  256. Arc::new(memory::empty().await.unwrap()),
  257. seed,
  258. None,
  259. )
  260. .expect("failed to create new wallet");
  261. assert_eq!(wallet_2.total_balance().await.unwrap(), 0.into());
  262. let restored = wallet_2.restore().await.unwrap();
  263. let proofs = wallet_2.get_unspent_proofs().await.unwrap();
  264. assert!(!proofs.is_empty());
  265. let expected_fee = wallet.get_proofs_fee(&proofs).await.unwrap();
  266. wallet_2
  267. .swap(None, SplitTarget::default(), proofs, None, false)
  268. .await
  269. .unwrap();
  270. assert_eq!(restored, 100.into());
  271. // Since we have to do a swap we expect to restore amount - fee
  272. assert_eq!(
  273. wallet_2.total_balance().await.unwrap(),
  274. Amount::from(100) - expected_fee
  275. );
  276. let proofs = wallet.get_unspent_proofs().await.unwrap();
  277. let states = wallet.check_proofs_spent(proofs).await.unwrap();
  278. for state in states {
  279. if state.state != State::Spent {
  280. panic!("All proofs should be spent");
  281. }
  282. }
  283. }
  284. /// Tests that change outputs in a melt quote are correctly handled
  285. ///
  286. /// This test verifies the following workflow:
  287. /// 1. Mint 100 sats of tokens
  288. /// 2. Create a melt quote for 9 sats (which requires 100 sats input with 91 sats change)
  289. /// 3. Manually construct a melt request with proofs and blinded messages for change
  290. /// 4. Verify that the change proofs in the response match what's reported by the quote status
  291. ///
  292. /// This ensures the mint correctly processes change outputs during melting operations
  293. /// and that the wallet can properly verify the change amounts match expectations.
  294. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  295. async fn test_fake_melt_change_in_quote() {
  296. let wallet = Wallet::new(
  297. &get_mint_url_from_env(),
  298. CurrencyUnit::Sat,
  299. Arc::new(memory::empty().await.unwrap()),
  300. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  301. None,
  302. )
  303. .expect("failed to create new wallet");
  304. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  305. let bolt11 = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
  306. pay_if_regtest(&get_test_temp_dir(), &bolt11).await.unwrap();
  307. let _proofs = wallet
  308. .wait_and_mint_quote(
  309. mint_quote.clone(),
  310. SplitTarget::default(),
  311. None,
  312. tokio::time::Duration::from_secs(60),
  313. )
  314. .await
  315. .expect("payment");
  316. let invoice = create_invoice_for_env(Some(9)).await.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. let proofs = wallet
  360. .wait_and_mint_quote(
  361. mint_quote.clone(),
  362. SplitTarget::default(),
  363. None,
  364. tokio::time::Duration::from_secs(60),
  365. )
  366. .await
  367. .expect("payment");
  368. let mint_amount = proofs.total_amount().unwrap();
  369. assert_eq!(mint_amount, 100.into());
  370. let invoice = create_invoice_for_env(Some(25)).await.unwrap();
  371. let melt_quote = wallet.melt_quote(invoice.clone(), None).await.unwrap();
  372. let melt = wallet.melt(&melt_quote.id).await.unwrap();
  373. let melt_two = wallet.melt_quote(invoice, None).await;
  374. match melt_two {
  375. Err(err) => match err {
  376. cdk::Error::RequestAlreadyPaid => (),
  377. err => {
  378. if !err.to_string().contains("Duplicate entry") {
  379. panic!("Wrong invoice already paid: {}", err.to_string());
  380. }
  381. }
  382. },
  383. Ok(_) => {
  384. panic!("Should not have allowed second payment");
  385. }
  386. }
  387. let balance = wallet.total_balance().await.unwrap();
  388. assert_eq!(balance, (Amount::from(100) - melt.fee_paid - melt.amount));
  389. }