regtest.rs 11 KB

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