ffi_minting_integration.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. //! FFI Minting Integration Tests
  2. //!
  3. //! These tests verify the FFI wallet minting functionality through the complete
  4. //! mint-to-tokens workflow, similar to the Swift bindings tests. The tests use
  5. //! the actual FFI layer to ensure compatibility with language bindings.
  6. //!
  7. //! The tests include:
  8. //! 1. Creating mint quotes through the FFI layer
  9. //! 2. Simulating payment for development/testing environments
  10. //! 3. Minting tokens and verifying amounts
  11. //! 4. Testing the complete quote state transitions
  12. //! 5. Validating proof generation and verification
  13. use std::env;
  14. use std::path::PathBuf;
  15. use std::str::FromStr;
  16. use std::time::Duration;
  17. use bip39::Mnemonic;
  18. use cdk_ffi::database::WalletSqliteDatabase;
  19. use cdk_ffi::types::{Amount, CurrencyUnit, QuoteState, SplitTarget};
  20. use cdk_ffi::wallet::Wallet as FfiWallet;
  21. use cdk_ffi::WalletConfig;
  22. use cdk_integration_tests::{get_mint_url_from_env, pay_if_regtest};
  23. use lightning_invoice::Bolt11Invoice;
  24. use tokio::time::timeout;
  25. // Helper function to get temp directory from environment or fallback
  26. fn get_test_temp_dir() -> PathBuf {
  27. match env::var("CDK_ITESTS_DIR") {
  28. Ok(dir) => PathBuf::from(dir),
  29. Err(_) => panic!("Unknown test dir"),
  30. }
  31. }
  32. /// Create a test FFI wallet with in-memory database
  33. async fn create_test_ffi_wallet() -> FfiWallet {
  34. let db = WalletSqliteDatabase::new_in_memory().expect("Failed to create in-memory database");
  35. let mnemonic = Mnemonic::generate(12).unwrap().to_string();
  36. let config = WalletConfig {
  37. target_proof_count: Some(3),
  38. };
  39. FfiWallet::new(
  40. get_mint_url_from_env(),
  41. CurrencyUnit::Sat,
  42. mnemonic,
  43. db,
  44. config,
  45. )
  46. .expect("Failed to create FFI wallet")
  47. }
  48. /// Tests the complete FFI minting flow from quote creation to token minting
  49. ///
  50. /// This test replicates the Swift integration test functionality:
  51. /// 1. Creates an FFI wallet with in-memory database
  52. /// 2. Creates a mint quote for 1000 sats
  53. /// 3. Verifies the quote properties (amount, state, expiry)
  54. /// 4. Simulates payment in test environments
  55. /// 5. Mints tokens using the paid quote
  56. /// 6. Verifies the minted proofs have the correct total amount
  57. /// 7. Validates the wallet balance after minting
  58. ///
  59. /// This ensures the FFI layer properly handles the complete minting workflow
  60. /// that language bindings (Swift, Python, Kotlin) will use.
  61. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  62. async fn test_ffi_full_minting_flow() {
  63. let wallet = create_test_ffi_wallet().await;
  64. // Verify initial wallet state
  65. let initial_balance = wallet
  66. .total_balance()
  67. .await
  68. .expect("Failed to get initial balance");
  69. assert_eq!(initial_balance.value, 0, "Initial balance should be zero");
  70. // Test minting amount (1000 sats, matching Swift test)
  71. let mint_amount = Amount::new(1000);
  72. // Step 1: Create a mint quote
  73. let quote = wallet
  74. .mint_quote(mint_amount, Some("FFI Integration Test".to_string()))
  75. .await
  76. .expect("Failed to create mint quote");
  77. // Verify quote properties
  78. assert_eq!(
  79. quote.amount,
  80. Some(mint_amount),
  81. "Quote amount should match requested amount"
  82. );
  83. assert_eq!(quote.unit, CurrencyUnit::Sat, "Quote unit should be sats");
  84. assert_eq!(
  85. quote.state,
  86. QuoteState::Unpaid,
  87. "Initial quote state should be unpaid"
  88. );
  89. assert!(
  90. !quote.request.is_empty(),
  91. "Quote should have a payment request"
  92. );
  93. assert!(!quote.id.is_empty(), "Quote should have an ID");
  94. // Verify the quote can be parsed as a valid invoice
  95. let invoice = Bolt11Invoice::from_str(&quote.request)
  96. .expect("Quote request should be a valid Lightning invoice");
  97. // In test environments, simulate payment
  98. pay_if_regtest(&get_test_temp_dir(), &invoice)
  99. .await
  100. .expect("Failed to pay invoice in test environment");
  101. // Give the mint time to process the payment in test environments
  102. tokio::time::sleep(Duration::from_millis(1000)).await;
  103. // Step 2: Wait for payment and mint tokens
  104. // We'll use a timeout to avoid hanging in case of issues
  105. let mint_result = timeout(Duration::from_secs(30), async {
  106. // Keep checking quote status until it's paid, then mint
  107. let mut attempts = 0;
  108. let max_attempts = 10;
  109. loop {
  110. attempts += 1;
  111. if attempts > max_attempts {
  112. panic!(
  113. "Quote never transitioned to paid state after {} attempts",
  114. max_attempts
  115. );
  116. }
  117. // In a real scenario, we'd check quote status, but for integration tests
  118. // we'll try to mint directly and handle any errors
  119. match wallet.mint(quote.id.clone(), SplitTarget::None, None).await {
  120. Ok(proofs) => break proofs,
  121. Err(e) => {
  122. // If quote isn't paid yet, wait and retry
  123. if e.to_string().contains("quote not paid") || e.to_string().contains("unpaid")
  124. {
  125. tokio::time::sleep(Duration::from_millis(2000)).await;
  126. continue;
  127. } else {
  128. panic!("Unexpected error while minting: {}", e);
  129. }
  130. }
  131. }
  132. }
  133. })
  134. .await
  135. .expect("Timeout waiting for minting to complete");
  136. // Step 3: Verify minted proofs
  137. assert!(
  138. !mint_result.is_empty(),
  139. "Should have minted at least one proof"
  140. );
  141. // Calculate total amount of minted proofs
  142. let total_minted: u64 = mint_result.iter().map(|proof| proof.amount().value).sum();
  143. assert_eq!(
  144. total_minted, mint_amount.value,
  145. "Total minted amount should equal requested amount"
  146. );
  147. // Verify each proof has valid properties
  148. for proof in &mint_result {
  149. assert!(
  150. proof.amount().value > 0,
  151. "Each proof should have positive amount"
  152. );
  153. assert!(
  154. !proof.secret().is_empty(),
  155. "Each proof should have a secret"
  156. );
  157. assert!(!proof.c().is_empty(), "Each proof should have a C value");
  158. }
  159. // Step 4: Verify wallet balance after minting
  160. let final_balance = wallet
  161. .total_balance()
  162. .await
  163. .expect("Failed to get final balance");
  164. assert_eq!(
  165. final_balance.value, mint_amount.value,
  166. "Final wallet balance should equal minted amount"
  167. );
  168. println!(
  169. "✅ FFI minting test completed successfully: minted {} sats in {} proofs",
  170. total_minted,
  171. mint_result.len()
  172. );
  173. }
  174. /// Tests FFI wallet quote creation and validation
  175. ///
  176. /// This test focuses on the quote creation aspects:
  177. /// 1. Creates quotes for different amounts
  178. /// 2. Verifies quote properties and validation
  179. /// 3. Tests quote serialization/deserialization
  180. /// 4. Ensures quotes have proper expiry times
  181. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  182. async fn test_ffi_mint_quote_creation() {
  183. let wallet = create_test_ffi_wallet().await;
  184. // Test different quote amounts
  185. let test_amounts = vec![100, 500, 1000, 2100]; // Including amount that requires split
  186. for amount_value in test_amounts {
  187. let amount = Amount::new(amount_value);
  188. let description = format!("Test quote for {} sats", amount_value);
  189. let quote = wallet
  190. .mint_quote(amount, Some(description.clone()))
  191. .await
  192. .expect(&format!("Failed to create quote for {} sats", amount_value));
  193. // Verify quote properties
  194. assert_eq!(quote.amount, Some(amount));
  195. assert_eq!(quote.unit, CurrencyUnit::Sat);
  196. assert_eq!(quote.state, QuoteState::Unpaid);
  197. assert!(!quote.id.is_empty());
  198. assert!(!quote.request.is_empty());
  199. // Verify the payment request is a valid Lightning invoice
  200. let invoice = Bolt11Invoice::from_str(&quote.request)
  201. .expect("Quote request should be a valid Lightning invoice");
  202. // The invoice amount should match the quote amount (in millisats)
  203. assert_eq!(
  204. invoice.amount_milli_satoshis(),
  205. Some(amount_value * 1000),
  206. "Invoice amount should match quote amount"
  207. );
  208. // Test quote JSON serialization (useful for bindings that need JSON)
  209. let quote_json = quote.to_json().expect("Quote should serialize to JSON");
  210. assert!(!quote_json.is_empty(), "Quote JSON should not be empty");
  211. println!(
  212. "✅ Quote created for {} sats: ID={}, Invoice amount={}msat",
  213. amount_value,
  214. quote.id,
  215. invoice.amount_milli_satoshis().unwrap_or(0)
  216. );
  217. }
  218. }
  219. /// Tests error handling in FFI minting operations
  220. ///
  221. /// This test verifies proper error handling:
  222. /// 1. Invalid mint URLs
  223. /// 2. Invalid amounts (zero, too large)
  224. /// 3. Attempting to mint unpaid quotes
  225. /// 4. Network connectivity issues
  226. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  227. async fn test_ffi_minting_error_handling() {
  228. // Test invalid mint URL
  229. let db = WalletSqliteDatabase::new_in_memory().expect("Failed to create database");
  230. let mnemonic = Mnemonic::generate(12).unwrap().to_string();
  231. let config = WalletConfig {
  232. target_proof_count: Some(3),
  233. };
  234. let invalid_wallet_result = FfiWallet::new(
  235. "invalid-url".to_string(),
  236. CurrencyUnit::Sat,
  237. mnemonic.clone(),
  238. db,
  239. config.clone(),
  240. );
  241. assert!(
  242. invalid_wallet_result.is_err(),
  243. "Should fail to create wallet with invalid URL"
  244. );
  245. // Test with valid wallet for other error cases
  246. let wallet = create_test_ffi_wallet().await;
  247. // Test zero amount quote (should fail)
  248. let zero_amount_result = wallet.mint_quote(Amount::new(0), None).await;
  249. assert!(
  250. zero_amount_result.is_err(),
  251. "Should fail to create quote with zero amount"
  252. );
  253. // Test minting with non-existent quote ID
  254. let invalid_mint_result = wallet
  255. .mint("non-existent-quote-id".to_string(), SplitTarget::None, None)
  256. .await;
  257. assert!(
  258. invalid_mint_result.is_err(),
  259. "Should fail to mint with non-existent quote ID"
  260. );
  261. println!("✅ Error handling tests completed successfully");
  262. }
  263. /// Tests FFI wallet configuration options
  264. ///
  265. /// This test verifies different wallet configurations:
  266. /// 1. Different target proof counts
  267. /// 2. Different currency units (if supported)
  268. /// 3. Wallet restoration with same mnemonic
  269. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  270. async fn test_ffi_wallet_configuration() {
  271. let mint_url = get_mint_url_from_env();
  272. let mnemonic = Mnemonic::generate(12).unwrap().to_string();
  273. // Test different target proof counts
  274. let proof_counts = vec![1, 3, 5, 10];
  275. for target_count in proof_counts {
  276. let db = WalletSqliteDatabase::new_in_memory().expect("Failed to create database");
  277. let config = WalletConfig {
  278. target_proof_count: Some(target_count),
  279. };
  280. let wallet = FfiWallet::new(
  281. mint_url.clone(),
  282. CurrencyUnit::Sat,
  283. mnemonic.clone(),
  284. db,
  285. config,
  286. )
  287. .expect("Failed to create wallet");
  288. // Verify wallet properties
  289. assert_eq!(wallet.mint_url().url, mint_url);
  290. assert_eq!(wallet.unit(), CurrencyUnit::Sat);
  291. println!(
  292. "✅ Wallet created with target proof count: {}",
  293. target_count
  294. );
  295. }
  296. // Test wallet restoration with same mnemonic
  297. let db1 = WalletSqliteDatabase::new_in_memory().expect("Failed to create database");
  298. let db2 = WalletSqliteDatabase::new_in_memory().expect("Failed to create database");
  299. let config = WalletConfig {
  300. target_proof_count: Some(3),
  301. };
  302. let wallet1 = FfiWallet::new(
  303. mint_url.clone(),
  304. CurrencyUnit::Sat,
  305. mnemonic.clone(),
  306. db1,
  307. config.clone(),
  308. )
  309. .expect("Failed to create first wallet");
  310. let wallet2 = FfiWallet::new(mint_url, CurrencyUnit::Sat, mnemonic, db2, config)
  311. .expect("Failed to create second wallet");
  312. // Both wallets should have the same mint URL and unit
  313. assert_eq!(wallet1.mint_url().url, wallet2.mint_url().url);
  314. assert_eq!(wallet1.unit(), wallet2.unit());
  315. println!("✅ Wallet configuration tests completed successfully");
  316. }