regtest.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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::env;
  16. use std::path::PathBuf;
  17. use std::sync::Arc;
  18. use std::time::Duration;
  19. use bip39::Mnemonic;
  20. use cashu::ProofsMethods;
  21. use cdk::amount::{Amount, SplitTarget};
  22. use cdk::nuts::{
  23. CurrencyUnit, MeltOptions, MeltQuoteState, MintQuoteState, MintRequest, Mpp,
  24. NotificationPayload, PreMintSecrets,
  25. };
  26. use cdk::wallet::{HttpClient, MintConnector, Wallet, WalletSubscription};
  27. use cdk_integration_tests::init_regtest::{get_lnd_dir, LND_RPC_ADDR};
  28. use cdk_integration_tests::{get_mint_url_from_env, get_second_mint_url_from_env};
  29. use cdk_sqlite::wallet::{self, memory};
  30. use futures::join;
  31. use ln_regtest_rs::ln_client::{LightningClient, LndClient};
  32. use tokio::time::timeout;
  33. // This is the ln wallet we use to send/receive ln payements as the wallet
  34. async fn init_lnd_client() -> LndClient {
  35. // Try to get the temp directory from environment variable first (from .env file)
  36. let temp_dir = match env::var("CDK_ITESTS_DIR") {
  37. Ok(dir) => {
  38. let path = PathBuf::from(dir);
  39. println!("Using temp directory from CDK_ITESTS_DIR: {:?}", path);
  40. path
  41. }
  42. Err(_) => {
  43. panic!("Unknown temp dir");
  44. }
  45. };
  46. // The LND mint uses the second LND node (LND_TWO_RPC_ADDR = localhost:10010)
  47. let lnd_dir = get_lnd_dir(&temp_dir, "one");
  48. let cert_file = lnd_dir.join("tls.cert");
  49. let macaroon_file = lnd_dir.join("data/chain/bitcoin/regtest/admin.macaroon");
  50. println!("Looking for LND cert file: {:?}", cert_file);
  51. println!("Looking for LND macaroon file: {:?}", macaroon_file);
  52. println!("Connecting to LND at: https://{}", LND_RPC_ADDR);
  53. // Connect to LND
  54. LndClient::new(
  55. format!("https://{}", LND_RPC_ADDR),
  56. cert_file.clone(),
  57. macaroon_file.clone(),
  58. )
  59. .await
  60. .expect("Could not connect to lnd rpc")
  61. }
  62. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  63. async fn test_internal_payment() {
  64. let lnd_client = init_lnd_client().await;
  65. let wallet = Wallet::new(
  66. &get_mint_url_from_env(),
  67. CurrencyUnit::Sat,
  68. Arc::new(memory::empty().await.unwrap()),
  69. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  70. None,
  71. )
  72. .expect("failed to create new wallet");
  73. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  74. lnd_client
  75. .pay_invoice(mint_quote.request.clone())
  76. .await
  77. .expect("failed to pay invoice");
  78. wallet
  79. .wait_for_payment(&mint_quote, Duration::from_secs(60))
  80. .await
  81. .unwrap();
  82. let _mint_amount = wallet
  83. .mint(&mint_quote.id, SplitTarget::default(), None)
  84. .await
  85. .unwrap();
  86. assert!(wallet.total_balance().await.unwrap() == 100.into());
  87. let wallet_2 = Wallet::new(
  88. &get_mint_url_from_env(),
  89. CurrencyUnit::Sat,
  90. Arc::new(memory::empty().await.unwrap()),
  91. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  92. None,
  93. )
  94. .expect("failed to create new wallet");
  95. let mint_quote = wallet_2.mint_quote(10.into(), None).await.unwrap();
  96. let melt = wallet
  97. .melt_quote(mint_quote.request.clone(), None)
  98. .await
  99. .unwrap();
  100. assert_eq!(melt.amount, 10.into());
  101. let _melted = wallet.melt(&melt.id).await.unwrap();
  102. wallet_2
  103. .wait_for_payment(&mint_quote, Duration::from_secs(60))
  104. .await
  105. .unwrap();
  106. let _wallet_2_mint = wallet_2
  107. .mint(&mint_quote.id, SplitTarget::default(), None)
  108. .await
  109. .unwrap();
  110. // let check_paid = match get_mint_port("0") {
  111. // 8085 => {
  112. // let cln_one_dir = get_cln_dir(&get_temp_dir(), "one");
  113. // let cln_client = ClnClient::new(cln_one_dir.clone(), None).await.unwrap();
  114. // let payment_hash = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
  115. // cln_client
  116. // .check_incoming_payment_status(&payment_hash.payment_hash().to_string())
  117. // .await
  118. // .expect("Could not check invoice")
  119. // }
  120. // 8087 => {
  121. // let lnd_two_dir = get_lnd_dir(&get_temp_dir(), "two");
  122. // let lnd_client = LndClient::new(
  123. // format!("https://{}", LND_TWO_RPC_ADDR),
  124. // get_lnd_cert_file_path(&lnd_two_dir),
  125. // get_lnd_macaroon_path(&lnd_two_dir),
  126. // )
  127. // .await
  128. // .unwrap();
  129. // let payment_hash = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
  130. // lnd_client
  131. // .check_incoming_payment_status(&payment_hash.payment_hash().to_string())
  132. // .await
  133. // .expect("Could not check invoice")
  134. // }
  135. // _ => panic!("Unknown mint port"),
  136. // };
  137. // match check_paid {
  138. // InvoiceStatus::Unpaid => (),
  139. // _ => {
  140. // panic!("Invoice has incorrect status: {:?}", check_paid);
  141. // }
  142. // }
  143. let wallet_2_balance = wallet_2.total_balance().await.unwrap();
  144. assert!(wallet_2_balance == 10.into());
  145. let wallet_1_balance = wallet.total_balance().await.unwrap();
  146. assert!(wallet_1_balance == 90.into());
  147. }
  148. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  149. async fn test_websocket_connection() {
  150. let wallet = Wallet::new(
  151. &get_mint_url_from_env(),
  152. CurrencyUnit::Sat,
  153. Arc::new(wallet::memory::empty().await.unwrap()),
  154. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  155. None,
  156. )
  157. .expect("failed to create new wallet");
  158. // Create a small mint quote to test notifications
  159. let mint_quote = wallet.mint_quote(10.into(), None).await.unwrap();
  160. // Subscribe to notifications for this quote
  161. let mut subscription = wallet
  162. .subscribe(WalletSubscription::Bolt11MintQuoteState(vec![mint_quote
  163. .id
  164. .clone()]))
  165. .await;
  166. // First check we get the unpaid state
  167. let msg = timeout(Duration::from_secs(10), subscription.recv())
  168. .await
  169. .expect("timeout waiting for unpaid notification")
  170. .expect("No paid notification received");
  171. match msg {
  172. NotificationPayload::MintQuoteBolt11Response(response) => {
  173. assert_eq!(response.quote.to_string(), mint_quote.id);
  174. assert_eq!(response.state, MintQuoteState::Unpaid);
  175. }
  176. _ => panic!("Unexpected notification type"),
  177. }
  178. let lnd_client = init_lnd_client().await;
  179. lnd_client
  180. .pay_invoice(mint_quote.request)
  181. .await
  182. .expect("failed to pay invoice");
  183. // Wait for paid notification with 10 second timeout
  184. let msg = timeout(Duration::from_secs(10), subscription.recv())
  185. .await
  186. .expect("timeout waiting for paid notification")
  187. .expect("No paid notification received");
  188. match msg {
  189. NotificationPayload::MintQuoteBolt11Response(response) => {
  190. assert_eq!(response.quote.to_string(), mint_quote.id);
  191. assert_eq!(response.state, MintQuoteState::Paid);
  192. }
  193. _ => panic!("Unexpected notification type"),
  194. }
  195. }
  196. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  197. async fn test_multimint_melt() {
  198. let lnd_client = init_lnd_client().await;
  199. let db = Arc::new(memory::empty().await.unwrap());
  200. let wallet1 = Wallet::new(
  201. &get_mint_url_from_env(),
  202. CurrencyUnit::Sat,
  203. db,
  204. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  205. None,
  206. )
  207. .expect("failed to create new wallet");
  208. let db = Arc::new(memory::empty().await.unwrap());
  209. let wallet2 = Wallet::new(
  210. &get_second_mint_url_from_env(),
  211. CurrencyUnit::Sat,
  212. db,
  213. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  214. None,
  215. )
  216. .expect("failed to create new wallet");
  217. let mint_amount = Amount::from(100);
  218. // Fund the wallets
  219. let quote = wallet1.mint_quote(mint_amount, None).await.unwrap();
  220. lnd_client
  221. .pay_invoice(quote.request.clone())
  222. .await
  223. .expect("failed to pay invoice");
  224. wallet1
  225. .wait_for_payment(&quote, Duration::from_secs(60))
  226. .await
  227. .unwrap();
  228. wallet1
  229. .mint(&quote.id, SplitTarget::default(), None)
  230. .await
  231. .unwrap();
  232. let quote = wallet2.mint_quote(mint_amount, None).await.unwrap();
  233. lnd_client
  234. .pay_invoice(quote.request.clone())
  235. .await
  236. .expect("failed to pay invoice");
  237. wallet2
  238. .wait_for_payment(&quote, Duration::from_secs(60))
  239. .await
  240. .unwrap();
  241. wallet2
  242. .mint(&quote.id, SplitTarget::default(), None)
  243. .await
  244. .unwrap();
  245. // Get an invoice
  246. let invoice = lnd_client.create_invoice(Some(50)).await.unwrap();
  247. // Get multi-part melt quotes
  248. let melt_options = MeltOptions::Mpp {
  249. mpp: Mpp {
  250. amount: Amount::from(25000),
  251. },
  252. };
  253. let quote_1 = wallet1
  254. .melt_quote(invoice.clone(), Some(melt_options))
  255. .await
  256. .expect("Could not get melt quote");
  257. let quote_2 = wallet2
  258. .melt_quote(invoice.clone(), Some(melt_options))
  259. .await
  260. .expect("Could not get melt quote");
  261. // Multimint pay invoice
  262. let result1 = wallet1.melt(&quote_1.id);
  263. let result2 = wallet2.melt(&quote_2.id);
  264. let result = join!(result1, result2);
  265. // Unpack results
  266. let result1 = result.0.unwrap();
  267. let result2 = result.1.unwrap();
  268. // Check
  269. assert!(result1.state == result2.state);
  270. assert!(result1.state == MeltQuoteState::Paid);
  271. }
  272. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  273. async fn test_cached_mint() {
  274. let lnd_client = init_lnd_client().await;
  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_amount = Amount::from(100);
  284. let quote = wallet.mint_quote(mint_amount, None).await.unwrap();
  285. lnd_client
  286. .pay_invoice(quote.request.clone())
  287. .await
  288. .expect("failed to pay invoice");
  289. wallet
  290. .wait_for_payment(&quote, Duration::from_secs(60))
  291. .await
  292. .unwrap();
  293. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  294. let http_client = HttpClient::new(get_mint_url_from_env().parse().unwrap(), None);
  295. let premint_secrets =
  296. PreMintSecrets::random(active_keyset_id, 100.into(), &SplitTarget::default()).unwrap();
  297. let mut request = MintRequest {
  298. quote: quote.id,
  299. outputs: premint_secrets.blinded_messages(),
  300. signature: None,
  301. };
  302. let secret_key = quote.secret_key;
  303. request
  304. .sign(secret_key.expect("Secret key on quote"))
  305. .unwrap();
  306. let response = http_client.post_mint(request.clone()).await.unwrap();
  307. let response1 = http_client.post_mint(request).await.unwrap();
  308. assert!(response == response1);
  309. }
  310. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  311. async fn test_regtest_melt_amountless() {
  312. let lnd_client = init_lnd_client().await;
  313. let wallet = Wallet::new(
  314. &get_mint_url_from_env(),
  315. CurrencyUnit::Sat,
  316. Arc::new(memory::empty().await.unwrap()),
  317. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  318. None,
  319. )
  320. .expect("failed to create new wallet");
  321. let mint_amount = Amount::from(100);
  322. let mint_quote = wallet.mint_quote(mint_amount, None).await.unwrap();
  323. assert_eq!(mint_quote.amount, Some(mint_amount));
  324. lnd_client
  325. .pay_invoice(mint_quote.request)
  326. .await
  327. .expect("failed to pay invoice");
  328. let proofs = wallet
  329. .mint(&mint_quote.id, SplitTarget::default(), None)
  330. .await
  331. .unwrap();
  332. let amount = proofs.total_amount().unwrap();
  333. assert!(mint_amount == amount);
  334. let invoice = lnd_client.create_invoice(None).await.unwrap();
  335. let options = MeltOptions::new_amountless(5_000);
  336. let melt_quote = wallet
  337. .melt_quote(invoice.clone(), Some(options))
  338. .await
  339. .unwrap();
  340. let melt = wallet.melt(&melt_quote.id).await.unwrap();
  341. assert!(melt.amount == 5.into());
  342. }