bolt12.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. use std::env;
  2. use std::path::PathBuf;
  3. use std::sync::Arc;
  4. use anyhow::{bail, Result};
  5. use bip39::Mnemonic;
  6. use cashu::amount::SplitTarget;
  7. use cashu::nut23::Amountless;
  8. use cashu::{Amount, CurrencyUnit, MintRequest, PreMintSecrets, ProofsMethods};
  9. use cdk::wallet::{HttpClient, MintConnector, Wallet};
  10. use cdk::StreamExt;
  11. use cdk_integration_tests::get_mint_url_from_env;
  12. use cdk_integration_tests::init_regtest::{get_cln_dir, get_temp_dir};
  13. use cdk_sqlite::wallet::memory;
  14. use ln_regtest_rs::ln_client::ClnClient;
  15. // Helper function to get temp directory from environment or fallback
  16. fn get_test_temp_dir() -> PathBuf {
  17. match env::var("CDK_ITESTS_DIR") {
  18. Ok(dir) => PathBuf::from(dir),
  19. Err(_) => get_temp_dir(), // fallback to default
  20. }
  21. }
  22. // Helper function to create CLN client with retries
  23. async fn create_cln_client_with_retry(cln_dir: PathBuf) -> Result<ClnClient> {
  24. let mut retries = 0;
  25. let max_retries = 10;
  26. loop {
  27. match ClnClient::new(cln_dir.clone(), None).await {
  28. Ok(client) => return Ok(client),
  29. Err(e) => {
  30. retries += 1;
  31. if retries >= max_retries {
  32. bail!(
  33. "Could not connect to CLN client after {} retries: {}",
  34. max_retries,
  35. e
  36. );
  37. }
  38. println!(
  39. "Failed to connect to CLN (attempt {}/{}): {}. Retrying in 7 seconds...",
  40. retries, max_retries, e
  41. );
  42. tokio::time::sleep(tokio::time::Duration::from_secs(7)).await;
  43. }
  44. }
  45. }
  46. }
  47. /// Tests basic BOLT12 minting functionality:
  48. /// - Creates a wallet
  49. /// - Gets a BOLT12 quote for a specific amount (100 sats)
  50. /// - Pays the quote using Core Lightning
  51. /// - Mints tokens and verifies the correct amount is received
  52. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  53. async fn test_regtest_bolt12_mint() {
  54. let wallet = Wallet::new(
  55. &get_mint_url_from_env(),
  56. CurrencyUnit::Sat,
  57. Arc::new(memory::empty().await.unwrap()),
  58. Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  59. None,
  60. )
  61. .unwrap();
  62. let mint_amount = Amount::from(100);
  63. let mint_quote = wallet
  64. .mint_bolt12_quote(Some(mint_amount), None)
  65. .await
  66. .unwrap();
  67. assert_eq!(mint_quote.amount, Some(mint_amount));
  68. let work_dir = get_test_temp_dir();
  69. let cln_one_dir = get_cln_dir(&work_dir, "one");
  70. let cln_client = create_cln_client_with_retry(cln_one_dir.clone())
  71. .await
  72. .unwrap();
  73. cln_client
  74. .pay_bolt12_offer(None, mint_quote.request)
  75. .await
  76. .unwrap();
  77. let proofs = wallet
  78. .mint_bolt12(&mint_quote.id, None, SplitTarget::default(), None)
  79. .await
  80. .unwrap();
  81. assert_eq!(proofs.total_amount().unwrap(), 100.into());
  82. }
  83. /// Tests multiple payments to a single BOLT12 quote:
  84. /// - Creates a wallet and gets a BOLT12 quote without specifying amount
  85. /// - Makes two separate payments (10,000 sats and 11,000 sats) to the same quote
  86. /// - Verifies that each payment can be minted separately and correctly
  87. /// - Tests the functionality of reusing a quote for multiple payments
  88. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  89. async fn test_regtest_bolt12_mint_multiple() -> Result<()> {
  90. let wallet = Wallet::new(
  91. &get_mint_url_from_env(),
  92. CurrencyUnit::Sat,
  93. Arc::new(memory::empty().await?),
  94. Mnemonic::generate(12)?.to_seed_normalized(""),
  95. None,
  96. )?;
  97. let mint_quote = wallet.mint_bolt12_quote(None, None).await?;
  98. let work_dir = get_test_temp_dir();
  99. let cln_one_dir = get_cln_dir(&work_dir, "one");
  100. let cln_client = create_cln_client_with_retry(cln_one_dir.clone()).await?;
  101. cln_client
  102. .pay_bolt12_offer(Some(10000), mint_quote.request.clone())
  103. .await
  104. .unwrap();
  105. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  106. let proofs = proof_streams.next().await.expect("payment")?;
  107. assert_eq!(proofs.total_amount().unwrap(), 10.into());
  108. cln_client
  109. .pay_bolt12_offer(Some(11_000), mint_quote.request.clone())
  110. .await
  111. .unwrap();
  112. let proofs = proof_streams.next().await.expect("payment")?;
  113. assert_eq!(proofs.total_amount().unwrap(), 11.into());
  114. Ok(())
  115. }
  116. /// Tests that multiple wallets can pay the same BOLT12 offer:
  117. /// - Creates a BOLT12 offer through CLN that both wallets will pay
  118. /// - Creates two separate wallets with different minting amounts
  119. /// - Has each wallet get their own quote and make payments
  120. /// - Verifies both wallets can successfully mint their tokens
  121. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  122. async fn test_regtest_bolt12_multiple_wallets() -> Result<()> {
  123. // Create first wallet
  124. let wallet_one = Wallet::new(
  125. &get_mint_url_from_env(),
  126. CurrencyUnit::Sat,
  127. Arc::new(memory::empty().await?),
  128. Mnemonic::generate(12)?.to_seed_normalized(""),
  129. None,
  130. )?;
  131. // Create second wallet
  132. let wallet_two = Wallet::new(
  133. &get_mint_url_from_env(),
  134. CurrencyUnit::Sat,
  135. Arc::new(memory::empty().await?),
  136. Mnemonic::generate(12)?.to_seed_normalized(""),
  137. None,
  138. )?;
  139. // Create a BOLT12 offer that both wallets will use
  140. let work_dir = get_test_temp_dir();
  141. let cln_one_dir = get_cln_dir(&work_dir, "one");
  142. let cln_client = create_cln_client_with_retry(cln_one_dir.clone()).await?;
  143. // First wallet payment
  144. let quote_one = wallet_one
  145. .mint_bolt12_quote(Some(10_000.into()), None)
  146. .await?;
  147. cln_client
  148. .pay_bolt12_offer(None, quote_one.request.clone())
  149. .await?;
  150. let mut proof_streams_one =
  151. wallet_one.proof_stream(quote_one.clone(), SplitTarget::default(), None);
  152. let proofs_one = proof_streams_one.next().await.expect("payment")?;
  153. assert_eq!(proofs_one.total_amount()?, 10_000.into());
  154. // Second wallet payment
  155. let quote_two = wallet_two
  156. .mint_bolt12_quote(Some(15_000.into()), None)
  157. .await?;
  158. cln_client
  159. .pay_bolt12_offer(None, quote_two.request.clone())
  160. .await?;
  161. let mut proof_streams_two =
  162. wallet_two.proof_stream(quote_two.clone(), SplitTarget::default(), None);
  163. let proofs_two = proof_streams_two.next().await.expect("payment")?;
  164. assert_eq!(proofs_two.total_amount()?, 15_000.into());
  165. let offer = cln_client
  166. .get_bolt12_offer(None, false, "test_multiple_wallets".to_string())
  167. .await?;
  168. let wallet_one_melt_quote = wallet_one
  169. .melt_bolt12_quote(
  170. offer.to_string(),
  171. Some(cashu::MeltOptions::Amountless {
  172. amountless: Amountless {
  173. amount_msat: 1500.into(),
  174. },
  175. }),
  176. )
  177. .await?;
  178. let wallet_two_melt_quote = wallet_two
  179. .melt_bolt12_quote(
  180. offer.to_string(),
  181. Some(cashu::MeltOptions::Amountless {
  182. amountless: Amountless {
  183. amount_msat: 1000.into(),
  184. },
  185. }),
  186. )
  187. .await?;
  188. let melted = wallet_one.melt(&wallet_one_melt_quote.id).await?;
  189. assert!(melted.preimage.is_some());
  190. let melted_two = wallet_two.melt(&wallet_two_melt_quote.id).await?;
  191. assert!(melted_two.preimage.is_some());
  192. Ok(())
  193. }
  194. /// Tests the BOLT12 melting (spending) functionality:
  195. /// - Creates a wallet and mints 20,000 sats using BOLT12
  196. /// - Creates a BOLT12 offer for 10,000 sats
  197. /// - Tests melting (spending) tokens using the BOLT12 offer
  198. /// - Verifies the correct amount is melted
  199. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  200. async fn test_regtest_bolt12_melt() -> Result<()> {
  201. let wallet = Wallet::new(
  202. &get_mint_url_from_env(),
  203. CurrencyUnit::Sat,
  204. Arc::new(memory::empty().await?),
  205. Mnemonic::generate(12)?.to_seed_normalized(""),
  206. None,
  207. )?;
  208. let mint_amount = Amount::from(20_000);
  209. // Create a single-use BOLT12 quote
  210. let mint_quote = wallet.mint_bolt12_quote(Some(mint_amount), None).await?;
  211. assert_eq!(mint_quote.amount, Some(mint_amount));
  212. // Pay the quote
  213. let work_dir = get_test_temp_dir();
  214. let cln_one_dir = get_cln_dir(&work_dir, "one");
  215. let cln_client = create_cln_client_with_retry(cln_one_dir.clone()).await?;
  216. cln_client
  217. .pay_bolt12_offer(None, mint_quote.request.clone())
  218. .await?;
  219. // Wait for payment to be processed
  220. let mut proof_streams = wallet.proof_stream(mint_quote.clone(), SplitTarget::default(), None);
  221. let offer = cln_client
  222. .get_bolt12_offer(Some(10_000), true, "hhhhhhhh".to_string())
  223. .await?;
  224. let _proofs = proof_streams.next().await.expect("payment")?;
  225. let quote = wallet.melt_bolt12_quote(offer.to_string(), None).await?;
  226. let melt = wallet.melt(&quote.id).await?;
  227. assert_eq!(melt.amount, 10.into());
  228. Ok(())
  229. }
  230. /// Tests security validation for BOLT12 minting to prevent overspending:
  231. /// - Creates a wallet and gets an open-ended BOLT12 quote
  232. /// - Makes a payment of 10,000 millisats
  233. /// - Attempts to mint more tokens (500 sats) than were actually paid for
  234. /// - Verifies that the mint correctly rejects the oversized mint request
  235. /// - Ensures proper error handling with TransactionUnbalanced error
  236. /// This test is crucial for ensuring the economic security of the minting process
  237. /// by preventing users from minting more tokens than they have paid for.
  238. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  239. async fn test_regtest_bolt12_mint_extra() -> Result<()> {
  240. let wallet = Wallet::new(
  241. &get_mint_url_from_env(),
  242. CurrencyUnit::Sat,
  243. Arc::new(memory::empty().await?),
  244. Mnemonic::generate(12)?.to_seed_normalized(""),
  245. None,
  246. )?;
  247. // Create a single-use BOLT12 quote
  248. let mint_quote = wallet.mint_bolt12_quote(None, None).await?;
  249. let state = wallet.mint_bolt12_quote_state(&mint_quote.id).await?;
  250. assert_eq!(state.amount_paid, Amount::ZERO);
  251. assert_eq!(state.amount_issued, Amount::ZERO);
  252. let active_keyset_id = wallet.fetch_active_keyset().await?.id;
  253. let pay_amount_msats = 10_000;
  254. let work_dir = get_test_temp_dir();
  255. let cln_one_dir = get_cln_dir(&work_dir, "one");
  256. let cln_client = create_cln_client_with_retry(cln_one_dir.clone()).await?;
  257. cln_client
  258. .pay_bolt12_offer(Some(pay_amount_msats), mint_quote.request.clone())
  259. .await?;
  260. let mut payment_streams = wallet.payment_stream(&mint_quote);
  261. let _ = payment_streams.next().await;
  262. let state = wallet.mint_bolt12_quote_state(&mint_quote.id).await?;
  263. assert_eq!(state.amount_paid, (pay_amount_msats / 1_000).into());
  264. assert_eq!(state.amount_issued, Amount::ZERO);
  265. let pre_mint = PreMintSecrets::random(active_keyset_id, 500.into(), &SplitTarget::None)?;
  266. let quote_info = wallet
  267. .localstore
  268. .get_mint_quote(&mint_quote.id)
  269. .await?
  270. .expect("there is a quote");
  271. let mut mint_request = MintRequest {
  272. quote: mint_quote.id,
  273. outputs: pre_mint.blinded_messages(),
  274. signature: None,
  275. };
  276. if let Some(secret_key) = quote_info.secret_key {
  277. mint_request.sign(secret_key)?;
  278. }
  279. let http_client = HttpClient::new(get_mint_url_from_env().parse().unwrap(), None);
  280. let response = http_client.post_mint(mint_request.clone()).await;
  281. match response {
  282. Err(err) => match err {
  283. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  284. err => {
  285. bail!("Wrong mint error returned: {}", err.to_string());
  286. }
  287. },
  288. Ok(_) => {
  289. bail!("Should not have allowed second payment");
  290. }
  291. }
  292. Ok(())
  293. }