bolt12.rs 12 KB

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