regtest.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. //! Regtest Integration Tests
  2. //!
  3. //! This file contains tests that run against actual Lightning Network nodes in regtest mode.
  4. //! These tests require a local development environment with LND nodes configured for regtest.
  5. //!
  6. //! Test Environment Setup:
  7. //! - Uses actual LND nodes connected to a regtest Bitcoin network
  8. //! - Tests real Lightning payment flows including invoice creation and payment
  9. //! - Verifies mint behavior with actual Lightning Network interactions
  10. //!
  11. //! Running Tests:
  12. //! - Requires CDK_TEST_REGTEST=1 environment variable to be set
  13. //! - Requires properly configured LND nodes with TLS certificates and macaroons
  14. //! - Uses real Bitcoin transactions in regtest mode
  15. use std::sync::Arc;
  16. use std::time::Duration;
  17. use bip39::Mnemonic;
  18. use cashu::ProofsMethods;
  19. use cdk::amount::{Amount, SplitTarget};
  20. use cdk::nuts::{
  21. CurrencyUnit, MeltOptions, MeltQuoteState, MintQuoteState, MintRequest, Mpp,
  22. NotificationPayload, PreMintSecrets,
  23. };
  24. use cdk::wallet::{HttpClient, MintConnector, Wallet, WalletSubscription};
  25. use cdk_integration_tests::{get_mint_url_from_env, get_second_mint_url_from_env, get_test_client};
  26. use cdk_sqlite::wallet::{self, memory};
  27. use futures::join;
  28. use tokio::time::timeout;
  29. const LDK_URL: &str = "http://127.0.0.1:8089";
  30. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  31. async fn test_internal_payment() {
  32. let ln_client = get_test_client().await;
  33. let wallet = Wallet::new(
  34. &get_mint_url_from_env(),
  35. CurrencyUnit::Sat,
  36. Arc::new(memory::empty().await.unwrap()),
  37. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  38. None,
  39. )
  40. .expect("failed to create new wallet");
  41. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  42. ln_client
  43. .pay_invoice(mint_quote.request.clone())
  44. .await
  45. .expect("failed to pay invoice");
  46. wallet
  47. .wait_for_payment(&mint_quote, Duration::from_secs(60))
  48. .await
  49. .unwrap();
  50. let _mint_amount = wallet
  51. .mint(&mint_quote.id, SplitTarget::default(), None)
  52. .await
  53. .unwrap();
  54. assert!(wallet.total_balance().await.unwrap() == 100.into());
  55. let wallet_2 = Wallet::new(
  56. &get_mint_url_from_env(),
  57. CurrencyUnit::Sat,
  58. Arc::new(memory::empty().await.unwrap()),
  59. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  60. None,
  61. )
  62. .expect("failed to create new wallet");
  63. let mint_quote = wallet_2.mint_quote(10.into(), None).await.unwrap();
  64. let melt = wallet
  65. .melt_quote(mint_quote.request.clone(), None)
  66. .await
  67. .unwrap();
  68. assert_eq!(melt.amount, 10.into());
  69. let _melted = wallet.melt(&melt.id).await.unwrap();
  70. wallet_2
  71. .wait_for_payment(&mint_quote, Duration::from_secs(60))
  72. .await
  73. .unwrap();
  74. let _wallet_2_mint = wallet_2
  75. .mint(&mint_quote.id, SplitTarget::default(), None)
  76. .await
  77. .unwrap();
  78. // let check_paid = match get_mint_port("0") {
  79. // 8085 => {
  80. // let cln_one_dir = get_cln_dir(&get_temp_dir(), "one");
  81. // let cln_client = ClnClient::new(cln_one_dir.clone(), None).await.unwrap();
  82. // let payment_hash = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
  83. // cln_client
  84. // .check_incoming_payment_status(&payment_hash.payment_hash().to_string())
  85. // .await
  86. // .expect("Could not check invoice")
  87. // }
  88. // 8087 => {
  89. // let lnd_two_dir = get_lnd_dir(&get_temp_dir(), "two");
  90. // let lnd_client = LndClient::new(
  91. // format!("https://{}", LND_TWO_RPC_ADDR),
  92. // get_lnd_cert_file_path(&lnd_two_dir),
  93. // get_lnd_macaroon_path(&lnd_two_dir),
  94. // )
  95. // .await
  96. // .unwrap();
  97. // let payment_hash = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
  98. // lnd_client
  99. // .check_incoming_payment_status(&payment_hash.payment_hash().to_string())
  100. // .await
  101. // .expect("Could not check invoice")
  102. // }
  103. // _ => panic!("Unknown mint port"),
  104. // };
  105. // match check_paid {
  106. // InvoiceStatus::Unpaid => (),
  107. // _ => {
  108. // panic!("Invoice has incorrect status: {:?}", check_paid);
  109. // }
  110. // }
  111. let wallet_2_balance = wallet_2.total_balance().await.unwrap();
  112. assert!(wallet_2_balance == 10.into());
  113. let wallet_1_balance = wallet.total_balance().await.unwrap();
  114. assert!(wallet_1_balance == 90.into());
  115. }
  116. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  117. async fn test_websocket_connection() {
  118. let wallet = Wallet::new(
  119. &get_mint_url_from_env(),
  120. CurrencyUnit::Sat,
  121. Arc::new(wallet::memory::empty().await.unwrap()),
  122. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  123. None,
  124. )
  125. .expect("failed to create new wallet");
  126. // Create a small mint quote to test notifications
  127. let mint_quote = wallet.mint_quote(10.into(), None).await.unwrap();
  128. // Subscribe to notifications for this quote
  129. let mut subscription = wallet
  130. .subscribe(WalletSubscription::Bolt11MintQuoteState(vec![mint_quote
  131. .id
  132. .clone()]))
  133. .await;
  134. // First check we get the unpaid state
  135. let msg = timeout(Duration::from_secs(10), subscription.recv())
  136. .await
  137. .expect("timeout waiting for unpaid notification")
  138. .expect("No paid notification received");
  139. match msg {
  140. NotificationPayload::MintQuoteBolt11Response(response) => {
  141. assert_eq!(response.quote.to_string(), mint_quote.id);
  142. assert_eq!(response.state, MintQuoteState::Unpaid);
  143. }
  144. _ => panic!("Unexpected notification type"),
  145. }
  146. let ln_client = get_test_client().await;
  147. ln_client
  148. .pay_invoice(mint_quote.request)
  149. .await
  150. .expect("failed to pay invoice");
  151. // Wait for paid notification with 10 second timeout
  152. let msg = timeout(Duration::from_secs(10), subscription.recv())
  153. .await
  154. .expect("timeout waiting for paid notification")
  155. .expect("No paid notification received");
  156. match msg {
  157. NotificationPayload::MintQuoteBolt11Response(response) => {
  158. assert_eq!(response.quote.to_string(), mint_quote.id);
  159. assert_eq!(response.state, MintQuoteState::Paid);
  160. }
  161. _ => panic!("Unexpected notification type"),
  162. }
  163. }
  164. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  165. async fn test_multimint_melt() {
  166. if get_mint_url_from_env() == LDK_URL {
  167. return;
  168. }
  169. let ln_client = get_test_client().await;
  170. let db = Arc::new(memory::empty().await.unwrap());
  171. let wallet1 = Wallet::new(
  172. &get_mint_url_from_env(),
  173. CurrencyUnit::Sat,
  174. db,
  175. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  176. None,
  177. )
  178. .expect("failed to create new wallet");
  179. let db = Arc::new(memory::empty().await.unwrap());
  180. let wallet2 = Wallet::new(
  181. &get_second_mint_url_from_env(),
  182. CurrencyUnit::Sat,
  183. db,
  184. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  185. None,
  186. )
  187. .expect("failed to create new wallet");
  188. let mint_amount = Amount::from(100);
  189. // Fund the wallets
  190. let quote = wallet1.mint_quote(mint_amount, None).await.unwrap();
  191. ln_client
  192. .pay_invoice(quote.request.clone())
  193. .await
  194. .expect("failed to pay invoice");
  195. wallet1
  196. .wait_for_payment(&quote, Duration::from_secs(60))
  197. .await
  198. .unwrap();
  199. wallet1
  200. .mint(&quote.id, SplitTarget::default(), None)
  201. .await
  202. .unwrap();
  203. let quote = wallet2.mint_quote(mint_amount, None).await.unwrap();
  204. ln_client
  205. .pay_invoice(quote.request.clone())
  206. .await
  207. .expect("failed to pay invoice");
  208. wallet2
  209. .wait_for_payment(&quote, Duration::from_secs(60))
  210. .await
  211. .unwrap();
  212. wallet2
  213. .mint(&quote.id, SplitTarget::default(), None)
  214. .await
  215. .unwrap();
  216. // Get an invoice
  217. let invoice = ln_client.create_invoice(Some(50)).await.unwrap();
  218. // Get multi-part melt quotes
  219. let melt_options = MeltOptions::Mpp {
  220. mpp: Mpp {
  221. amount: Amount::from(25000),
  222. },
  223. };
  224. let quote_1 = wallet1
  225. .melt_quote(invoice.clone(), Some(melt_options))
  226. .await
  227. .expect("Could not get melt quote");
  228. let quote_2 = wallet2
  229. .melt_quote(invoice.clone(), Some(melt_options))
  230. .await
  231. .expect("Could not get melt quote");
  232. // Multimint pay invoice
  233. let result1 = wallet1.melt(&quote_1.id);
  234. let result2 = wallet2.melt(&quote_2.id);
  235. let result = join!(result1, result2);
  236. // Unpack results
  237. let result1 = result.0.unwrap();
  238. let result2 = result.1.unwrap();
  239. // Check
  240. assert!(result1.state == result2.state);
  241. assert!(result1.state == MeltQuoteState::Paid);
  242. }
  243. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  244. async fn test_cached_mint() {
  245. let ln_client = get_test_client().await;
  246. let wallet = Wallet::new(
  247. &get_mint_url_from_env(),
  248. CurrencyUnit::Sat,
  249. Arc::new(memory::empty().await.unwrap()),
  250. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  251. None,
  252. )
  253. .expect("failed to create new wallet");
  254. let mint_amount = Amount::from(100);
  255. let quote = wallet.mint_quote(mint_amount, None).await.unwrap();
  256. ln_client
  257. .pay_invoice(quote.request.clone())
  258. .await
  259. .expect("failed to pay invoice");
  260. wallet
  261. .wait_for_payment(&quote, Duration::from_secs(60))
  262. .await
  263. .unwrap();
  264. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  265. let http_client = HttpClient::new(get_mint_url_from_env().parse().unwrap(), None);
  266. let premint_secrets =
  267. PreMintSecrets::random(active_keyset_id, 100.into(), &SplitTarget::default()).unwrap();
  268. let mut request = MintRequest {
  269. quote: quote.id,
  270. outputs: premint_secrets.blinded_messages(),
  271. signature: None,
  272. };
  273. let secret_key = quote.secret_key;
  274. request
  275. .sign(secret_key.expect("Secret key on quote"))
  276. .unwrap();
  277. let response = http_client.post_mint(request.clone()).await.unwrap();
  278. let response1 = http_client.post_mint(request).await.unwrap();
  279. assert!(response == response1);
  280. }
  281. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  282. async fn test_regtest_melt_amountless() {
  283. let ln_client = get_test_client().await;
  284. let wallet = Wallet::new(
  285. &get_mint_url_from_env(),
  286. CurrencyUnit::Sat,
  287. Arc::new(memory::empty().await.unwrap()),
  288. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  289. None,
  290. )
  291. .expect("failed to create new wallet");
  292. let mint_amount = Amount::from(100);
  293. let mint_quote = wallet.mint_quote(mint_amount, None).await.unwrap();
  294. assert_eq!(mint_quote.amount, Some(mint_amount));
  295. ln_client
  296. .pay_invoice(mint_quote.request)
  297. .await
  298. .expect("failed to pay invoice");
  299. let proofs = wallet
  300. .mint(&mint_quote.id, SplitTarget::default(), None)
  301. .await
  302. .unwrap();
  303. let amount = proofs.total_amount().unwrap();
  304. assert!(mint_amount == amount);
  305. let invoice = ln_client.create_invoice(None).await.unwrap();
  306. let options = MeltOptions::new_amountless(5_000);
  307. let melt_quote = wallet
  308. .melt_quote(invoice.clone(), Some(options))
  309. .await
  310. .unwrap();
  311. let melt = wallet.melt(&melt_quote.id).await.unwrap();
  312. assert!(melt.amount == 5.into());
  313. }
  314. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  315. async fn test_attempt_to_mint_unpaid() {
  316. let wallet = Wallet::new(
  317. &get_mint_url_from_env(),
  318. CurrencyUnit::Sat,
  319. Arc::new(memory::empty().await.unwrap()),
  320. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  321. None,
  322. )
  323. .expect("failed to create new wallet");
  324. let mint_amount = Amount::from(100);
  325. let mint_quote = wallet.mint_quote(mint_amount, None).await.unwrap();
  326. assert_eq!(mint_quote.amount, Some(mint_amount));
  327. let proofs = wallet
  328. .mint(&mint_quote.id, SplitTarget::default(), None)
  329. .await;
  330. match proofs {
  331. Err(err) => {
  332. if !matches!(err, cdk::Error::UnpaidQuote) {
  333. panic!("Wrong error quote should be unpaid: {}", err);
  334. }
  335. }
  336. Ok(_) => {
  337. panic!("Minting should not be allowed");
  338. }
  339. }
  340. let mint_quote = wallet.mint_quote(mint_amount, None).await.unwrap();
  341. let state = wallet.mint_quote_state(&mint_quote.id).await.unwrap();
  342. assert!(state.state == MintQuoteState::Unpaid);
  343. let proofs = wallet
  344. .mint(&mint_quote.id, SplitTarget::default(), None)
  345. .await;
  346. match proofs {
  347. Err(err) => {
  348. if !matches!(err, cdk::Error::UnpaidQuote) {
  349. panic!("Wrong error quote should be unpaid: {}", err);
  350. }
  351. }
  352. Ok(_) => {
  353. panic!("Minting should not be allowed");
  354. }
  355. }
  356. }