regtest.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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::{
  29. get_mint_url_from_env, get_second_mint_url_from_env, wait_for_mint_to_be_paid,
  30. };
  31. use cdk_sqlite::wallet::{self, memory};
  32. use futures::join;
  33. use ln_regtest_rs::ln_client::{LightningClient, LndClient};
  34. use tokio::time::timeout;
  35. // This is the ln wallet we use to send/receive ln payements as the wallet
  36. async fn init_lnd_client() -> LndClient {
  37. // Try to get the temp directory from environment variable first (from .env file)
  38. let temp_dir = match env::var("CDK_ITESTS_DIR") {
  39. Ok(dir) => {
  40. let path = PathBuf::from(dir);
  41. println!("Using temp directory from CDK_ITESTS_DIR: {:?}", path);
  42. path
  43. }
  44. Err(_) => {
  45. panic!("Unknown temp dir");
  46. }
  47. };
  48. // The LND mint uses the second LND node (LND_TWO_RPC_ADDR = localhost:10010)
  49. let lnd_dir = get_lnd_dir(&temp_dir, "one");
  50. let cert_file = lnd_dir.join("tls.cert");
  51. let macaroon_file = lnd_dir.join("data/chain/bitcoin/regtest/admin.macaroon");
  52. println!("Looking for LND cert file: {:?}", cert_file);
  53. println!("Looking for LND macaroon file: {:?}", macaroon_file);
  54. println!("Connecting to LND at: https://{}", LND_RPC_ADDR);
  55. // Connect to LND
  56. LndClient::new(
  57. format!("https://{}", LND_RPC_ADDR),
  58. cert_file.clone(),
  59. macaroon_file.clone(),
  60. )
  61. .await
  62. .expect("Could not connect to lnd rpc")
  63. }
  64. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  65. async fn test_internal_payment() {
  66. let lnd_client = init_lnd_client().await;
  67. let wallet = Wallet::new(
  68. &get_mint_url_from_env(),
  69. CurrencyUnit::Sat,
  70. Arc::new(memory::empty().await.unwrap()),
  71. &Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  72. None,
  73. )
  74. .expect("failed to create new wallet");
  75. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  76. lnd_client
  77. .pay_invoice(mint_quote.request)
  78. .await
  79. .expect("failed to pay invoice");
  80. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60)
  81. .await
  82. .unwrap();
  83. let _mint_amount = wallet
  84. .mint(&mint_quote.id, SplitTarget::default(), None)
  85. .await
  86. .unwrap();
  87. assert!(wallet.total_balance().await.unwrap() == 100.into());
  88. let wallet_2 = Wallet::new(
  89. &get_mint_url_from_env(),
  90. CurrencyUnit::Sat,
  91. Arc::new(memory::empty().await.unwrap()),
  92. &Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  93. None,
  94. )
  95. .expect("failed to create new wallet");
  96. let mint_quote = wallet_2.mint_quote(10.into(), None).await.unwrap();
  97. let melt = wallet
  98. .melt_quote(mint_quote.request.clone(), None)
  99. .await
  100. .unwrap();
  101. assert_eq!(melt.amount, 10.into());
  102. let _melted = wallet.melt(&melt.id).await.unwrap();
  103. wait_for_mint_to_be_paid(&wallet_2, &mint_quote.id, 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. wait_for_mint_to_be_paid(&wallet1, &quote.id, 60)
  225. .await
  226. .unwrap();
  227. wallet1
  228. .mint(&quote.id, SplitTarget::default(), None)
  229. .await
  230. .unwrap();
  231. let quote = wallet2.mint_quote(mint_amount, None).await.unwrap();
  232. lnd_client
  233. .pay_invoice(quote.request.clone())
  234. .await
  235. .expect("failed to pay invoice");
  236. wait_for_mint_to_be_paid(&wallet2, &quote.id, 60)
  237. .await
  238. .unwrap();
  239. wallet2
  240. .mint(&quote.id, SplitTarget::default(), None)
  241. .await
  242. .unwrap();
  243. // Get an invoice
  244. let invoice = lnd_client.create_invoice(Some(50)).await.unwrap();
  245. // Get multi-part melt quotes
  246. let melt_options = MeltOptions::Mpp {
  247. mpp: Mpp {
  248. amount: Amount::from(25000),
  249. },
  250. };
  251. let quote_1 = wallet1
  252. .melt_quote(invoice.clone(), Some(melt_options))
  253. .await
  254. .expect("Could not get melt quote");
  255. let quote_2 = wallet2
  256. .melt_quote(invoice.clone(), Some(melt_options))
  257. .await
  258. .expect("Could not get melt quote");
  259. // Multimint pay invoice
  260. let result1 = wallet1.melt(&quote_1.id);
  261. let result2 = wallet2.melt(&quote_2.id);
  262. let result = join!(result1, result2);
  263. // Unpack results
  264. let result1 = result.0.unwrap();
  265. let result2 = result.1.unwrap();
  266. // Check
  267. assert!(result1.state == result2.state);
  268. assert!(result1.state == MeltQuoteState::Paid);
  269. }
  270. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  271. async fn test_cached_mint() {
  272. let lnd_client = init_lnd_client().await;
  273. let wallet = Wallet::new(
  274. &get_mint_url_from_env(),
  275. CurrencyUnit::Sat,
  276. Arc::new(memory::empty().await.unwrap()),
  277. &Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  278. None,
  279. )
  280. .expect("failed to create new wallet");
  281. let mint_amount = Amount::from(100);
  282. let quote = wallet.mint_quote(mint_amount, None).await.unwrap();
  283. lnd_client
  284. .pay_invoice(quote.request.clone())
  285. .await
  286. .expect("failed to pay invoice");
  287. wait_for_mint_to_be_paid(&wallet, &quote.id, 60)
  288. .await
  289. .unwrap();
  290. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  291. let http_client = HttpClient::new(get_mint_url_from_env().parse().unwrap(), None);
  292. let premint_secrets =
  293. PreMintSecrets::random(active_keyset_id, 100.into(), &SplitTarget::default()).unwrap();
  294. let mut request = MintRequest {
  295. quote: quote.id,
  296. outputs: premint_secrets.blinded_messages(),
  297. signature: None,
  298. };
  299. let secret_key = quote.secret_key;
  300. request
  301. .sign(secret_key.expect("Secret key on quote"))
  302. .unwrap();
  303. let response = http_client.post_mint(request.clone()).await.unwrap();
  304. let response1 = http_client.post_mint(request).await.unwrap();
  305. assert!(response == response1);
  306. }
  307. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  308. async fn test_regtest_melt_amountless() {
  309. let lnd_client = init_lnd_client().await;
  310. let wallet = Wallet::new(
  311. &get_mint_url_from_env(),
  312. CurrencyUnit::Sat,
  313. Arc::new(memory::empty().await.unwrap()),
  314. &Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  315. None,
  316. )
  317. .expect("failed to create new wallet");
  318. let mint_amount = Amount::from(100);
  319. let mint_quote = wallet.mint_quote(mint_amount, None).await.unwrap();
  320. assert_eq!(mint_quote.amount, Some(mint_amount));
  321. lnd_client
  322. .pay_invoice(mint_quote.request)
  323. .await
  324. .expect("failed to pay invoice");
  325. let proofs = wallet
  326. .mint(&mint_quote.id, SplitTarget::default(), None)
  327. .await
  328. .unwrap();
  329. let amount = proofs.total_amount().unwrap();
  330. assert!(mint_amount == amount);
  331. let invoice = lnd_client.create_invoice(None).await.unwrap();
  332. let options = MeltOptions::new_amountless(5_000);
  333. let melt_quote = wallet
  334. .melt_quote(invoice.clone(), Some(options))
  335. .await
  336. .unwrap();
  337. let melt = wallet.melt(&melt_quote.id).await.unwrap();
  338. assert!(melt.amount == 5.into());
  339. }