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::collections::HashMap;
  12. use std::env;
  13. use std::fmt::Debug;
  14. use std::path::PathBuf;
  15. use std::str::FromStr;
  16. use std::sync::Arc;
  17. use std::time::Duration;
  18. use bip39::Mnemonic;
  19. use cashu::{MeltRequest, PreMintSecrets};
  20. use cdk::amount::{Amount, SplitTarget};
  21. use cdk::nuts::nut00::ProofsMethods;
  22. use cdk::nuts::{CurrencyUnit, MeltQuoteState, NotificationPayload, State};
  23. use cdk::wallet::{HttpClient, MintConnector, Wallet};
  24. use cdk_integration_tests::{create_invoice_for_env, get_mint_url_from_env, pay_if_regtest};
  25. use cdk_sqlite::wallet::memory;
  26. use futures::{SinkExt, StreamExt};
  27. use lightning_invoice::Bolt11Invoice;
  28. use serde_json::json;
  29. use tokio::time::timeout;
  30. use tokio_tungstenite::connect_async;
  31. use tokio_tungstenite::tungstenite::protocol::Message;
  32. // Helper function to get temp directory from environment or fallback
  33. fn get_test_temp_dir() -> PathBuf {
  34. match env::var("CDK_ITESTS_DIR") {
  35. Ok(dir) => PathBuf::from(dir),
  36. Err(_) => panic!("Unknown test dir"),
  37. }
  38. }
  39. async fn get_notification<T: StreamExt<Item = Result<Message, E>> + Unpin, E: Debug>(
  40. reader: &mut T,
  41. timeout_to_wait: Duration,
  42. ) -> (String, NotificationPayload<String>) {
  43. let msg = timeout(timeout_to_wait, reader.next())
  44. .await
  45. .expect("timeout")
  46. .unwrap()
  47. .unwrap();
  48. let mut response: serde_json::Value =
  49. serde_json::from_str(msg.to_text().unwrap()).expect("valid json");
  50. let mut params_raw = response
  51. .as_object_mut()
  52. .expect("object")
  53. .remove("params")
  54. .expect("valid params");
  55. let params_map = params_raw.as_object_mut().expect("params is object");
  56. (
  57. params_map
  58. .remove("subId")
  59. .unwrap()
  60. .as_str()
  61. .unwrap()
  62. .to_string(),
  63. serde_json::from_value(params_map.remove("payload").unwrap()).unwrap(),
  64. )
  65. }
  66. /// Tests a complete mint-melt round trip with WebSocket notifications
  67. ///
  68. /// This test verifies the full lifecycle of tokens:
  69. /// 1. Creates a mint quote and pays the invoice
  70. /// 2. Mints tokens and verifies the correct amount
  71. /// 3. Creates a melt quote to spend tokens
  72. /// 4. Subscribes to WebSocket notifications for the melt process
  73. /// 5. Executes the melt and verifies the payment was successful
  74. /// 6. Validates all WebSocket notifications received during the process
  75. ///
  76. /// This ensures the entire mint-melt flow works correctly and that
  77. /// WebSocket notifications are properly sent at each state transition.
  78. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  79. async fn test_happy_mint_melt_round_trip() {
  80. let wallet = Wallet::new(
  81. &get_mint_url_from_env(),
  82. CurrencyUnit::Sat,
  83. Arc::new(memory::empty().await.unwrap()),
  84. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  85. None,
  86. )
  87. .expect("failed to create new wallet");
  88. let (ws_stream, _) = connect_async(format!(
  89. "{}/v1/ws",
  90. get_mint_url_from_env().replace("http", "ws")
  91. ))
  92. .await
  93. .expect("Failed to connect");
  94. let (mut write, mut reader) = ws_stream.split();
  95. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  96. let invoice = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
  97. pay_if_regtest(&get_test_temp_dir(), &invoice)
  98. .await
  99. .unwrap();
  100. let proofs = wallet
  101. .wait_and_mint_quote(
  102. mint_quote.clone(),
  103. SplitTarget::default(),
  104. None,
  105. tokio::time::Duration::from_secs(60),
  106. )
  107. .await
  108. .expect("payment");
  109. let mint_amount = proofs.total_amount().unwrap();
  110. assert!(mint_amount == 100.into());
  111. let invoice = create_invoice_for_env(Some(50)).await.unwrap();
  112. let melt = wallet.melt_quote(invoice, None).await.unwrap();
  113. write
  114. .send(Message::Text(
  115. serde_json::to_string(&json!({
  116. "jsonrpc": "2.0",
  117. "id": 2,
  118. "method": "subscribe",
  119. "params": {
  120. "kind": "bolt11_melt_quote",
  121. "filters": [
  122. melt.id.clone(),
  123. ],
  124. "subId": "test-sub",
  125. }
  126. }))
  127. .unwrap()
  128. .into(),
  129. ))
  130. .await
  131. .unwrap();
  132. // Parse both JSON strings to objects and compare them instead of comparing strings directly
  133. let binding = reader.next().await.unwrap().unwrap();
  134. let response_str = binding.to_text().unwrap();
  135. let response_json: serde_json::Value =
  136. serde_json::from_str(response_str).expect("Valid JSON response");
  137. let expected_json: serde_json::Value = serde_json::from_str(
  138. r#"{"jsonrpc":"2.0","result":{"status":"OK","subId":"test-sub"},"id":2}"#,
  139. )
  140. .expect("Valid JSON expected");
  141. assert_eq!(response_json, expected_json);
  142. let mut metadata = HashMap::new();
  143. metadata.insert("test".to_string(), "value".to_string());
  144. let melt_response = wallet
  145. .melt_with_metadata(&melt.id, metadata.clone())
  146. .await
  147. .unwrap();
  148. assert!(melt_response.preimage.is_some());
  149. assert_eq!(melt_response.state, MeltQuoteState::Paid);
  150. let txs = wallet.list_transactions(None).await.unwrap();
  151. let tx = txs
  152. .into_iter()
  153. .find(|tx| tx.quote_id == Some(melt.id.clone()))
  154. .unwrap();
  155. assert_eq!(tx.amount, melt.amount);
  156. assert_eq!(tx.metadata, metadata);
  157. let (sub_id, payload) = get_notification(&mut reader, Duration::from_millis(15000)).await;
  158. // first message is the current state
  159. assert_eq!("test-sub", sub_id);
  160. let payload = match payload {
  161. NotificationPayload::MeltQuoteBolt11Response(melt) => melt,
  162. _ => panic!("Wrong payload"),
  163. };
  164. // assert_eq!(payload.amount + payload.fee_reserve, 50.into());
  165. assert_eq!(payload.quote.to_string(), melt.id);
  166. assert_eq!(payload.state, MeltQuoteState::Unpaid);
  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.quote.to_string(), melt.id);
  175. assert_eq!(payload.state, MeltQuoteState::Pending);
  176. // get current state
  177. let (sub_id, payload) = get_notification(&mut reader, Duration::from_millis(15000)).await;
  178. assert_eq!("test-sub", sub_id);
  179. let payload = match payload {
  180. NotificationPayload::MeltQuoteBolt11Response(melt) => melt,
  181. _ => panic!("Wrong payload"),
  182. };
  183. assert_eq!(payload.amount, 50.into());
  184. assert_eq!(payload.quote.to_string(), melt.id);
  185. assert_eq!(payload.state, MeltQuoteState::Paid);
  186. }
  187. /// Tests basic minting functionality with payment verification
  188. ///
  189. /// This test focuses on the core minting process:
  190. /// 1. Creates a mint quote for a specific amount (100 sats)
  191. /// 2. Verifies the quote has the correct amount
  192. /// 3. Pays the invoice (or simulates payment in non-regtest environments)
  193. /// 4. Waits for the mint to recognize the payment
  194. /// 5. Mints tokens and verifies the correct amount was received
  195. ///
  196. /// This ensures the basic minting flow works correctly from quote to token issuance.
  197. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  198. async fn test_happy_mint() {
  199. let wallet = Wallet::new(
  200. &get_mint_url_from_env(),
  201. CurrencyUnit::Sat,
  202. Arc::new(memory::empty().await.unwrap()),
  203. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  204. None,
  205. )
  206. .expect("failed to create new wallet");
  207. let mint_amount = Amount::from(100);
  208. let mint_quote = wallet.mint_quote(mint_amount, None).await.unwrap();
  209. assert_eq!(mint_quote.amount, Some(mint_amount));
  210. let invoice = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
  211. pay_if_regtest(&get_test_temp_dir(), &invoice)
  212. .await
  213. .unwrap();
  214. let proofs = wallet
  215. .wait_and_mint_quote(
  216. mint_quote.clone(),
  217. SplitTarget::default(),
  218. None,
  219. tokio::time::Duration::from_secs(60),
  220. )
  221. .await
  222. .expect("payment");
  223. let mint_amount = proofs.total_amount().unwrap();
  224. assert!(mint_amount == 100.into());
  225. }
  226. /// Tests wallet restoration and proof state verification
  227. ///
  228. /// This test verifies the wallet restoration process:
  229. /// 1. Creates a wallet with a specific seed and mints tokens
  230. /// 2. Verifies the wallet has the expected balance
  231. /// 3. Creates a new wallet instance with the same seed but empty storage
  232. /// 4. Confirms the new wallet starts with zero balance
  233. /// 5. Restores the wallet state from the mint
  234. /// 6. Swaps the proofs to ensure they're valid
  235. /// 7. Verifies the restored wallet has the correct balance
  236. /// 8. Checks that the original proofs are now marked as spent
  237. ///
  238. /// This ensures wallet restoration works correctly and that
  239. /// the mint properly tracks spent proofs across wallet instances.
  240. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  241. async fn test_restore() {
  242. let seed = Mnemonic::generate(12).unwrap().to_seed_normalized("");
  243. let wallet = Wallet::new(
  244. &get_mint_url_from_env(),
  245. CurrencyUnit::Sat,
  246. Arc::new(memory::empty().await.unwrap()),
  247. seed,
  248. None,
  249. )
  250. .expect("failed to create new wallet");
  251. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  252. let invoice = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
  253. pay_if_regtest(&get_test_temp_dir(), &invoice)
  254. .await
  255. .unwrap();
  256. let _proofs = wallet
  257. .wait_and_mint_quote(
  258. mint_quote.clone(),
  259. SplitTarget::default(),
  260. None,
  261. tokio::time::Duration::from_secs(60),
  262. )
  263. .await
  264. .expect("payment");
  265. assert_eq!(wallet.total_balance().await.unwrap(), 100.into());
  266. let wallet_2 = Wallet::new(
  267. &get_mint_url_from_env(),
  268. CurrencyUnit::Sat,
  269. Arc::new(memory::empty().await.unwrap()),
  270. seed,
  271. None,
  272. )
  273. .expect("failed to create new wallet");
  274. assert_eq!(wallet_2.total_balance().await.unwrap(), 0.into());
  275. let restored = wallet_2.restore().await.unwrap();
  276. let proofs = wallet_2.get_unspent_proofs().await.unwrap();
  277. assert!(!proofs.is_empty());
  278. let expected_fee = wallet.get_proofs_fee(&proofs).await.unwrap();
  279. wallet_2
  280. .swap(None, SplitTarget::default(), proofs, None, false)
  281. .await
  282. .unwrap();
  283. assert_eq!(restored, 100.into());
  284. // Since we have to do a swap we expect to restore amount - fee
  285. assert_eq!(
  286. wallet_2.total_balance().await.unwrap(),
  287. Amount::from(100) - expected_fee
  288. );
  289. let proofs = wallet.get_unspent_proofs().await.unwrap();
  290. let states = wallet.check_proofs_spent(proofs).await.unwrap();
  291. for state in states {
  292. if state.state != State::Spent {
  293. panic!("All proofs should be spent");
  294. }
  295. }
  296. }
  297. /// Tests that change outputs in a melt quote are correctly handled
  298. ///
  299. /// This test verifies the following workflow:
  300. /// 1. Mint 100 sats of tokens
  301. /// 2. Create a melt quote for 9 sats (which requires 100 sats input with 91 sats change)
  302. /// 3. Manually construct a melt request with proofs and blinded messages for change
  303. /// 4. Verify that the change proofs in the response match what's reported by the quote status
  304. ///
  305. /// This ensures the mint correctly processes change outputs during melting operations
  306. /// and that the wallet can properly verify the change amounts match expectations.
  307. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  308. async fn test_fake_melt_change_in_quote() {
  309. let wallet = Wallet::new(
  310. &get_mint_url_from_env(),
  311. CurrencyUnit::Sat,
  312. Arc::new(memory::empty().await.unwrap()),
  313. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  314. None,
  315. )
  316. .expect("failed to create new wallet");
  317. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  318. let bolt11 = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
  319. pay_if_regtest(&get_test_temp_dir(), &bolt11).await.unwrap();
  320. let _proofs = wallet
  321. .wait_and_mint_quote(
  322. mint_quote.clone(),
  323. SplitTarget::default(),
  324. None,
  325. tokio::time::Duration::from_secs(60),
  326. )
  327. .await
  328. .expect("payment");
  329. let invoice = create_invoice_for_env(Some(9)).await.unwrap();
  330. let proofs = wallet.get_unspent_proofs().await.unwrap();
  331. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await.unwrap();
  332. let keyset = wallet.fetch_active_keyset().await.unwrap();
  333. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  334. let premint_secrets = PreMintSecrets::random(
  335. keyset.id,
  336. 100.into(),
  337. &SplitTarget::default(),
  338. &fee_and_amounts,
  339. )
  340. .unwrap();
  341. let client = HttpClient::new(get_mint_url_from_env().parse().unwrap(), None);
  342. let melt_request = MeltRequest::new(
  343. melt_quote.id.clone(),
  344. proofs.clone(),
  345. Some(premint_secrets.blinded_messages()),
  346. );
  347. let melt_response = client.post_melt(melt_request).await.unwrap();
  348. assert!(melt_response.change.is_some());
  349. let check = wallet.melt_quote_status(&melt_quote.id).await.unwrap();
  350. let mut melt_change = melt_response.change.unwrap();
  351. melt_change.sort_by(|a, b| a.amount.cmp(&b.amount));
  352. let mut check = check.change.unwrap();
  353. check.sort_by(|a, b| a.amount.cmp(&b.amount));
  354. assert_eq!(melt_change, check);
  355. }
  356. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  357. async fn test_pay_invoice_twice() {
  358. let ln_backend = match env::var("LN_BACKEND") {
  359. Ok(val) => Some(val),
  360. Err(_) => env::var("CDK_MINTD_LN_BACKEND").ok(),
  361. };
  362. if ln_backend.map(|ln| ln.to_uppercase()) == Some("FAKEWALLET".to_string()) {
  363. // We can only perform this test on regtest backends as fake wallet just marks the quote as paid
  364. return;
  365. }
  366. let wallet = Wallet::new(
  367. &get_mint_url_from_env(),
  368. CurrencyUnit::Sat,
  369. Arc::new(memory::empty().await.unwrap()),
  370. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  371. None,
  372. )
  373. .expect("failed to create new wallet");
  374. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  375. pay_if_regtest(&get_test_temp_dir(), &mint_quote.request.parse().unwrap())
  376. .await
  377. .unwrap();
  378. let proofs = wallet
  379. .wait_and_mint_quote(
  380. mint_quote.clone(),
  381. SplitTarget::default(),
  382. None,
  383. tokio::time::Duration::from_secs(60),
  384. )
  385. .await
  386. .expect("payment");
  387. let mint_amount = proofs.total_amount().unwrap();
  388. assert_eq!(mint_amount, 100.into());
  389. let invoice = create_invoice_for_env(Some(25)).await.unwrap();
  390. let melt_quote = wallet.melt_quote(invoice.clone(), None).await.unwrap();
  391. let melt = wallet.melt(&melt_quote.id).await.unwrap();
  392. let melt_two = wallet.melt_quote(invoice, None).await;
  393. match melt_two {
  394. Err(err) => match err {
  395. cdk::Error::RequestAlreadyPaid => (),
  396. err => {
  397. if !err.to_string().contains("Duplicate entry") {
  398. panic!("Wrong invoice already paid: {}", err.to_string());
  399. }
  400. }
  401. },
  402. Ok(_) => {
  403. panic!("Should not have allowed second payment");
  404. }
  405. }
  406. let balance = wallet.total_balance().await.unwrap();
  407. assert_eq!(balance, (Amount::from(100) - melt.fee_paid - melt.amount));
  408. }