regtest.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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::ProofsMethods;
  7. use cdk::amount::{Amount, SplitTarget};
  8. use cdk::nuts::{
  9. CurrencyUnit, MeltOptions, MeltQuoteState, MintBolt11Request, MintQuoteState, Mpp,
  10. NotificationPayload, 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 db = Arc::new(memory::empty().await?);
  159. let wallet1 = Wallet::new(
  160. &get_mint_url_from_env(),
  161. CurrencyUnit::Sat,
  162. db,
  163. &Mnemonic::generate(12)?.to_seed_normalized(""),
  164. None,
  165. )?;
  166. let db = Arc::new(memory::empty().await?);
  167. let wallet2 = Wallet::new(
  168. &get_second_mint_url_from_env(),
  169. CurrencyUnit::Sat,
  170. db,
  171. &Mnemonic::generate(12)?.to_seed_normalized(""),
  172. None,
  173. )?;
  174. let mint_amount = Amount::from(100);
  175. // Fund the wallets
  176. let quote = wallet1.mint_quote(mint_amount, None).await?;
  177. lnd_client.pay_invoice(quote.request.clone()).await?;
  178. wait_for_mint_to_be_paid(&wallet1, &quote.id, 60).await?;
  179. wallet1
  180. .mint(&quote.id, SplitTarget::default(), None)
  181. .await?;
  182. let quote = wallet2.mint_quote(mint_amount, None).await?;
  183. lnd_client.pay_invoice(quote.request.clone()).await?;
  184. wait_for_mint_to_be_paid(&wallet2, &quote.id, 60).await?;
  185. wallet2
  186. .mint(&quote.id, SplitTarget::default(), None)
  187. .await?;
  188. // Get an invoice
  189. let invoice = lnd_client.create_invoice(Some(50)).await?;
  190. // Get multi-part melt quotes
  191. let melt_options = MeltOptions::Mpp {
  192. mpp: Mpp {
  193. amount: Amount::from(25000),
  194. },
  195. };
  196. let quote_1 = wallet1
  197. .melt_quote(invoice.clone(), Some(melt_options))
  198. .await
  199. .expect("Could not get melt quote");
  200. let quote_2 = wallet2
  201. .melt_quote(invoice.clone(), Some(melt_options))
  202. .await
  203. .expect("Could not get melt quote");
  204. // Multimint pay invoice
  205. let result1 = wallet1.melt(&quote_1.id);
  206. let result2 = wallet2.melt(&quote_2.id);
  207. let result = join!(result1, result2);
  208. // Unpack results
  209. let result1 = result.0.unwrap();
  210. let result2 = result.1.unwrap();
  211. // Check
  212. assert!(result1.state == result2.state);
  213. assert!(result1.state == MeltQuoteState::Paid);
  214. Ok(())
  215. }
  216. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  217. async fn test_cached_mint() -> Result<()> {
  218. let lnd_client = init_lnd_client().await;
  219. let wallet = Wallet::new(
  220. &get_mint_url_from_env(),
  221. CurrencyUnit::Sat,
  222. Arc::new(memory::empty().await?),
  223. &Mnemonic::generate(12)?.to_seed_normalized(""),
  224. None,
  225. )?;
  226. let mint_amount = Amount::from(100);
  227. let quote = wallet.mint_quote(mint_amount, None).await?;
  228. lnd_client.pay_invoice(quote.request.clone()).await?;
  229. wait_for_mint_to_be_paid(&wallet, &quote.id, 60).await?;
  230. let active_keyset_id = wallet.get_active_mint_keyset().await?.id;
  231. let http_client = HttpClient::new(get_mint_url_from_env().parse().unwrap(), None);
  232. let premint_secrets =
  233. PreMintSecrets::random(active_keyset_id, 100.into(), &SplitTarget::default()).unwrap();
  234. let mut request = MintBolt11Request {
  235. quote: quote.id,
  236. outputs: premint_secrets.blinded_messages(),
  237. signature: None,
  238. };
  239. let secret_key = quote.secret_key;
  240. request.sign(secret_key.expect("Secret key on quote"))?;
  241. let response = http_client.post_mint(request.clone()).await?;
  242. let response1 = http_client.post_mint(request).await?;
  243. assert!(response == response1);
  244. Ok(())
  245. }
  246. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  247. async fn test_regtest_melt_amountless() -> Result<()> {
  248. let lnd_client = init_lnd_client().await;
  249. let wallet = Wallet::new(
  250. &get_mint_url_from_env(),
  251. CurrencyUnit::Sat,
  252. Arc::new(memory::empty().await?),
  253. &Mnemonic::generate(12)?.to_seed_normalized(""),
  254. None,
  255. )?;
  256. let mint_amount = Amount::from(100);
  257. let mint_quote = wallet.mint_quote(mint_amount, None).await?;
  258. assert_eq!(mint_quote.amount, mint_amount);
  259. lnd_client.pay_invoice(mint_quote.request).await?;
  260. let proofs = wallet
  261. .mint(&mint_quote.id, SplitTarget::default(), None)
  262. .await?;
  263. let amount = proofs.total_amount()?;
  264. assert!(mint_amount == amount);
  265. let invoice = lnd_client.create_invoice(None).await?;
  266. let options = MeltOptions::new_amountless(5_000);
  267. let melt_quote = wallet.melt_quote(invoice.clone(), Some(options)).await?;
  268. let melt = wallet.melt(&melt_quote.id).await.unwrap();
  269. assert!(melt.amount == 5.into());
  270. Ok(())
  271. }