bolt12.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. use std::env;
  2. use std::path::PathBuf;
  3. use std::sync::Arc;
  4. use std::time::Duration;
  5. use anyhow::{bail, Result};
  6. use bip39::Mnemonic;
  7. use cashu::amount::SplitTarget;
  8. use cashu::nut23::Amountless;
  9. use cashu::{Amount, CurrencyUnit, MintRequest, PreMintSecrets, ProofsMethods};
  10. use cdk::wallet::{HttpClient, MintConnector, Wallet};
  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. wallet
  106. .wait_for_payment(&mint_quote, Duration::from_secs(60))
  107. .await?;
  108. wallet.mint_bolt12_quote_state(&mint_quote.id).await?;
  109. let proofs = wallet
  110. .mint_bolt12(&mint_quote.id, None, SplitTarget::default(), None)
  111. .await
  112. .unwrap();
  113. assert_eq!(proofs.total_amount().unwrap(), 10.into());
  114. cln_client
  115. .pay_bolt12_offer(Some(11_000), mint_quote.request.clone())
  116. .await
  117. .unwrap();
  118. wallet
  119. .wait_for_payment(&mint_quote, Duration::from_secs(60))
  120. .await?;
  121. wallet.mint_bolt12_quote_state(&mint_quote.id).await?;
  122. let proofs = wallet
  123. .mint_bolt12(&mint_quote.id, None, SplitTarget::default(), None)
  124. .await
  125. .unwrap();
  126. assert_eq!(proofs.total_amount().unwrap(), 11.into());
  127. Ok(())
  128. }
  129. /// Tests that multiple wallets can pay the same BOLT12 offer:
  130. /// - Creates a BOLT12 offer through CLN that both wallets will pay
  131. /// - Creates two separate wallets with different minting amounts
  132. /// - Has each wallet get their own quote and make payments
  133. /// - Verifies both wallets can successfully mint their tokens
  134. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  135. async fn test_regtest_bolt12_multiple_wallets() -> Result<()> {
  136. // Create first wallet
  137. let wallet_one = Wallet::new(
  138. &get_mint_url_from_env(),
  139. CurrencyUnit::Sat,
  140. Arc::new(memory::empty().await?),
  141. Mnemonic::generate(12)?.to_seed_normalized(""),
  142. None,
  143. )?;
  144. // Create second wallet
  145. let wallet_two = Wallet::new(
  146. &get_mint_url_from_env(),
  147. CurrencyUnit::Sat,
  148. Arc::new(memory::empty().await?),
  149. Mnemonic::generate(12)?.to_seed_normalized(""),
  150. None,
  151. )?;
  152. // Create a BOLT12 offer that both wallets will use
  153. let work_dir = get_test_temp_dir();
  154. let cln_one_dir = get_cln_dir(&work_dir, "one");
  155. let cln_client = create_cln_client_with_retry(cln_one_dir.clone()).await?;
  156. // First wallet payment
  157. let quote_one = wallet_one
  158. .mint_bolt12_quote(Some(10_000.into()), None)
  159. .await?;
  160. cln_client
  161. .pay_bolt12_offer(None, quote_one.request.clone())
  162. .await?;
  163. wallet_one
  164. .wait_for_payment(&quote_one, Duration::from_secs(60))
  165. .await?;
  166. let proofs_one = wallet_one
  167. .mint_bolt12(&quote_one.id, None, SplitTarget::default(), None)
  168. .await?;
  169. assert_eq!(proofs_one.total_amount()?, 10_000.into());
  170. // Second wallet payment
  171. let quote_two = wallet_two
  172. .mint_bolt12_quote(Some(15_000.into()), None)
  173. .await?;
  174. cln_client
  175. .pay_bolt12_offer(None, quote_two.request.clone())
  176. .await?;
  177. wallet_two
  178. .wait_for_payment(&quote_two, Duration::from_secs(60))
  179. .await?;
  180. let proofs_two = wallet_two
  181. .mint_bolt12(&quote_two.id, None, SplitTarget::default(), None)
  182. .await?;
  183. assert_eq!(proofs_two.total_amount()?, 15_000.into());
  184. let offer = cln_client
  185. .get_bolt12_offer(None, false, "test_multiple_wallets".to_string())
  186. .await?;
  187. let wallet_one_melt_quote = wallet_one
  188. .melt_bolt12_quote(
  189. offer.to_string(),
  190. Some(cashu::MeltOptions::Amountless {
  191. amountless: Amountless {
  192. amount_msat: 1500.into(),
  193. },
  194. }),
  195. )
  196. .await?;
  197. let wallet_two_melt_quote = wallet_two
  198. .melt_bolt12_quote(
  199. offer.to_string(),
  200. Some(cashu::MeltOptions::Amountless {
  201. amountless: Amountless {
  202. amount_msat: 1000.into(),
  203. },
  204. }),
  205. )
  206. .await?;
  207. let melted = wallet_one.melt(&wallet_one_melt_quote.id).await?;
  208. assert!(melted.preimage.is_some());
  209. let melted_two = wallet_two.melt(&wallet_two_melt_quote.id).await?;
  210. assert!(melted_two.preimage.is_some());
  211. Ok(())
  212. }
  213. /// Tests the BOLT12 melting (spending) functionality:
  214. /// - Creates a wallet and mints 20,000 sats using BOLT12
  215. /// - Creates a BOLT12 offer for 10,000 sats
  216. /// - Tests melting (spending) tokens using the BOLT12 offer
  217. /// - Verifies the correct amount is melted
  218. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  219. async fn test_regtest_bolt12_melt() -> Result<()> {
  220. let wallet = Wallet::new(
  221. &get_mint_url_from_env(),
  222. CurrencyUnit::Sat,
  223. Arc::new(memory::empty().await?),
  224. Mnemonic::generate(12)?.to_seed_normalized(""),
  225. None,
  226. )?;
  227. wallet.get_mint_info().await?;
  228. let mint_amount = Amount::from(20_000);
  229. // Create a single-use BOLT12 quote
  230. let mint_quote = wallet.mint_bolt12_quote(Some(mint_amount), None).await?;
  231. assert_eq!(mint_quote.amount, Some(mint_amount));
  232. // Pay the quote
  233. let work_dir = get_test_temp_dir();
  234. let cln_one_dir = get_cln_dir(&work_dir, "one");
  235. let cln_client = create_cln_client_with_retry(cln_one_dir.clone()).await?;
  236. cln_client
  237. .pay_bolt12_offer(None, mint_quote.request.clone())
  238. .await?;
  239. // Wait for payment to be processed
  240. wallet
  241. .wait_for_payment(&mint_quote, Duration::from_secs(60))
  242. .await?;
  243. let offer = cln_client
  244. .get_bolt12_offer(Some(10_000), true, "hhhhhhhh".to_string())
  245. .await?;
  246. let _proofs = wallet
  247. .mint_bolt12(&mint_quote.id, None, SplitTarget::default(), None)
  248. .await
  249. .unwrap();
  250. let quote = wallet.melt_bolt12_quote(offer.to_string(), None).await?;
  251. let melt = wallet.melt(&quote.id).await?;
  252. assert_eq!(melt.amount, 10.into());
  253. Ok(())
  254. }
  255. /// Tests security validation for BOLT12 minting to prevent overspending:
  256. /// - Creates a wallet and gets an open-ended BOLT12 quote
  257. /// - Makes a payment of 10,000 millisats
  258. /// - Attempts to mint more tokens (500 sats) than were actually paid for
  259. /// - Verifies that the mint correctly rejects the oversized mint request
  260. /// - Ensures proper error handling with TransactionUnbalanced error
  261. /// This test is crucial for ensuring the economic security of the minting process
  262. /// by preventing users from minting more tokens than they have paid for.
  263. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  264. async fn test_regtest_bolt12_mint_extra() -> Result<()> {
  265. let wallet = Wallet::new(
  266. &get_mint_url_from_env(),
  267. CurrencyUnit::Sat,
  268. Arc::new(memory::empty().await?),
  269. Mnemonic::generate(12)?.to_seed_normalized(""),
  270. None,
  271. )?;
  272. wallet.get_mint_info().await?;
  273. // Create a single-use BOLT12 quote
  274. let mint_quote = wallet.mint_bolt12_quote(None, None).await?;
  275. let state = wallet.mint_bolt12_quote_state(&mint_quote.id).await?;
  276. assert_eq!(state.amount_paid, Amount::ZERO);
  277. assert_eq!(state.amount_issued, Amount::ZERO);
  278. let active_keyset_id = wallet.fetch_active_keyset().await?.id;
  279. let pay_amount_msats = 10_000;
  280. let work_dir = get_test_temp_dir();
  281. let cln_one_dir = get_cln_dir(&work_dir, "one");
  282. let cln_client = create_cln_client_with_retry(cln_one_dir.clone()).await?;
  283. cln_client
  284. .pay_bolt12_offer(Some(pay_amount_msats), mint_quote.request.clone())
  285. .await?;
  286. wallet
  287. .wait_for_payment(&mint_quote, Duration::from_secs(10))
  288. .await?;
  289. let state = wallet.mint_bolt12_quote_state(&mint_quote.id).await?;
  290. assert_eq!(state.amount_paid, (pay_amount_msats / 1_000).into());
  291. assert_eq!(state.amount_issued, Amount::ZERO);
  292. let pre_mint = PreMintSecrets::random(active_keyset_id, 500.into(), &SplitTarget::None)?;
  293. let quote_info = wallet
  294. .localstore
  295. .get_mint_quote(&mint_quote.id)
  296. .await?
  297. .expect("there is a quote");
  298. let mut mint_request = MintRequest {
  299. quote: mint_quote.id,
  300. outputs: pre_mint.blinded_messages(),
  301. signature: None,
  302. };
  303. if let Some(secret_key) = quote_info.secret_key {
  304. mint_request.sign(secret_key)?;
  305. }
  306. let http_client = HttpClient::new(get_mint_url_from_env().parse().unwrap(), None);
  307. let response = http_client.post_mint(mint_request.clone()).await;
  308. match response {
  309. Err(err) => match err {
  310. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  311. err => {
  312. bail!("Wrong mint error returned: {}", err.to_string());
  313. }
  314. },
  315. Ok(_) => {
  316. bail!("Should not have allowed second payment");
  317. }
  318. }
  319. Ok(())
  320. }