regtest.rs 13 KB

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