happy_path_mint_wallet.rs 14 KB

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