happy_path_mint_wallet.rs 15 KB

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