happy_path_mint_wallet.rs 15 KB

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