regtest.rs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. use std::str::FromStr;
  2. use std::sync::Arc;
  3. use std::time::Duration;
  4. use anyhow::{bail, Result};
  5. use bip39::Mnemonic;
  6. use cashu::{MeltOptions, Mpp};
  7. use cdk::amount::{Amount, SplitTarget};
  8. use cdk::nuts::{
  9. CurrencyUnit, MeltQuoteState, MintBolt11Request, MintQuoteState, NotificationPayload,
  10. PreMintSecrets,
  11. };
  12. use cdk::wallet::{HttpClient, MintConnector, Wallet, WalletSubscription};
  13. use cdk_integration_tests::init_regtest::{
  14. get_cln_dir, get_lnd_cert_file_path, get_lnd_dir, get_lnd_macaroon_path, get_mint_port,
  15. LND_RPC_ADDR, LND_TWO_RPC_ADDR,
  16. };
  17. use cdk_integration_tests::{
  18. get_mint_url_from_env, get_second_mint_url_from_env, wait_for_mint_to_be_paid,
  19. };
  20. use cdk_sqlite::wallet::{self, memory};
  21. use futures::join;
  22. use lightning_invoice::Bolt11Invoice;
  23. use ln_regtest_rs::ln_client::{ClnClient, LightningClient, LndClient};
  24. use ln_regtest_rs::InvoiceStatus;
  25. use tokio::time::timeout;
  26. // This is the ln wallet we use to send/receive ln payements as the wallet
  27. async fn init_lnd_client() -> LndClient {
  28. let lnd_dir = get_lnd_dir("one");
  29. let cert_file = lnd_dir.join("tls.cert");
  30. let macaroon_file = lnd_dir.join("data/chain/bitcoin/regtest/admin.macaroon");
  31. LndClient::new(
  32. format!("https://{}", LND_RPC_ADDR),
  33. cert_file,
  34. macaroon_file,
  35. )
  36. .await
  37. .unwrap()
  38. }
  39. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  40. async fn test_internal_payment() -> Result<()> {
  41. let lnd_client = init_lnd_client().await;
  42. let wallet = Wallet::new(
  43. &get_mint_url_from_env(),
  44. CurrencyUnit::Sat,
  45. Arc::new(memory::empty().await?),
  46. &Mnemonic::generate(12)?.to_seed_normalized(""),
  47. None,
  48. )?;
  49. let mint_quote = wallet.mint_quote(100.into(), None).await?;
  50. lnd_client.pay_invoice(mint_quote.request).await?;
  51. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  52. let _mint_amount = wallet
  53. .mint(&mint_quote.id, SplitTarget::default(), None)
  54. .await?;
  55. assert!(wallet.total_balance().await? == 100.into());
  56. let wallet_2 = Wallet::new(
  57. &get_mint_url_from_env(),
  58. CurrencyUnit::Sat,
  59. Arc::new(memory::empty().await?),
  60. &Mnemonic::generate(12)?.to_seed_normalized(""),
  61. None,
  62. )?;
  63. let mint_quote = wallet_2.mint_quote(10.into(), None).await?;
  64. let melt = wallet.melt_quote(mint_quote.request.clone(), None).await?;
  65. assert_eq!(melt.amount, 10.into());
  66. let _melted = wallet.melt(&melt.id).await.unwrap();
  67. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  68. let _wallet_2_mint = wallet_2
  69. .mint(&mint_quote.id, SplitTarget::default(), None)
  70. .await
  71. .unwrap();
  72. let check_paid = match get_mint_port("0") {
  73. 8085 => {
  74. let cln_one_dir = get_cln_dir("one");
  75. let cln_client = ClnClient::new(cln_one_dir.clone(), None).await?;
  76. let payment_hash = Bolt11Invoice::from_str(&mint_quote.request)?;
  77. cln_client
  78. .check_incoming_payment_status(&payment_hash.payment_hash().to_string())
  79. .await
  80. .expect("Could not check invoice")
  81. }
  82. 8087 => {
  83. let lnd_two_dir = get_lnd_dir("two");
  84. let lnd_client = LndClient::new(
  85. format!("https://{}", LND_TWO_RPC_ADDR),
  86. get_lnd_cert_file_path(&lnd_two_dir),
  87. get_lnd_macaroon_path(&lnd_two_dir),
  88. )
  89. .await?;
  90. let payment_hash = Bolt11Invoice::from_str(&mint_quote.request)?;
  91. lnd_client
  92. .check_incoming_payment_status(&payment_hash.payment_hash().to_string())
  93. .await
  94. .expect("Could not check invoice")
  95. }
  96. _ => panic!("Unknown mint port"),
  97. };
  98. match check_paid {
  99. InvoiceStatus::Unpaid => (),
  100. _ => {
  101. bail!("Invoice has incorrect status: {:?}", check_paid);
  102. }
  103. }
  104. let wallet_2_balance = wallet_2.total_balance().await?;
  105. assert!(wallet_2_balance == 10.into());
  106. let wallet_1_balance = wallet.total_balance().await?;
  107. assert!(wallet_1_balance == 90.into());
  108. Ok(())
  109. }
  110. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  111. async fn test_websocket_connection() -> Result<()> {
  112. let wallet = Wallet::new(
  113. &get_mint_url_from_env(),
  114. CurrencyUnit::Sat,
  115. Arc::new(wallet::memory::empty().await?),
  116. &Mnemonic::generate(12)?.to_seed_normalized(""),
  117. None,
  118. )?;
  119. // Create a small mint quote to test notifications
  120. let mint_quote = wallet.mint_quote(10.into(), None).await?;
  121. // Subscribe to notifications for this quote
  122. let mut subscription = wallet
  123. .subscribe(WalletSubscription::Bolt11MintQuoteState(vec![mint_quote
  124. .id
  125. .clone()]))
  126. .await;
  127. // First check we get the unpaid state
  128. let msg = timeout(Duration::from_secs(10), subscription.recv())
  129. .await
  130. .expect("timeout waiting for unpaid notification")
  131. .ok_or_else(|| anyhow::anyhow!("No unpaid notification received"))?;
  132. match msg {
  133. NotificationPayload::MintQuoteBolt11Response(response) => {
  134. assert_eq!(response.quote.to_string(), mint_quote.id);
  135. assert_eq!(response.state, MintQuoteState::Unpaid);
  136. }
  137. _ => bail!("Unexpected notification type"),
  138. }
  139. let lnd_client = init_lnd_client().await;
  140. lnd_client.pay_invoice(mint_quote.request).await?;
  141. // Wait for paid notification with 10 second timeout
  142. let msg = timeout(Duration::from_secs(10), subscription.recv())
  143. .await
  144. .expect("timeout waiting for paid notification")
  145. .ok_or_else(|| anyhow::anyhow!("No paid notification received"))?;
  146. match msg {
  147. NotificationPayload::MintQuoteBolt11Response(response) => {
  148. assert_eq!(response.quote.to_string(), mint_quote.id);
  149. assert_eq!(response.state, MintQuoteState::Paid);
  150. Ok(())
  151. }
  152. _ => bail!("Unexpected notification type"),
  153. }
  154. }
  155. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  156. async fn test_multimint_melt() -> Result<()> {
  157. let lnd_client = init_lnd_client().await;
  158. let wallet1 = Wallet::new(
  159. &get_mint_url_from_env(),
  160. CurrencyUnit::Sat,
  161. Arc::new(memory::empty().await?),
  162. &Mnemonic::generate(12)?.to_seed_normalized(""),
  163. None,
  164. )?;
  165. let wallet2 = Wallet::new(
  166. &get_second_mint_url_from_env(),
  167. CurrencyUnit::Sat,
  168. Arc::new(memory::empty().await?),
  169. &Mnemonic::generate(12)?.to_seed_normalized(""),
  170. None,
  171. )?;
  172. let mint_amount = Amount::from(100);
  173. // Fund the wallets
  174. let quote = wallet1.mint_quote(mint_amount, None).await?;
  175. lnd_client.pay_invoice(quote.request.clone()).await?;
  176. wait_for_mint_to_be_paid(&wallet1, &quote.id, 60).await?;
  177. wallet1
  178. .mint(&quote.id, SplitTarget::default(), None)
  179. .await?;
  180. let quote = wallet2.mint_quote(mint_amount, None).await?;
  181. lnd_client.pay_invoice(quote.request.clone()).await?;
  182. wait_for_mint_to_be_paid(&wallet2, &quote.id, 60).await?;
  183. wallet2
  184. .mint(&quote.id, SplitTarget::default(), None)
  185. .await?;
  186. // Get an invoice
  187. let invoice = lnd_client.create_invoice(Some(50)).await?;
  188. // Get multi-part melt quotes
  189. let melt_options = MeltOptions::Mpp {
  190. mpp: Mpp {
  191. amount: Amount::from(25000),
  192. },
  193. };
  194. let quote_1 = wallet1
  195. .melt_quote(invoice.clone(), Some(melt_options))
  196. .await
  197. .expect("Could not get melt quote");
  198. let quote_2 = wallet2
  199. .melt_quote(invoice.clone(), Some(melt_options))
  200. .await
  201. .expect("Could not get melt quote");
  202. // Multimint pay invoice
  203. let result1 = wallet1.melt(&quote_1.id);
  204. let result2 = wallet2.melt(&quote_2.id);
  205. let result = join!(result1, result2);
  206. // Unpack results
  207. let result1 = result.0.unwrap();
  208. let result2 = result.1.unwrap();
  209. // Check
  210. assert!(result1.state == result2.state);
  211. assert!(result1.state == MeltQuoteState::Paid);
  212. Ok(())
  213. }
  214. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  215. async fn test_cached_mint() -> Result<()> {
  216. let lnd_client = init_lnd_client().await;
  217. let wallet = Wallet::new(
  218. &get_mint_url_from_env(),
  219. CurrencyUnit::Sat,
  220. Arc::new(memory::empty().await?),
  221. &Mnemonic::generate(12)?.to_seed_normalized(""),
  222. None,
  223. )?;
  224. let mint_amount = Amount::from(100);
  225. let quote = wallet.mint_quote(mint_amount, None).await?;
  226. lnd_client.pay_invoice(quote.request.clone()).await?;
  227. wait_for_mint_to_be_paid(&wallet, &quote.id, 60).await?;
  228. let active_keyset_id = wallet.get_active_mint_keyset().await?.id;
  229. let http_client = HttpClient::new(get_mint_url_from_env().parse().unwrap(), None);
  230. let premint_secrets =
  231. PreMintSecrets::random(active_keyset_id, 100.into(), &SplitTarget::default()).unwrap();
  232. let mut request = MintBolt11Request {
  233. quote: quote.id,
  234. outputs: premint_secrets.blinded_messages(),
  235. signature: None,
  236. };
  237. let secret_key = quote.secret_key;
  238. request.sign(secret_key.expect("Secret key on quote"))?;
  239. let response = http_client.post_mint(request.clone()).await?;
  240. let response1 = http_client.post_mint(request).await?;
  241. assert!(response == response1);
  242. Ok(())
  243. }