regtest.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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::nut00::KnownMethod;
  21. use cdk::nuts::{
  22. CurrencyUnit, MeltOptions, MeltQuoteState, MintQuoteState, MintRequest, Mpp,
  23. NotificationPayload, PaymentMethod, PreMintSecrets,
  24. };
  25. use cdk::wallet::{HttpClient, MintConnector, Wallet, WalletSubscription};
  26. use cdk_integration_tests::{
  27. attempt_manual_mint, get_mint_url_from_env, get_second_mint_url_from_env, get_test_client,
  28. };
  29. use cdk_sqlite::wallet::{self, memory};
  30. use futures::join;
  31. use tokio::time::timeout;
  32. const LDK_URL: &str = "http://127.0.0.1:8089";
  33. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  34. async fn test_internal_payment() {
  35. let ln_client = get_test_client().await;
  36. let wallet = Wallet::new(
  37. &get_mint_url_from_env(),
  38. CurrencyUnit::Sat,
  39. Arc::new(memory::empty().await.unwrap()),
  40. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  41. None,
  42. )
  43. .expect("failed to create new wallet");
  44. let mint_quote = wallet
  45. .mint_quote(PaymentMethod::BOLT11, Some(100.into()), None, None)
  46. .await
  47. .unwrap();
  48. ln_client
  49. .pay_invoice(mint_quote.request.clone())
  50. .await
  51. .expect("failed to pay invoice");
  52. let _proofs = wallet
  53. .wait_and_mint_quote(
  54. mint_quote.clone(),
  55. SplitTarget::default(),
  56. None,
  57. tokio::time::Duration::from_secs(60),
  58. )
  59. .await
  60. .expect("payment");
  61. assert!(wallet.total_balance().await.unwrap() == 100.into());
  62. let wallet_2 = Wallet::new(
  63. &get_mint_url_from_env(),
  64. CurrencyUnit::Sat,
  65. Arc::new(memory::empty().await.unwrap()),
  66. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  67. None,
  68. )
  69. .expect("failed to create new wallet");
  70. let mint_quote = wallet_2
  71. .mint_quote(PaymentMethod::BOLT11, Some(10.into()), None, None)
  72. .await
  73. .unwrap();
  74. let melt = wallet
  75. .melt_quote(
  76. PaymentMethod::BOLT11,
  77. mint_quote.request.clone(),
  78. None,
  79. None,
  80. )
  81. .await
  82. .unwrap();
  83. assert_eq!(melt.amount, 10.into());
  84. let prepared = wallet
  85. .prepare_melt(&melt.id, std::collections::HashMap::new())
  86. .await
  87. .unwrap();
  88. let _melted = prepared.confirm().await.unwrap();
  89. let _proofs = wallet_2
  90. .wait_and_mint_quote(
  91. mint_quote.clone(),
  92. SplitTarget::default(),
  93. None,
  94. tokio::time::Duration::from_secs(60),
  95. )
  96. .await
  97. .expect("payment");
  98. // let check_paid = match get_mint_port("0") {
  99. // 8085 => {
  100. // let cln_one_dir = get_cln_dir(&get_temp_dir(), "one");
  101. // let cln_client = ClnClient::new(cln_one_dir.clone(), None).await.unwrap();
  102. // let payment_hash = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
  103. // cln_client
  104. // .check_incoming_payment_status(&payment_hash.payment_hash().to_string())
  105. // .await
  106. // .expect("Could not check invoice")
  107. // }
  108. // 8087 => {
  109. // let lnd_two_dir = get_lnd_dir(&get_temp_dir(), "two");
  110. // let lnd_client = LndClient::new(
  111. // format!("https://{}", LND_TWO_RPC_ADDR),
  112. // get_lnd_cert_file_path(&lnd_two_dir),
  113. // get_lnd_macaroon_path(&lnd_two_dir),
  114. // )
  115. // .await
  116. // .unwrap();
  117. // let payment_hash = Bolt11Invoice::from_str(&mint_quote.request).unwrap();
  118. // lnd_client
  119. // .check_incoming_payment_status(&payment_hash.payment_hash().to_string())
  120. // .await
  121. // .expect("Could not check invoice")
  122. // }
  123. // _ => panic!("Unknown mint port"),
  124. // };
  125. // match check_paid {
  126. // InvoiceStatus::Unpaid => (),
  127. // _ => {
  128. // panic!("Invoice has incorrect status: {:?}", check_paid);
  129. // }
  130. // }
  131. let wallet_2_balance = wallet_2.total_balance().await.unwrap();
  132. assert!(wallet_2_balance == 10.into());
  133. let wallet_1_balance = wallet.total_balance().await.unwrap();
  134. assert!(wallet_1_balance == 90.into());
  135. }
  136. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  137. async fn test_websocket_connection() {
  138. let wallet = Wallet::new(
  139. &get_mint_url_from_env(),
  140. CurrencyUnit::Sat,
  141. Arc::new(wallet::memory::empty().await.unwrap()),
  142. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  143. None,
  144. )
  145. .expect("failed to create new wallet");
  146. // Create a small mint quote to test notifications
  147. let mint_quote = wallet
  148. .mint_quote(PaymentMethod::BOLT11, Some(10.into()), None, None)
  149. .await
  150. .unwrap();
  151. // Subscribe to notifications for this quote
  152. let mut subscription = wallet
  153. .subscribe(WalletSubscription::Bolt11MintQuoteState(vec![mint_quote
  154. .id
  155. .clone()]))
  156. .await
  157. .expect("failed to subscribe");
  158. // First check we get the unpaid state
  159. let msg = timeout(Duration::from_secs(10), subscription.recv())
  160. .await
  161. .expect("timeout waiting for unpaid notification")
  162. .expect("No paid notification received");
  163. match msg.into_inner() {
  164. NotificationPayload::MintQuoteBolt11Response(response) => {
  165. assert_eq!(response.quote.to_string(), mint_quote.id);
  166. assert_eq!(response.state, MintQuoteState::Unpaid);
  167. }
  168. _ => panic!("Unexpected notification type"),
  169. }
  170. let ln_client = get_test_client().await;
  171. ln_client
  172. .pay_invoice(mint_quote.request)
  173. .await
  174. .expect("failed to pay invoice");
  175. // Wait for paid notification with 10 second timeout
  176. let msg = timeout(Duration::from_secs(10), subscription.recv())
  177. .await
  178. .expect("timeout waiting for paid notification")
  179. .expect("No paid notification received");
  180. match msg.into_inner() {
  181. NotificationPayload::MintQuoteBolt11Response(response) => {
  182. assert_eq!(response.quote.to_string(), mint_quote.id);
  183. assert_eq!(response.state, MintQuoteState::Paid);
  184. }
  185. _ => panic!("Unexpected notification type"),
  186. }
  187. }
  188. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  189. async fn test_multimint_melt() {
  190. if get_mint_url_from_env() == LDK_URL {
  191. return;
  192. }
  193. let ln_client = get_test_client().await;
  194. let db = Arc::new(memory::empty().await.unwrap());
  195. let wallet1 = Wallet::new(
  196. &get_mint_url_from_env(),
  197. CurrencyUnit::Sat,
  198. db,
  199. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  200. None,
  201. )
  202. .expect("failed to create new wallet");
  203. let db = Arc::new(memory::empty().await.unwrap());
  204. let wallet2 = Wallet::new(
  205. &get_second_mint_url_from_env(),
  206. CurrencyUnit::Sat,
  207. db,
  208. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  209. None,
  210. )
  211. .expect("failed to create new wallet");
  212. let mint_amount = Amount::from(100);
  213. // Fund the wallets
  214. let quote = wallet1
  215. .mint_quote(PaymentMethod::BOLT11, Some(mint_amount), None, None)
  216. .await
  217. .unwrap();
  218. ln_client
  219. .pay_invoice(quote.request.clone())
  220. .await
  221. .expect("failed to pay invoice");
  222. let _proofs = wallet1
  223. .wait_and_mint_quote(
  224. quote.clone(),
  225. SplitTarget::default(),
  226. None,
  227. tokio::time::Duration::from_secs(60),
  228. )
  229. .await
  230. .expect("payment");
  231. let quote = wallet2
  232. .mint_quote(PaymentMethod::BOLT11, Some(mint_amount), None, None)
  233. .await
  234. .unwrap();
  235. ln_client
  236. .pay_invoice(quote.request.clone())
  237. .await
  238. .expect("failed to pay invoice");
  239. let _proofs = wallet2
  240. .wait_and_mint_quote(
  241. quote.clone(),
  242. SplitTarget::default(),
  243. None,
  244. tokio::time::Duration::from_secs(60),
  245. )
  246. .await
  247. .expect("payment");
  248. // Get an invoice
  249. let invoice = ln_client.create_invoice(Some(50)).await.unwrap();
  250. // Get multi-part melt quotes
  251. let melt_options = MeltOptions::Mpp {
  252. mpp: Mpp {
  253. amount: Amount::from(25000),
  254. },
  255. };
  256. let quote_1 = wallet1
  257. .melt_quote(
  258. PaymentMethod::BOLT11,
  259. invoice.clone(),
  260. Some(melt_options),
  261. None,
  262. )
  263. .await
  264. .expect("Could not get melt quote");
  265. let quote_2 = wallet2
  266. .melt_quote(
  267. PaymentMethod::BOLT11,
  268. invoice.clone(),
  269. Some(melt_options),
  270. None,
  271. )
  272. .await
  273. .expect("Could not get melt quote");
  274. // Multimint pay invoice - prepare both melts
  275. let prepared1 = wallet1
  276. .prepare_melt(&quote_1.id, std::collections::HashMap::new())
  277. .await
  278. .expect("Could not prepare melt 1");
  279. let prepared2 = wallet2
  280. .prepare_melt(&quote_2.id, std::collections::HashMap::new())
  281. .await
  282. .expect("Could not prepare melt 2");
  283. // Confirm both in parallel
  284. let result = join!(prepared1.confirm(), prepared2.confirm());
  285. // Unpack results
  286. let result1 = result.0.unwrap();
  287. let result2 = result.1.unwrap();
  288. // Check
  289. assert!(result1.state() == result2.state());
  290. assert!(result1.state() == MeltQuoteState::Paid);
  291. }
  292. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  293. async fn test_cached_mint() {
  294. let ln_client = get_test_client().await;
  295. let wallet = Wallet::new(
  296. &get_mint_url_from_env(),
  297. CurrencyUnit::Sat,
  298. Arc::new(memory::empty().await.unwrap()),
  299. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  300. None,
  301. )
  302. .expect("failed to create new wallet");
  303. let mint_amount = Amount::from(100);
  304. let quote = wallet
  305. .mint_quote(PaymentMethod::BOLT11, Some(mint_amount), None, None)
  306. .await
  307. .unwrap();
  308. ln_client
  309. .pay_invoice(quote.request.clone())
  310. .await
  311. .expect("failed to pay invoice");
  312. let _proofs = wallet
  313. .wait_for_payment(&quote, tokio::time::Duration::from_secs(15))
  314. .await
  315. .expect("payment");
  316. let active_keyset_id = wallet.fetch_active_keyset().await.unwrap().id;
  317. let fee_and_amounts = (0, ((0..32).map(|x| 2u64.pow(x)).collect::<Vec<_>>())).into();
  318. let http_client = HttpClient::new(get_mint_url_from_env().parse().unwrap(), None);
  319. // Fetch mint info to populate cache support (NUT-19)
  320. http_client.get_mint_info().await.unwrap();
  321. let premint_secrets = PreMintSecrets::random(
  322. active_keyset_id,
  323. 100.into(),
  324. &SplitTarget::default().to_owned(),
  325. &fee_and_amounts,
  326. )
  327. .unwrap();
  328. let mut request = MintRequest {
  329. quote: quote.id,
  330. outputs: premint_secrets.blinded_messages(),
  331. signature: None,
  332. };
  333. let secret_key = quote.secret_key;
  334. request
  335. .sign(secret_key.expect("Secret key on quote"))
  336. .unwrap();
  337. let response = http_client
  338. .post_mint(&PaymentMethod::Known(KnownMethod::Bolt11), request.clone())
  339. .await
  340. .unwrap();
  341. let response1 = http_client
  342. .post_mint(&PaymentMethod::Known(KnownMethod::Bolt11), request)
  343. .await
  344. .unwrap();
  345. assert!(response == response1);
  346. }
  347. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  348. async fn test_regtest_melt_amountless() {
  349. let ln_client = get_test_client().await;
  350. let wallet = Wallet::new(
  351. &get_mint_url_from_env(),
  352. CurrencyUnit::Sat,
  353. Arc::new(memory::empty().await.unwrap()),
  354. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  355. None,
  356. )
  357. .expect("failed to create new wallet");
  358. let mint_amount = Amount::from(100);
  359. let mint_quote = wallet
  360. .mint_quote(PaymentMethod::BOLT11, Some(mint_amount), None, None)
  361. .await
  362. .unwrap();
  363. assert_eq!(mint_quote.amount, Some(mint_amount));
  364. ln_client
  365. .pay_invoice(mint_quote.request.clone())
  366. .await
  367. .expect("failed to pay invoice");
  368. let proofs = wallet
  369. .wait_and_mint_quote(
  370. mint_quote,
  371. SplitTarget::default(),
  372. None,
  373. Duration::from_secs(60),
  374. )
  375. .await
  376. .unwrap();
  377. let amount = proofs.total_amount().unwrap();
  378. assert!(mint_amount == amount);
  379. let invoice = ln_client.create_invoice(None).await.unwrap();
  380. let options = MeltOptions::new_amountless(5_000);
  381. let melt_quote = wallet
  382. .melt_quote(PaymentMethod::BOLT11, invoice.clone(), Some(options), None)
  383. .await
  384. .unwrap();
  385. let prepared = wallet
  386. .prepare_melt(&melt_quote.id, std::collections::HashMap::new())
  387. .await
  388. .unwrap();
  389. let melt = prepared.confirm().await.unwrap();
  390. assert!(melt.amount() == 5.into());
  391. }
  392. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  393. async fn test_attempt_to_mint_unpaid() {
  394. let wallet = Wallet::new(
  395. &get_mint_url_from_env(),
  396. CurrencyUnit::Sat,
  397. Arc::new(memory::empty().await.unwrap()),
  398. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  399. None,
  400. )
  401. .expect("failed to create new wallet");
  402. let mint_amount = Amount::from(100);
  403. let mint_quote = wallet
  404. .mint_quote(PaymentMethod::BOLT11, Some(mint_amount), None, None)
  405. .await
  406. .unwrap();
  407. assert_eq!(mint_quote.amount, Some(mint_amount));
  408. let response = attempt_manual_mint(
  409. &wallet,
  410. &get_mint_url_from_env(),
  411. &mint_quote,
  412. mint_amount,
  413. PaymentMethod::Known(KnownMethod::Bolt11),
  414. )
  415. .await;
  416. match response {
  417. Err(err) => {
  418. if !matches!(err, cdk::Error::UnpaidQuote) {
  419. panic!("Wrong error quote should be unpaid: {}", err);
  420. }
  421. }
  422. Ok(_) => {
  423. panic!("Minting should not be allowed");
  424. }
  425. }
  426. let mint_quote = wallet
  427. .mint_quote(PaymentMethod::BOLT11, Some(mint_amount), None, None)
  428. .await
  429. .unwrap();
  430. let state = wallet
  431. .refresh_mint_quote_status(&mint_quote.id)
  432. .await
  433. .unwrap();
  434. assert!(state.state == MintQuoteState::Unpaid);
  435. let response = attempt_manual_mint(
  436. &wallet,
  437. &get_mint_url_from_env(),
  438. &mint_quote,
  439. mint_amount,
  440. PaymentMethod::Known(KnownMethod::Bolt11),
  441. )
  442. .await;
  443. match response {
  444. Err(err) => {
  445. if !matches!(err, cdk::Error::UnpaidQuote) {
  446. panic!("Wrong error quote should be unpaid: {}", err);
  447. }
  448. }
  449. Ok(_) => {
  450. panic!("Minting should not be allowed");
  451. }
  452. }
  453. }