happy_path_mint_wallet.rs 15 KB

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