happy_path_mint_wallet.rs 16 KB

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