happy_path_mint_wallet.rs 16 KB

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