happy_path_mint_wallet.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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::{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_fake_wallet::create_fake_invoice;
  24. use cdk_integration_tests::init_regtest::{get_lnd_dir, LND_RPC_ADDR};
  25. use cdk_integration_tests::{get_mint_url_from_env, wait_for_mint_to_be_paid};
  26. use cdk_sqlite::wallet::memory;
  27. use futures::{SinkExt, StreamExt};
  28. use lightning_invoice::Bolt11Invoice;
  29. use ln_regtest_rs::ln_client::{LightningClient, LndClient};
  30. use serde_json::json;
  31. use tokio::time::timeout;
  32. use tokio_tungstenite::connect_async;
  33. use tokio_tungstenite::tungstenite::protocol::Message;
  34. // This is the ln wallet we use to send/receive ln payements as the wallet
  35. async fn init_lnd_client() -> LndClient {
  36. let lnd_dir = get_lnd_dir("one");
  37. let cert_file = lnd_dir.join("tls.cert");
  38. let macaroon_file = lnd_dir.join("data/chain/bitcoin/regtest/admin.macaroon");
  39. LndClient::new(
  40. format!("https://{}", LND_RPC_ADDR),
  41. cert_file,
  42. macaroon_file,
  43. )
  44. .await
  45. .unwrap()
  46. }
  47. /// Pays a Bolt11Invoice if it's on the regtest network, otherwise returns Ok
  48. ///
  49. /// This is useful for tests that need to pay invoices in regtest mode but
  50. /// should be skipped in other environments.
  51. async fn pay_if_regtest(invoice: &Bolt11Invoice) -> Result<()> {
  52. // Check if the invoice is for the regtest network
  53. if invoice.network() == bitcoin::Network::Regtest {
  54. println!("Regtest invoice");
  55. let lnd_client = init_lnd_client().await;
  56. lnd_client.pay_invoice(invoice.to_string()).await?;
  57. Ok(())
  58. } else {
  59. // Not a regtest invoice, just return Ok
  60. Ok(())
  61. }
  62. }
  63. /// Determines if we're running in regtest mode based on environment variable
  64. ///
  65. /// Checks the CDK_TEST_REGTEST environment variable:
  66. /// - If set to "1", "true", or "yes" (case insensitive), returns true
  67. /// - Otherwise returns false
  68. fn is_regtest_env() -> bool {
  69. match env::var("CDK_TEST_REGTEST") {
  70. Ok(val) => {
  71. let val = val.to_lowercase();
  72. val == "1" || val == "true" || val == "yes"
  73. }
  74. Err(_) => false,
  75. }
  76. }
  77. /// Creates a real invoice if in regtest mode, otherwise returns a fake invoice
  78. ///
  79. /// Uses the is_regtest_env() function to determine whether to
  80. /// create a real regtest invoice or a fake one for testing.
  81. async fn create_invoice_for_env(amount_sat: Option<u64>) -> Result<String> {
  82. if is_regtest_env() {
  83. // In regtest mode, create a real invoice
  84. let lnd_client = init_lnd_client().await;
  85. lnd_client
  86. .create_invoice(amount_sat)
  87. .await
  88. .map_err(|e| anyhow!("Failed to create regtest invoice: {}", e))
  89. } else {
  90. // Not in regtest mode, create a fake invoice
  91. let fake_invoice = create_fake_invoice(
  92. amount_sat.expect("Amount must be defined") * 1_000,
  93. "".to_string(),
  94. );
  95. Ok(fake_invoice.to_string())
  96. }
  97. }
  98. async fn get_notification<T: StreamExt<Item = Result<Message, E>> + Unpin, E: Debug>(
  99. reader: &mut T,
  100. timeout_to_wait: Duration,
  101. ) -> (String, NotificationPayload<String>) {
  102. let msg = timeout(timeout_to_wait, reader.next())
  103. .await
  104. .expect("timeout")
  105. .unwrap()
  106. .unwrap();
  107. let mut response: serde_json::Value =
  108. serde_json::from_str(msg.to_text().unwrap()).expect("valid json");
  109. let mut params_raw = response
  110. .as_object_mut()
  111. .expect("object")
  112. .remove("params")
  113. .expect("valid params");
  114. let params_map = params_raw.as_object_mut().expect("params is object");
  115. (
  116. params_map
  117. .remove("subId")
  118. .unwrap()
  119. .as_str()
  120. .unwrap()
  121. .to_string(),
  122. serde_json::from_value(params_map.remove("payload").unwrap()).unwrap(),
  123. )
  124. }
  125. /// Tests a complete mint-melt round trip with WebSocket notifications
  126. ///
  127. /// This test verifies the full lifecycle of tokens:
  128. /// 1. Creates a mint quote and pays the invoice
  129. /// 2. Mints tokens and verifies the correct amount
  130. /// 3. Creates a melt quote to spend tokens
  131. /// 4. Subscribes to WebSocket notifications for the melt process
  132. /// 5. Executes the melt and verifies the payment was successful
  133. /// 6. Validates all WebSocket notifications received during the process
  134. ///
  135. /// This ensures the entire mint-melt flow works correctly and that
  136. /// WebSocket notifications are properly sent at each state transition.
  137. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  138. async fn test_happy_mint_melt_round_trip() -> Result<()> {
  139. let wallet = Wallet::new(
  140. &get_mint_url_from_env(),
  141. CurrencyUnit::Sat,
  142. Arc::new(memory::empty().await?),
  143. &Mnemonic::generate(12)?.to_seed_normalized(""),
  144. None,
  145. )?;
  146. let (ws_stream, _) = connect_async(format!(
  147. "{}/v1/ws",
  148. get_mint_url_from_env().replace("http", "ws")
  149. ))
  150. .await
  151. .expect("Failed to connect");
  152. let (mut write, mut reader) = ws_stream.split();
  153. let mint_quote = wallet.mint_quote(100.into(), None).await?;
  154. let invoice = Bolt11Invoice::from_str(&mint_quote.request)?;
  155. pay_if_regtest(&invoice).await.unwrap();
  156. let proofs = wallet
  157. .mint(&mint_quote.id, SplitTarget::default(), None)
  158. .await?;
  159. let mint_amount = proofs.total_amount()?;
  160. assert!(mint_amount == 100.into());
  161. let invoice = create_invoice_for_env(Some(50)).await.unwrap();
  162. let melt = wallet.melt_quote(invoice, None).await?;
  163. write
  164. .send(Message::Text(
  165. serde_json::to_string(&json!({
  166. "jsonrpc": "2.0",
  167. "id": 2,
  168. "method": "subscribe",
  169. "params": {
  170. "kind": "bolt11_melt_quote",
  171. "filters": [
  172. melt.id.clone(),
  173. ],
  174. "subId": "test-sub",
  175. }
  176. }))?
  177. .into(),
  178. ))
  179. .await?;
  180. assert_eq!(
  181. reader
  182. .next()
  183. .await
  184. .unwrap()
  185. .unwrap()
  186. .to_text()
  187. .unwrap()
  188. .replace(char::is_whitespace, ""),
  189. r#"{"jsonrpc":"2.0","result":{"status":"OK","subId":"test-sub"},"id":2}"#
  190. );
  191. let melt_response = wallet.melt(&melt.id).await.unwrap();
  192. assert!(melt_response.preimage.is_some());
  193. assert!(melt_response.state == MeltQuoteState::Paid);
  194. let (sub_id, payload) = get_notification(&mut reader, Duration::from_millis(15000)).await;
  195. // first message is the current state
  196. assert_eq!("test-sub", sub_id);
  197. let payload = match payload {
  198. NotificationPayload::MeltQuoteBolt11Response(melt) => melt,
  199. _ => panic!("Wrong payload"),
  200. };
  201. // assert_eq!(payload.amount + payload.fee_reserve, 50.into());
  202. assert_eq!(payload.quote.to_string(), melt.id);
  203. assert_eq!(payload.state, MeltQuoteState::Unpaid);
  204. // get current state
  205. let (sub_id, payload) = get_notification(&mut reader, Duration::from_millis(15000)).await;
  206. assert_eq!("test-sub", sub_id);
  207. let payload = match payload {
  208. NotificationPayload::MeltQuoteBolt11Response(melt) => melt,
  209. _ => panic!("Wrong payload"),
  210. };
  211. assert_eq!(payload.quote.to_string(), melt.id);
  212. assert_eq!(payload.state, MeltQuoteState::Pending);
  213. // get current state
  214. let (sub_id, payload) = get_notification(&mut reader, Duration::from_millis(15000)).await;
  215. assert_eq!("test-sub", sub_id);
  216. let payload = match payload {
  217. NotificationPayload::MeltQuoteBolt11Response(melt) => melt,
  218. _ => panic!("Wrong payload"),
  219. };
  220. assert_eq!(payload.amount, 50.into());
  221. assert_eq!(payload.quote.to_string(), melt.id);
  222. assert_eq!(payload.state, MeltQuoteState::Paid);
  223. Ok(())
  224. }
  225. /// Tests basic minting functionality with payment verification
  226. ///
  227. /// This test focuses on the core minting process:
  228. /// 1. Creates a mint quote for a specific amount (100 sats)
  229. /// 2. Verifies the quote has the correct amount
  230. /// 3. Pays the invoice (or simulates payment in non-regtest environments)
  231. /// 4. Waits for the mint to recognize the payment
  232. /// 5. Mints tokens and verifies the correct amount was received
  233. ///
  234. /// This ensures the basic minting flow works correctly from quote to token issuance.
  235. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  236. async fn test_happy_mint_melt() -> Result<()> {
  237. let wallet = Wallet::new(
  238. &get_mint_url_from_env(),
  239. CurrencyUnit::Sat,
  240. Arc::new(memory::empty().await?),
  241. &Mnemonic::generate(12)?.to_seed_normalized(""),
  242. None,
  243. )?;
  244. let mint_amount = Amount::from(100);
  245. let mint_quote = wallet.mint_quote(mint_amount, None).await?;
  246. assert_eq!(mint_quote.amount, mint_amount);
  247. let invoice = Bolt11Invoice::from_str(&mint_quote.request)?;
  248. pay_if_regtest(&invoice).await?;
  249. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  250. let proofs = wallet
  251. .mint(&mint_quote.id, SplitTarget::default(), None)
  252. .await?;
  253. let mint_amount = proofs.total_amount()?;
  254. assert!(mint_amount == 100.into());
  255. Ok(())
  256. }
  257. /// Tests wallet restoration and proof state verification
  258. ///
  259. /// This test verifies the wallet restoration process:
  260. /// 1. Creates a wallet with a specific seed and mints tokens
  261. /// 2. Verifies the wallet has the expected balance
  262. /// 3. Creates a new wallet instance with the same seed but empty storage
  263. /// 4. Confirms the new wallet starts with zero balance
  264. /// 5. Restores the wallet state from the mint
  265. /// 6. Swaps the proofs to ensure they're valid
  266. /// 7. Verifies the restored wallet has the correct balance
  267. /// 8. Checks that the original proofs are now marked as spent
  268. ///
  269. /// This ensures wallet restoration works correctly and that
  270. /// the mint properly tracks spent proofs across wallet instances.
  271. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  272. async fn test_restore() -> Result<()> {
  273. let seed = Mnemonic::generate(12)?.to_seed_normalized("");
  274. let wallet = Wallet::new(
  275. &get_mint_url_from_env(),
  276. CurrencyUnit::Sat,
  277. Arc::new(memory::empty().await?),
  278. &seed,
  279. None,
  280. )?;
  281. let mint_quote = wallet.mint_quote(100.into(), None).await?;
  282. let invoice = Bolt11Invoice::from_str(&mint_quote.request)?;
  283. pay_if_regtest(&invoice).await?;
  284. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  285. let _mint_amount = wallet
  286. .mint(&mint_quote.id, SplitTarget::default(), None)
  287. .await?;
  288. assert!(wallet.total_balance().await? == 100.into());
  289. let wallet_2 = Wallet::new(
  290. &get_mint_url_from_env(),
  291. CurrencyUnit::Sat,
  292. Arc::new(memory::empty().await?),
  293. &seed,
  294. None,
  295. )?;
  296. assert!(wallet_2.total_balance().await? == 0.into());
  297. let restored = wallet_2.restore().await?;
  298. let proofs = wallet_2.get_unspent_proofs().await?;
  299. wallet_2
  300. .swap(None, SplitTarget::default(), proofs, None, false)
  301. .await?;
  302. assert!(restored == 100.into());
  303. assert_eq!(wallet_2.total_balance().await?, 100.into());
  304. let proofs = wallet.get_unspent_proofs().await?;
  305. let states = wallet.check_proofs_spent(proofs).await?;
  306. for state in states {
  307. if state.state != State::Spent {
  308. bail!("All proofs should be spent");
  309. }
  310. }
  311. Ok(())
  312. }
  313. /// Tests that change outputs in a melt quote are correctly handled
  314. ///
  315. /// This test verifies the following workflow:
  316. /// 1. Mint 100 sats of tokens
  317. /// 2. Create a melt quote for 9 sats (which requires 100 sats input with 91 sats change)
  318. /// 3. Manually construct a melt request with proofs and blinded messages for change
  319. /// 4. Verify that the change proofs in the response match what's reported by the quote status
  320. ///
  321. /// This ensures the mint correctly processes change outputs during melting operations
  322. /// and that the wallet can properly verify the change amounts match expectations.
  323. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  324. async fn test_fake_melt_change_in_quote() -> Result<()> {
  325. let wallet = Wallet::new(
  326. &get_mint_url_from_env(),
  327. CurrencyUnit::Sat,
  328. Arc::new(memory::empty().await?),
  329. &Mnemonic::generate(12)?.to_seed_normalized(""),
  330. None,
  331. )?;
  332. let mint_quote = wallet.mint_quote(100.into(), None).await?;
  333. let bolt11 = Bolt11Invoice::from_str(&mint_quote.request)?;
  334. pay_if_regtest(&bolt11).await?;
  335. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  336. let _mint_amount = wallet
  337. .mint(&mint_quote.id, SplitTarget::default(), None)
  338. .await?;
  339. let invoice = create_invoice_for_env(Some(9)).await?;
  340. let proofs = wallet.get_unspent_proofs().await?;
  341. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await?;
  342. let keyset = wallet.get_active_mint_keyset().await?;
  343. let premint_secrets = PreMintSecrets::random(keyset.id, 100.into(), &SplitTarget::default())?;
  344. let client = HttpClient::new(get_mint_url_from_env().parse()?, None);
  345. let melt_request = MeltBolt11Request::new(
  346. melt_quote.id.clone(),
  347. proofs.clone(),
  348. Some(premint_secrets.blinded_messages()),
  349. );
  350. let melt_response = client.post_melt(melt_request).await?;
  351. assert!(melt_response.change.is_some());
  352. let check = wallet.melt_quote_status(&melt_quote.id).await?;
  353. let mut melt_change = melt_response.change.unwrap();
  354. melt_change.sort_by(|a, b| a.amount.cmp(&b.amount));
  355. let mut check = check.change.unwrap();
  356. check.sort_by(|a, b| a.amount.cmp(&b.amount));
  357. assert_eq!(melt_change, check);
  358. Ok(())
  359. }
  360. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  361. async fn test_pay_invoice_twice() -> Result<()> {
  362. let ln_backend = match env::var("LN_BACKEND") {
  363. Ok(val) => Some(val),
  364. Err(_) => env::var("CDK_MINTD_LN_BACKEND").ok(),
  365. };
  366. if ln_backend.map(|ln| ln.to_uppercase()) == Some("FAKEWALLET".to_string()) {
  367. // We can only preform this test on regtest backends as fake wallet just marks the quote as paid
  368. return Ok(());
  369. }
  370. let wallet = Wallet::new(
  371. &get_mint_url_from_env(),
  372. CurrencyUnit::Sat,
  373. Arc::new(memory::empty().await?),
  374. &Mnemonic::generate(12)?.to_seed_normalized(""),
  375. None,
  376. )?;
  377. let mint_quote = wallet.mint_quote(100.into(), None).await?;
  378. pay_if_regtest(&mint_quote.request.parse()?).await?;
  379. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  380. let proofs = wallet
  381. .mint(&mint_quote.id, SplitTarget::default(), None)
  382. .await?;
  383. let mint_amount = proofs.total_amount()?;
  384. assert_eq!(mint_amount, 100.into());
  385. let invoice = create_invoice_for_env(Some(25)).await?;
  386. let melt_quote = wallet.melt_quote(invoice.clone(), None).await?;
  387. let melt = wallet.melt(&melt_quote.id).await.unwrap();
  388. let melt_two = wallet.melt_quote(invoice, None).await?;
  389. let melt_two = wallet.melt(&melt_two.id).await;
  390. match melt_two {
  391. Err(err) => match err {
  392. cdk::Error::RequestAlreadyPaid => (),
  393. err => {
  394. bail!("Wrong invoice already paid: {}", err.to_string());
  395. }
  396. },
  397. Ok(_) => {
  398. bail!("Should not have allowed second payment");
  399. }
  400. }
  401. let balance = wallet.total_balance().await?;
  402. assert_eq!(balance, (Amount::from(100) - melt.fee_paid - melt.amount));
  403. Ok(())
  404. }