happy_path_mint_wallet.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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(mint_quote.clone(), SplitTarget::default(), None);
  100. let proofs = proof_streams
  101. .next()
  102. .await
  103. .expect("payment")
  104. .expect("no error");
  105. let mint_amount = proofs.total_amount().unwrap();
  106. assert!(mint_amount == 100.into());
  107. let invoice = create_invoice_for_env(&get_test_temp_dir(), Some(50))
  108. .await
  109. .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. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  201. let proofs = proof_streams
  202. .next()
  203. .await
  204. .expect("payment")
  205. .expect("no error");
  206. let mint_amount = proofs.total_amount().unwrap();
  207. assert!(mint_amount == 100.into());
  208. }
  209. /// Tests wallet restoration and proof state verification
  210. ///
  211. /// This test verifies the wallet restoration process:
  212. /// 1. Creates a wallet with a specific seed and mints tokens
  213. /// 2. Verifies the wallet has the expected balance
  214. /// 3. Creates a new wallet instance with the same seed but empty storage
  215. /// 4. Confirms the new wallet starts with zero balance
  216. /// 5. Restores the wallet state from the mint
  217. /// 6. Swaps the proofs to ensure they're valid
  218. /// 7. Verifies the restored wallet has the correct balance
  219. /// 8. Checks that the original proofs are now marked as spent
  220. ///
  221. /// This ensures wallet restoration works correctly and that
  222. /// the mint properly tracks spent proofs across wallet instances.
  223. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  224. async fn test_restore() {
  225. let seed = Mnemonic::generate(12).unwrap().to_seed_normalized("");
  226. let wallet = Wallet::new(
  227. &get_mint_url_from_env(),
  228. CurrencyUnit::Sat,
  229. Arc::new(memory::empty().await.unwrap()),
  230. seed,
  231. None,
  232. )
  233. .expect("failed to create new wallet");
  234. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  235. let invoice = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
  236. pay_if_regtest(&get_test_temp_dir(), &invoice)
  237. .await
  238. .unwrap();
  239. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  240. let _proofs = proof_streams
  241. .next()
  242. .await
  243. .expect("payment")
  244. .expect("no error");
  245. assert_eq!(wallet.total_balance().await.unwrap(), 100.into());
  246. let wallet_2 = Wallet::new(
  247. &get_mint_url_from_env(),
  248. CurrencyUnit::Sat,
  249. Arc::new(memory::empty().await.unwrap()),
  250. seed,
  251. None,
  252. )
  253. .expect("failed to create new wallet");
  254. assert_eq!(wallet_2.total_balance().await.unwrap(), 0.into());
  255. let restored = wallet_2.restore().await.unwrap();
  256. let proofs = wallet_2.get_unspent_proofs().await.unwrap();
  257. assert!(!proofs.is_empty());
  258. let expected_fee = wallet.get_proofs_fee(&proofs).await.unwrap();
  259. wallet_2
  260. .swap(None, SplitTarget::default(), proofs, None, false)
  261. .await
  262. .unwrap();
  263. assert_eq!(restored, 100.into());
  264. // Since we have to do a swap we expect to restore amount - fee
  265. assert_eq!(
  266. wallet_2.total_balance().await.unwrap(),
  267. Amount::from(100) - expected_fee
  268. );
  269. let proofs = wallet.get_unspent_proofs().await.unwrap();
  270. let states = wallet.check_proofs_spent(proofs).await.unwrap();
  271. for state in states {
  272. if state.state != State::Spent {
  273. panic!("All proofs should be spent");
  274. }
  275. }
  276. }
  277. /// Tests that change outputs in a melt quote are correctly handled
  278. ///
  279. /// This test verifies the following workflow:
  280. /// 1. Mint 100 sats of tokens
  281. /// 2. Create a melt quote for 9 sats (which requires 100 sats input with 91 sats change)
  282. /// 3. Manually construct a melt request with proofs and blinded messages for change
  283. /// 4. Verify that the change proofs in the response match what's reported by the quote status
  284. ///
  285. /// This ensures the mint correctly processes change outputs during melting operations
  286. /// and that the wallet can properly verify the change amounts match expectations.
  287. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  288. async fn test_fake_melt_change_in_quote() {
  289. let wallet = Wallet::new(
  290. &get_mint_url_from_env(),
  291. CurrencyUnit::Sat,
  292. Arc::new(memory::empty().await.unwrap()),
  293. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  294. None,
  295. )
  296. .expect("failed to create new wallet");
  297. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  298. let bolt11 = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
  299. pay_if_regtest(&get_test_temp_dir(), &bolt11).await.unwrap();
  300. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  301. let _proofs = proof_streams
  302. .next()
  303. .await
  304. .expect("payment")
  305. .expect("no error");
  306. let invoice = create_invoice_for_env(&get_test_temp_dir(), Some(9))
  307. .await
  308. .unwrap();
  309. let proofs = wallet.get_unspent_proofs().await.unwrap();
  310. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  311. let keyset = wallet.fetch_active_keyset().await.unwrap();
  312. let premint_secrets =
  313. PreMintSecrets::random(keyset.id, 100.into(), &SplitTarget::default()).unwrap();
  314. let client = HttpClient::new(get_mint_url_from_env().parse().unwrap(), None);
  315. let melt_request = MeltRequest::new(
  316. melt_quote.id.clone(),
  317. proofs.clone(),
  318. Some(premint_secrets.blinded_messages()),
  319. );
  320. let melt_response = client.post_melt(melt_request).await.unwrap();
  321. assert!(melt_response.change.is_some());
  322. let check = wallet.melt_quote_status(&melt_quote.id).await.unwrap();
  323. let mut melt_change = melt_response.change.unwrap();
  324. melt_change.sort_by(|a, b| a.amount.cmp(&b.amount));
  325. let mut check = check.change.unwrap();
  326. check.sort_by(|a, b| a.amount.cmp(&b.amount));
  327. assert_eq!(melt_change, check);
  328. }
  329. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  330. async fn test_pay_invoice_twice() {
  331. let ln_backend = match env::var("LN_BACKEND") {
  332. Ok(val) => Some(val),
  333. Err(_) => env::var("CDK_MINTD_LN_BACKEND").ok(),
  334. };
  335. if ln_backend.map(|ln| ln.to_uppercase()) == Some("FAKEWALLET".to_string()) {
  336. // We can only perform this test on regtest backends as fake wallet just marks the quote as paid
  337. return;
  338. }
  339. let wallet = Wallet::new(
  340. &get_mint_url_from_env(),
  341. CurrencyUnit::Sat,
  342. Arc::new(memory::empty().await.unwrap()),
  343. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  344. None,
  345. )
  346. .expect("failed to create new wallet");
  347. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  348. pay_if_regtest(&get_test_temp_dir(), &mint_quote.request.parse().unwrap())
  349. .await
  350. .unwrap();
  351. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  352. let proofs = proof_streams
  353. .next()
  354. .await
  355. .expect("payment")
  356. .expect("no error");
  357. let mint_amount = proofs.total_amount().unwrap();
  358. assert_eq!(mint_amount, 100.into());
  359. let invoice = create_invoice_for_env(&get_test_temp_dir(), Some(25))
  360. .await
  361. .unwrap();
  362. let melt_quote = wallet.melt_quote(invoice.clone(), None).await.unwrap();
  363. let melt = wallet.melt(&melt_quote.id).await.unwrap();
  364. let melt_two = wallet.melt_quote(invoice, None).await;
  365. match melt_two {
  366. Err(err) => match err {
  367. cdk::Error::RequestAlreadyPaid => (),
  368. err => {
  369. if !err.to_string().contains("Duplicate entry") {
  370. panic!("Wrong invoice already paid: {}", err.to_string());
  371. }
  372. }
  373. },
  374. Ok(_) => {
  375. panic!("Should not have allowed second payment");
  376. }
  377. }
  378. let balance = wallet.total_balance().await.unwrap();
  379. assert_eq!(balance, (Amount::from(100) - melt.fee_paid - melt.amount));
  380. }