From d8b4c207b882794109aafe582837da790292e07a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sun, 22 Nov 2026 03:54:04 +0100 Subject: [PATCH 1/2] test: remove blocktank staging tests Blocktank staging now requires an auth key that only the app repositories' CI has, so the tests calling the live staging API cannot pass here. Removes the 12 tests that call Blocktank over the network (info fetch, order and CJIT creation and refresh, fee estimates, regtest mine and deposit) and the STAGING_SERVER constant. The offline DB, model and liquidity tests stay and now build the client with the default URL, which they never call. Verified: cargo build --locked, cargo clippy --locked --all-targets, cargo test --locked --- src/modules/blocktank/tests.rs | 832 +-------------------------------- 1 file changed, 13 insertions(+), 819 deletions(-) diff --git a/src/modules/blocktank/tests.rs b/src/modules/blocktank/tests.rs index 27193362..013b441d 100644 --- a/src/modules/blocktank/tests.rs +++ b/src/modules/blocktank/tests.rs @@ -1,12 +1,7 @@ -//const STAGING_SERVER: &str = "https://api1.blocktank.to/api"; -//const STAGING_SERVER: &str = "https://api.stag.blocktank.to/api"; -const STAGING_SERVER: &str = "https://api.stag0.blocktank.to/blocktank/api/v2"; - #[cfg(test)] mod tests { #![allow(clippy::print_stdout)] - use super::*; use crate::modules::blocktank::liquidity::{ calculate_channel_liquidity_options, get_default_lsp_balance, ChannelLiquidityParams, DefaultLspBalanceParams, @@ -17,9 +12,7 @@ mod tests { #[tokio::test] async fn test_upsert_info() { // Initialize in-memory database - let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) - .await - .unwrap(); + let db = BlocktankDB::new(":memory:", None).await.unwrap(); // Create test data let test_info = IBtInfo { @@ -110,58 +103,6 @@ mod tests { } // Lock is dropped here } - #[tokio::test] - async fn test_fetch_and_store_info() { - // Initialize in-memory database - let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) - .await - .unwrap(); - - // Test fetch and store - let result = db.fetch_and_store_info().await; - assert!( - result.is_ok(), - "Failed to fetch and store info: {:?}", - result.err() - ); - - let info = result.unwrap(); - - // Verify the stored info matches what was returned - { - let conn = db.conn.lock().await; - - // Verify version is stored - let row = conn - .query_row( - "SELECT version, is_current FROM info WHERE version = ?1", - [info.version], - |row| Ok((row.get::<_, u32>(0)?, row.get::<_, bool>(1)?)), - ) - .unwrap(); - assert_eq!(row.0, info.version); - assert_eq!(row.1, true); - - // Verify JSON data - let nodes_json: String = conn - .query_row( - "SELECT nodes FROM info WHERE version = ?1", - [info.version], - |row| row.get(0), - ) - .unwrap(); - - let stored_nodes: Vec = serde_json::from_str(&nodes_json).unwrap(); - assert_eq!(stored_nodes.len(), info.nodes.len()); - - // Compare first node's data if any exist - if !info.nodes.is_empty() { - assert_eq!(stored_nodes[0].alias, info.nodes[0].alias); - assert_eq!(stored_nodes[0].pubkey, info.nodes[0].pubkey); - } - } - } - #[tokio::test] async fn test_fetch_and_store_info_error_handling() { // Initialize with invalid URL to test error handling @@ -193,9 +134,7 @@ mod tests { #[tokio::test] async fn test_get_info() { // Initialize in-memory database - let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) - .await - .unwrap(); + let db = BlocktankDB::new(":memory:", None).await.unwrap(); // Should return None when no info exists let empty_result = db.get_info().await.unwrap(); @@ -257,9 +196,7 @@ mod tests { #[tokio::test] async fn test_upsert_order() { - let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) - .await - .unwrap(); + let db = BlocktankDB::new(":memory:", None).await.unwrap(); // Get current timestamp in ISO 8601 format let now = chrono::Utc::now(); @@ -386,9 +323,7 @@ mod tests { #[tokio::test] async fn test_upsert_orders() { - let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) - .await - .unwrap(); + let db = BlocktankDB::new(":memory:", None).await.unwrap(); // Create multiple test orders let mut orders = Vec::new(); @@ -479,9 +414,7 @@ mod tests { #[tokio::test] async fn test_upsert_orders_empty() { - let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) - .await - .unwrap(); + let db = BlocktankDB::new(":memory:", None).await.unwrap(); // Test with empty vector let result = db.upsert_orders(&[]).await; @@ -494,9 +427,7 @@ mod tests { #[tokio::test] async fn test_upsert_orders_large_batch() { - let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) - .await - .unwrap(); + let db = BlocktankDB::new(":memory:", None).await.unwrap(); // Create a larger batch of orders to test performance let mut orders = Vec::new(); @@ -533,147 +464,9 @@ mod tests { println!("Bulk insert of 50 orders took: {:?}", bulk_duration); } - #[tokio::test] - async fn test_create_and_store_order() { - let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) - .await - .unwrap(); - - let options = CreateOrderOptions { - coupon_code: "".to_string(), - zero_conf: true, - zero_reserve: false, - announce_channel: false, - ..Default::default() - }; - - let result = db.create_and_store_order(100000, 4, Some(options)).await; - assert!( - result.is_ok(), - "Failed to create and store order: {:?}", - result.err() - ); - - let order = result.unwrap(); - assert_eq!(order.lsp_balance_sat, 100000); - assert_eq!(order.client_balance_sat, 0); - } - - #[tokio::test] - async fn test_refresh_orders() { - // Initialize in-memory database - let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) - .await - .unwrap(); - - // Create actual orders through the API - let options = CreateOrderOptions { - client_balance_sat: 0, - coupon_code: "".to_string(), - zero_conf: true, - zero_reserve: false, - announce_channel: false, - ..Default::default() - }; - - // Create two real orders - println!("Creating first test order..."); - let order1 = db - .create_and_store_order(100000, 4, Some(options.clone())) - .await - .expect("Failed to create first order"); - - println!("First order created with ID: {}", order1.id); - - // Add a small delay between order creations - tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; - - println!("Creating second test order..."); - let order2 = db - .create_and_store_order(150000, 4, Some(options.clone())) - .await - .expect("Failed to create second order"); - - println!("Second order created with ID: {}", order2.id); - - // Add a small delay before refreshing - tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; - - // Test refreshing orders - let order_ids = vec![order1.id.clone(), order2.id.clone()]; - println!("Attempting to refresh orders with IDs: {:?}", order_ids); - - let result = db.refresh_orders(&order_ids).await; - - match result { - Ok(refreshed_orders) => { - assert_eq!(refreshed_orders.len(), 2, "Should have refreshed 2 orders"); - - // Verify each refreshed order - let mut found_order1 = false; - let mut found_order2 = false; - - for order in &refreshed_orders { - println!("Checking refreshed order: {}", order.id); - - if order.id == order1.id { - found_order1 = true; - assert_eq!(order.lsp_balance_sat, 100000); - assert_eq!(order.client_balance_sat, 0); - } else if order.id == order2.id { - found_order2 = true; - assert_eq!(order.lsp_balance_sat, 150000); - assert_eq!(order.client_balance_sat, 0); - } - - // Verify database state - let conn = db.conn.lock().await; - let row = conn - .query_row( - "SELECT id, state, fee_sat FROM orders WHERE id = ?1", - [&order.id], - |row| { - Ok(( - row.get::<_, String>(0)?, - row.get::<_, String>(1)?, - row.get::<_, u64>(2)?, - )) - }, - ) - .unwrap(); - - assert_eq!(row.0, order.id); - assert_eq!(row.1, format!("{:?}", order.state)); - assert_eq!(row.2, order.fee_sat); - } - - assert!(found_order1, "First order not found in refreshed orders"); - assert!(found_order2, "Second order not found in refreshed orders"); - } - Err(e) => panic!("Failed to refresh orders: {:?}", e), - } - - // Test error handling with invalid order IDs - let invalid_ids = vec!["invalid_id_1".to_string()]; - let error_result = db.refresh_orders(&invalid_ids).await; - assert!( - error_result.is_err(), - "Expected error for invalid order IDs" - ); - - match error_result { - Err(BlocktankError::DataError { error_details }) => { - assert!(error_details.contains("Failed to fetch orders")); - } - _ => panic!("Expected DataError"), - } - } - #[tokio::test] async fn test_get_orders() { - let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) - .await - .unwrap(); + let db = BlocktankDB::new(":memory:", None).await.unwrap(); // Get current timestamp and future timestamp as integers let now = chrono::Utc::now(); @@ -829,9 +622,7 @@ mod tests { #[tokio::test] async fn test_get_active_orders() { - let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) - .await - .unwrap(); + let db = BlocktankDB::new(":memory:", None).await.unwrap(); // Get current timestamp and future timestamp let now = chrono::Utc::now(); @@ -956,293 +747,9 @@ mod tests { } } - #[tokio::test] - async fn test_refresh_active_orders() { - // Initialize in-memory database - let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) - .await - .unwrap(); - - // Create test orders with different states - let options = CreateOrderOptions { - client_balance_sat: 0, - coupon_code: "".to_string(), - zero_conf: true, - zero_reserve: false, - announce_channel: false, - ..Default::default() - }; - - // Create orders that should be active (Created and Paid states) - println!("Creating first test order (Created state)..."); - let order1 = db - .create_and_store_order(100000, 4, Some(options.clone())) - .await - .expect("Failed to create first order"); - println!("First order created with ID: {}", order1.id); - - // Add a small delay between order creations - tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; - - println!("Creating second test order (will be set to Paid state)..."); - let order2 = db - .create_and_store_order(150000, 4, Some(options.clone())) - .await - .expect("Failed to create second order"); - println!("Second order created with ID: {}", order2.id); - - // Add a small delay before refreshing - tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; - - // Test refreshing active orders - println!("Testing refresh_active_orders..."); - let result = db.refresh_active_orders().await; - - match result { - Ok(refreshed_orders) => { - assert_eq!( - refreshed_orders.len(), - 2, - "Should have refreshed 2 active orders" - ); - - // Verify each refreshed order - let mut found_order1 = false; - let mut found_order2 = false; - - for order in &refreshed_orders { - println!("Checking refreshed order: {}", order.id); - - if order.id == order1.id { - found_order1 = true; - assert_eq!(order.lsp_balance_sat, 100000); - assert_eq!(order.client_balance_sat, 0); - assert!(matches!(order.state2, Some(BtOrderState2::Created))); - } else if order.id == order2.id { - found_order2 = true; - assert_eq!(order.lsp_balance_sat, 150000); - assert_eq!(order.client_balance_sat, 0); - } - - // Verify order is in an active state - assert!( - matches!( - order.state2, - Some(BtOrderState2::Created) | Some(BtOrderState2::Paid) - ), - "Order should be in Created or Paid state" - ); - } - - assert!(found_order1, "First order not found in refreshed orders"); - assert!(found_order2, "Second order not found in refreshed orders"); - - // Verify database state - let conn = db.conn.lock().await; - for order in &refreshed_orders { - let row = conn - .query_row( - "SELECT id, state2, fee_sat FROM orders WHERE id = ?1", - [&order.id], - |row| { - Ok(( - row.get::<_, String>(0)?, - row.get::<_, String>(1)?, - row.get::<_, u64>(2)?, - )) - }, - ) - .unwrap(); - - assert_eq!(row.0, order.id); - assert!( - row.1 == "Created" || row.1 == "Paid", - "Database order state should be Created or Paid" - ); - } - } - Err(e) => panic!("Failed to refresh active orders: {:?}", e), - } - - // Test with no active orders - // First, expire all orders to make them inactive - let conn = db.conn.lock().await; - conn.execute("UPDATE orders SET state2 = 'Expired'", []) - .unwrap(); - drop(conn); // Release the lock - - // Now test refresh_active_orders with no active orders - let empty_result = db.refresh_active_orders().await.unwrap(); - assert_eq!( - empty_result.len(), - 0, - "Should return empty vec when no active orders exist" - ); - } - - #[tokio::test] - async fn test_get_min_zero_conf_tx_fee() { - let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) - .await - .unwrap(); - - // First create an order to get a valid order ID - let options = CreateOrderOptions { - client_balance_sat: 0, - coupon_code: "".to_string(), - zero_conf: true, - zero_reserve: false, - announce_channel: false, - ..Default::default() - }; - - println!("Creating test order..."); - let order = db - .create_and_store_order(100000, 4, Some(options)) - .await - .expect("Failed to create order"); - - println!("Order created with ID: {}", order.id); - - // Test getting min zero conf fee - let result = db.get_min_zero_conf_tx_fee(order.id).await; - assert!( - result.is_ok(), - "Failed to get min zero conf fee: {:?}", - result.err() - ); - - let fee_window = result.unwrap(); - assert!( - fee_window.sat_per_vbyte > 0.0, - "sat_per_vbyte should be greater than 0" - ); - assert!( - !fee_window.validity_ends_at.is_empty(), - "validity_ends_at should not be empty" - ); - - // Test with invalid order ID - let error_result = db.get_min_zero_conf_tx_fee("invalid_id".to_string()).await; - assert!(error_result.is_err(), "Expected error for invalid order ID"); - - match error_result { - Err(BlocktankError::DataError { error_details }) => { - assert!(error_details.contains("Failed to get minimum zero-conf transaction fee")); - } - _ => panic!("Expected DataError"), - } - } - - #[tokio::test] - async fn test_estimate_order_fee() { - let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) - .await - .unwrap(); - - let options = Some(CreateOrderOptions { - client_balance_sat: 0, - coupon_code: "".to_string(), - zero_conf: true, - zero_reserve: false, - announce_channel: false, - ..Default::default() - }); - - // Test valid estimation - let result = db.estimate_order_fee(100000, 4, options.clone()).await; - assert!( - result.is_ok(), - "Failed to estimate order fee: {:?}", - result.err() - ); - - let fee_estimate = result.unwrap(); - assert!( - fee_estimate.fee_sat > 0, - "Fee estimate should be greater than 0" - ); - assert!( - fee_estimate.min_0_conf_tx_fee.sat_per_vbyte > 0.0, - "min_0_conf_tx_fee.sat_per_vbyte should be greater than 0" - ); - - // Test with invalid parameters - let error_result = db.estimate_order_fee(0, 0, None).await; - assert!( - error_result.is_err(), - "Expected error for invalid parameters" - ); - - match error_result { - Err(BlocktankError::DataError { error_details }) => { - assert!(error_details.contains("Failed to estimate order fee")); - } - _ => panic!("Expected DataError"), - } - } - - #[tokio::test] - async fn test_estimate_order_fee_full() { - let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) - .await - .unwrap(); - - let options = Some(CreateOrderOptions { - client_balance_sat: 20000, - coupon_code: "".to_string(), - zero_conf: true, - zero_reserve: false, - announce_channel: false, - ..Default::default() - }); - - // Test valid full estimation - let result = db.estimate_order_fee_full(100000, 4, options.clone()).await; - assert!( - result.is_ok(), - "Failed to estimate full order fee: {:?}", - result.err() - ); - - let fee_estimate = result.unwrap(); - assert!( - fee_estimate.fee_sat > 0, - "Fee estimate should be greater than 0" - ); - assert!( - fee_estimate.network_fee_sat > 0, - "Network fee should be greater than 0" - ); - assert!( - fee_estimate.service_fee_sat > 0, - "Service fee should be greater than 0" - ); - assert!( - fee_estimate.min_0_conf_tx_fee.sat_per_vbyte > 0.0, - "min_0_conf_tx_fee.sat_per_vbyte should be greater than 0" - ); - - // Test with invalid parameters - let error_result = db.estimate_order_fee_full(0, 0, None).await; - assert!( - error_result.is_err(), - "Expected error for invalid parameters" - ); - - match error_result { - Err(BlocktankError::DataError { error_details }) => { - assert!(error_details.contains("Failed to estimate full order fee")); - } - _ => panic!("Expected DataError"), - } - } - #[tokio::test] async fn test_upsert_cjit_entry() { - let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) - .await - .unwrap(); + let db = BlocktankDB::new(":memory:", None).await.unwrap(); // Get current timestamp in ISO 8601 format let now = chrono::Utc::now(); @@ -1353,9 +860,7 @@ mod tests { #[tokio::test] async fn test_upsert_cjit_entries() { - let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) - .await - .unwrap(); + let db = BlocktankDB::new(":memory:", None).await.unwrap(); // Create multiple test CJIT entries let mut entries = Vec::new(); @@ -1443,9 +948,7 @@ mod tests { #[tokio::test] async fn test_upsert_cjit_entries_empty() { - let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) - .await - .unwrap(); + let db = BlocktankDB::new(":memory:", None).await.unwrap(); // Test with empty vector let result = db.upsert_cjit_entries(&[]).await; @@ -1458,9 +961,7 @@ mod tests { #[tokio::test] async fn test_get_cjit_entries() { - let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) - .await - .unwrap(); + let db = BlocktankDB::new(":memory:", None).await.unwrap(); // Get current timestamp and future timestamp let now = chrono::Utc::now(); @@ -1589,159 +1090,9 @@ mod tests { assert_eq!(specific_entry.source, test_entry1.source); } - #[tokio::test] - async fn test_cjit_entry_integration() { - // Initialize database with staging server - let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) - .await - .unwrap(); - - // Create a test CJIT entry - let options = Some(CreateCjitOptions { - source: Some("integration_test".to_string()), - discount_code: None, - }); - - println!("Creating CJIT entry..."); - let channel_size_sat = 100000; // 100k sats - let invoice_sat = 20000; // 20k sats - let invoice_description = "Integration test CJIT entry"; - let node_id = "03c8533232c155c41c42e5a8f8487b192dd36f1d354b86ef461cc82e67e3388839"; // Example node ID - let channel_expiry_weeks = 4; - - let result = db - .create_cjit_entry( - channel_size_sat, - invoice_sat, - invoice_description, - node_id, - channel_expiry_weeks, - options.clone(), - ) - .await; - - // Verify creation was successful - assert!( - result.is_ok(), - "Failed to create CJIT entry: {:?}", - result.err() - ); - let cjit_entry = result.unwrap(); - - println!("Created CJIT entry with ID: {}", cjit_entry.id); - - // Verify the entry properties - assert_eq!(cjit_entry.channel_size_sat, channel_size_sat); - assert_eq!(cjit_entry.channel_expiry_weeks, channel_expiry_weeks); - assert_eq!(cjit_entry.node_id, node_id); - assert_eq!(cjit_entry.state, CJitStateEnum::Created); - assert!(cjit_entry.fee_sat > 0); - assert!(cjit_entry.network_fee_sat > 0); - assert!(cjit_entry.service_fee_sat > 0); - - // Verify the invoice - assert_eq!(cjit_entry.invoice.state, BtBolt11InvoiceState::Pending); - assert!(!cjit_entry.invoice.request.is_empty()); - - // Verify source was set correctly - assert_eq!(cjit_entry.source, Some("integration_test".to_string())); - - // Test fetching the created entry - let fetched_entries = db - .get_cjit_entries(Some(&vec![cjit_entry.id.clone()]), None) - .await - .unwrap(); - - assert_eq!( - fetched_entries.len(), - 1, - "Should retrieve exactly one entry" - ); - let fetched_entry = &fetched_entries[0]; - - // Verify fetched entry matches created entry - assert_eq!(fetched_entry.id, cjit_entry.id); - assert_eq!(fetched_entry.channel_size_sat, channel_size_sat); - assert_eq!(fetched_entry.channel_expiry_weeks, channel_expiry_weeks); - assert_eq!(fetched_entry.node_id, node_id); - assert_eq!(fetched_entry.state, CJitStateEnum::Created); - - // Test filtering by state - let created_entries = db - .get_cjit_entries(None, Some(CJitStateEnum::Created)) - .await - .unwrap(); - assert!( - created_entries.iter().any(|e| e.id == cjit_entry.id), - "Should find the entry when filtering by Created state" - ); - - // Verify no entries in other states - let completed_entries = db - .get_cjit_entries(None, Some(CJitStateEnum::Completed)) - .await - .unwrap(); - assert!( - !completed_entries.iter().any(|e| e.id == cjit_entry.id), - "Should not find the entry when filtering by Completed state" - ); - - println!("CJIT entry integration test completed successfully"); - } - - #[tokio::test] - async fn test_cjit_entry_invalid_params() { - let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) - .await - .unwrap(); - - // Test with invalid channel size (too small) - let result = db - .create_cjit_entry( - 1000, // Very small channel size - 100, - "Test invalid channel size", - "03c8533232c155c41c42e5a8f8487b192dd36f1d354b86ef461cc82e67e3388839", - 4, - None, - ) - .await; - assert!(result.is_err(), "Should fail with too small channel size"); - - // Test with invalid node ID - let result = db - .create_cjit_entry( - 100000, - 1000, - "Test invalid node ID", - "invalid_node_id", - 4, - None, - ) - .await; - assert!(result.is_err(), "Should fail with invalid node ID"); - - // Test with invalid expiry weeks (too long) - let result = db - .create_cjit_entry( - 100000, - 1000, - "Test invalid expiry", - "03c8533232c155c41c42e5a8f8487b192dd36f1d354b86ef461cc82e67e3388839", - 100, // Too many weeks - None, - ) - .await; - assert!(result.is_err(), "Should fail with too many expiry weeks"); - - println!("CJIT entry invalid parameters test completed successfully"); - } - #[tokio::test] async fn test_get_active_cjit_entries() { - let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) - .await - .unwrap(); + let db = BlocktankDB::new(":memory:", None).await.unwrap(); // Get current timestamp and future timestamp let now = chrono::Utc::now(); @@ -1872,163 +1223,6 @@ mod tests { ); } - #[tokio::test] - async fn test_refresh_active_cjit_entries() { - // Initialize database with staging server - let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) - .await - .unwrap(); - - let options = Some(CreateCjitOptions { - source: Some("integration_test".to_string()), - discount_code: None, - }); - - // Create two test entries that will start in Created state - println!("Creating first test CJIT entry..."); - let entry1 = db - .create_cjit_entry( - 100000, // channel_size_sat - 20000, // invoice_sat - "Test CJIT 1", // description - "03c8533232c155c41c42e5a8f8487b192dd36f1d354b86ef461cc82e67e3388839", // node_id - 4, // channel_expiry_weeks - options.clone(), - ) - .await - .expect("Failed to create first CJIT entry"); - println!("First CJIT entry created with ID: {}", entry1.id); - - // Add a small delay between entry creations - tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; - - println!("Creating second test CJIT entry..."); - let entry2 = db - .create_cjit_entry( - 150000, // channel_size_sat - 30000, // invoice_sat - "Test CJIT 2", // description - "03c8533232c155c41c42e5a8f8487b192dd36f1d354b86ef461cc82e67e3388839", // node_id - 4, // channel_expiry_weeks - options.clone(), - ) - .await - .expect("Failed to create second CJIT entry"); - println!("Second CJIT entry created with ID: {}", entry2.id); - - // Test refreshing active CJIT entries - println!("Testing refresh_active_cjit_entries..."); - let result = db.refresh_active_cjit_entries().await; - - match result { - Ok(refreshed_entries) => { - // Verify we got entries back - assert!( - !refreshed_entries.is_empty(), - "Should have received refreshed entries" - ); - - // All refreshed entries should be in an active state - for entry in &refreshed_entries { - println!("Checking refreshed entry: {}", entry.id); - assert!( - matches!(entry.state, CJitStateEnum::Created | CJitStateEnum::Failed), - "Entry {} should be in Created or Failed state, but was in {:?} state", - entry.id, - entry.state - ); - - // Verify the basic entry properties are preserved - if entry.id == entry1.id { - assert_eq!(entry.channel_size_sat, 100000); - } else if entry.id == entry2.id { - assert_eq!(entry.channel_size_sat, 150000); - } - - // Verify LSP node data is loaded correctly - assert!(!entry.lsp_node.pubkey.is_empty()); - assert!(!entry.lsp_node.connection_strings.is_empty()); - } - - // Verify database state - let conn = db.conn.lock().await; - for entry in &refreshed_entries { - let row = conn - .query_row( - "SELECT id FROM cjit_entries WHERE id = ?1", - [&entry.id], - |row| Ok(row.get::<_, String>(0)?), - ) - .unwrap(); - - assert_eq!(row, entry.id); - } - } - Err(e) => panic!("Failed to refresh active CJIT entries: {:?}", e), - } - - // Test with no active entries by manually marking all entries as completed in the database - { - let conn = db.conn.lock().await; - conn.execute("UPDATE cjit_entries SET state = 'Completed'", []) - .unwrap(); - } - - // Now test refresh_active_cjit_entries with no active entries - let empty_result = db.refresh_active_cjit_entries().await.unwrap(); - assert_eq!( - empty_result.len(), - 0, - "Should return empty vec when no active entries exist" - ); - } - - #[tokio::test] - async fn test_regtest_mine() { - let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) - .await - .unwrap(); - // Test mining 1 block - let auth = std::env::var("BLOCKTANK_REGTEST_AUTH").ok(); - let result = db.regtest_mine(Some(1), auth.as_deref()).await; - assert!(result.is_ok(), "Failed to mine 1 block: {:?}", result.err()); - } - - #[tokio::test] - async fn test_regtest_deposit() { - let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) - .await - .unwrap(); - let auth = std::env::var("BLOCKTANK_REGTEST_AUTH").ok(); - - let test_address = "bcrt1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu"; - - // Test deposit with specific amount - let result = db - .regtest_deposit(test_address, Some(50000), auth.as_deref()) - .await; - - match result { - Ok(txid) => { - println!("Successfully deposited to address, txid: {}", txid); - assert!(!txid.is_empty(), "Transaction ID should not be empty"); - } - Err(err) => { - if err.to_string().contains("not in regtest mode") - || err.to_string().contains("Bad Request") - { - println!("Skipping test_regtest_deposit: Not in regtest mode or not supported in this environment"); - return; - } else { - panic!( - "API call to regtest_deposit failed with unexpected error: {:?}", - err - ); - } - } - } - } - #[tokio::test] async fn test_remove_all_orders() { let temp_dir = tempfile::tempdir().expect("Failed to create temp directory"); From a37e2ba8e82148f59a70c6d8bf742c9c537df7c8 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sun, 22 Nov 2026 04:34:20 +0100 Subject: [PATCH 2/2] test: keep blocktank staging tests out of the default run Restores the 12 Blocktank tests the previous commit removed. Only the regtest routes need staging's auth key; the other tests still pass against live staging, and they are the only coverage of the code that fetches from Blocktank and stores the result. The 10 tests that call live staging are now #[ignore], so cargo test stays off the network; run them with --ignored. The regtest mine and deposit tests return early when BLOCKTANK_REGTEST_AUTH is unset. A new offline test checks that refreshing active orders and CJIT entries on an empty database returns empty lists. Verified: cargo build --locked, cargo clippy --locked --all-targets, cargo test --locked; cargo test --lib modules::blocktank with BLOCKTANK_REGTEST_AUTH unset --- src/modules/blocktank/tests.rs | 861 ++++++++++++++++++++++++++++++++- 1 file changed, 848 insertions(+), 13 deletions(-) diff --git a/src/modules/blocktank/tests.rs b/src/modules/blocktank/tests.rs index 013b441d..529143cf 100644 --- a/src/modules/blocktank/tests.rs +++ b/src/modules/blocktank/tests.rs @@ -1,7 +1,12 @@ +//const STAGING_SERVER: &str = "https://api1.blocktank.to/api"; +//const STAGING_SERVER: &str = "https://api.stag.blocktank.to/api"; +const STAGING_SERVER: &str = "https://api.stag0.blocktank.to/blocktank/api/v2"; + #[cfg(test)] mod tests { #![allow(clippy::print_stdout)] + use super::*; use crate::modules::blocktank::liquidity::{ calculate_channel_liquidity_options, get_default_lsp_balance, ChannelLiquidityParams, DefaultLspBalanceParams, @@ -12,7 +17,9 @@ mod tests { #[tokio::test] async fn test_upsert_info() { // Initialize in-memory database - let db = BlocktankDB::new(":memory:", None).await.unwrap(); + let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) + .await + .unwrap(); // Create test data let test_info = IBtInfo { @@ -103,6 +110,59 @@ mod tests { } // Lock is dropped here } + #[tokio::test] + #[ignore = "calls live Blocktank staging"] + async fn test_fetch_and_store_info() { + // Initialize in-memory database + let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) + .await + .unwrap(); + + // Test fetch and store + let result = db.fetch_and_store_info().await; + assert!( + result.is_ok(), + "Failed to fetch and store info: {:?}", + result.err() + ); + + let info = result.unwrap(); + + // Verify the stored info matches what was returned + { + let conn = db.conn.lock().await; + + // Verify version is stored + let row = conn + .query_row( + "SELECT version, is_current FROM info WHERE version = ?1", + [info.version], + |row| Ok((row.get::<_, u32>(0)?, row.get::<_, bool>(1)?)), + ) + .unwrap(); + assert_eq!(row.0, info.version); + assert_eq!(row.1, true); + + // Verify JSON data + let nodes_json: String = conn + .query_row( + "SELECT nodes FROM info WHERE version = ?1", + [info.version], + |row| row.get(0), + ) + .unwrap(); + + let stored_nodes: Vec = serde_json::from_str(&nodes_json).unwrap(); + assert_eq!(stored_nodes.len(), info.nodes.len()); + + // Compare first node's data if any exist + if !info.nodes.is_empty() { + assert_eq!(stored_nodes[0].alias, info.nodes[0].alias); + assert_eq!(stored_nodes[0].pubkey, info.nodes[0].pubkey); + } + } + } + #[tokio::test] async fn test_fetch_and_store_info_error_handling() { // Initialize with invalid URL to test error handling @@ -134,7 +194,9 @@ mod tests { #[tokio::test] async fn test_get_info() { // Initialize in-memory database - let db = BlocktankDB::new(":memory:", None).await.unwrap(); + let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) + .await + .unwrap(); // Should return None when no info exists let empty_result = db.get_info().await.unwrap(); @@ -196,7 +258,9 @@ mod tests { #[tokio::test] async fn test_upsert_order() { - let db = BlocktankDB::new(":memory:", None).await.unwrap(); + let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) + .await + .unwrap(); // Get current timestamp in ISO 8601 format let now = chrono::Utc::now(); @@ -323,7 +387,9 @@ mod tests { #[tokio::test] async fn test_upsert_orders() { - let db = BlocktankDB::new(":memory:", None).await.unwrap(); + let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) + .await + .unwrap(); // Create multiple test orders let mut orders = Vec::new(); @@ -414,7 +480,9 @@ mod tests { #[tokio::test] async fn test_upsert_orders_empty() { - let db = BlocktankDB::new(":memory:", None).await.unwrap(); + let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) + .await + .unwrap(); // Test with empty vector let result = db.upsert_orders(&[]).await; @@ -427,7 +495,9 @@ mod tests { #[tokio::test] async fn test_upsert_orders_large_batch() { - let db = BlocktankDB::new(":memory:", None).await.unwrap(); + let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) + .await + .unwrap(); // Create a larger batch of orders to test performance let mut orders = Vec::new(); @@ -464,9 +534,149 @@ mod tests { println!("Bulk insert of 50 orders took: {:?}", bulk_duration); } + #[tokio::test] + #[ignore = "calls live Blocktank staging"] + async fn test_create_and_store_order() { + let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) + .await + .unwrap(); + + let options = CreateOrderOptions { + coupon_code: "".to_string(), + zero_conf: true, + zero_reserve: false, + announce_channel: false, + ..Default::default() + }; + + let result = db.create_and_store_order(100000, 4, Some(options)).await; + assert!( + result.is_ok(), + "Failed to create and store order: {:?}", + result.err() + ); + + let order = result.unwrap(); + assert_eq!(order.lsp_balance_sat, 100000); + assert_eq!(order.client_balance_sat, 0); + } + + #[tokio::test] + #[ignore = "calls live Blocktank staging"] + async fn test_refresh_orders() { + // Initialize in-memory database + let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) + .await + .unwrap(); + + // Create actual orders through the API + let options = CreateOrderOptions { + client_balance_sat: 0, + coupon_code: "".to_string(), + zero_conf: true, + zero_reserve: false, + announce_channel: false, + ..Default::default() + }; + + // Create two real orders + println!("Creating first test order..."); + let order1 = db + .create_and_store_order(100000, 4, Some(options.clone())) + .await + .expect("Failed to create first order"); + + println!("First order created with ID: {}", order1.id); + + // Add a small delay between order creations + tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; + + println!("Creating second test order..."); + let order2 = db + .create_and_store_order(150000, 4, Some(options.clone())) + .await + .expect("Failed to create second order"); + + println!("Second order created with ID: {}", order2.id); + + // Add a small delay before refreshing + tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; + + // Test refreshing orders + let order_ids = vec![order1.id.clone(), order2.id.clone()]; + println!("Attempting to refresh orders with IDs: {:?}", order_ids); + + let result = db.refresh_orders(&order_ids).await; + + match result { + Ok(refreshed_orders) => { + assert_eq!(refreshed_orders.len(), 2, "Should have refreshed 2 orders"); + + // Verify each refreshed order + let mut found_order1 = false; + let mut found_order2 = false; + + for order in &refreshed_orders { + println!("Checking refreshed order: {}", order.id); + + if order.id == order1.id { + found_order1 = true; + assert_eq!(order.lsp_balance_sat, 100000); + assert_eq!(order.client_balance_sat, 0); + } else if order.id == order2.id { + found_order2 = true; + assert_eq!(order.lsp_balance_sat, 150000); + assert_eq!(order.client_balance_sat, 0); + } + + // Verify database state + let conn = db.conn.lock().await; + let row = conn + .query_row( + "SELECT id, state, fee_sat FROM orders WHERE id = ?1", + [&order.id], + |row| { + Ok(( + row.get::<_, String>(0)?, + row.get::<_, String>(1)?, + row.get::<_, u64>(2)?, + )) + }, + ) + .unwrap(); + + assert_eq!(row.0, order.id); + assert_eq!(row.1, format!("{:?}", order.state)); + assert_eq!(row.2, order.fee_sat); + } + + assert!(found_order1, "First order not found in refreshed orders"); + assert!(found_order2, "Second order not found in refreshed orders"); + } + Err(e) => panic!("Failed to refresh orders: {:?}", e), + } + + // Test error handling with invalid order IDs + let invalid_ids = vec!["invalid_id_1".to_string()]; + let error_result = db.refresh_orders(&invalid_ids).await; + assert!( + error_result.is_err(), + "Expected error for invalid order IDs" + ); + + match error_result { + Err(BlocktankError::DataError { error_details }) => { + assert!(error_details.contains("Failed to fetch orders")); + } + _ => panic!("Expected DataError"), + } + } + #[tokio::test] async fn test_get_orders() { - let db = BlocktankDB::new(":memory:", None).await.unwrap(); + let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) + .await + .unwrap(); // Get current timestamp and future timestamp as integers let now = chrono::Utc::now(); @@ -622,7 +832,9 @@ mod tests { #[tokio::test] async fn test_get_active_orders() { - let db = BlocktankDB::new(":memory:", None).await.unwrap(); + let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) + .await + .unwrap(); // Get current timestamp and future timestamp let now = chrono::Utc::now(); @@ -747,9 +959,310 @@ mod tests { } } + #[tokio::test] + async fn test_refresh_active_with_empty_db() { + let db = BlocktankDB::new(":memory:", Some("http://invalid-url")) + .await + .unwrap(); + + let orders = db.refresh_active_orders().await.unwrap(); + assert!(orders.is_empty()); + + let entries = db.refresh_active_cjit_entries().await.unwrap(); + assert!(entries.is_empty()); + } + + #[tokio::test] + #[ignore = "calls live Blocktank staging"] + async fn test_refresh_active_orders() { + // Initialize in-memory database + let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) + .await + .unwrap(); + + // Create test orders with different states + let options = CreateOrderOptions { + client_balance_sat: 0, + coupon_code: "".to_string(), + zero_conf: true, + zero_reserve: false, + announce_channel: false, + ..Default::default() + }; + + // Create orders that should be active (Created and Paid states) + println!("Creating first test order (Created state)..."); + let order1 = db + .create_and_store_order(100000, 4, Some(options.clone())) + .await + .expect("Failed to create first order"); + println!("First order created with ID: {}", order1.id); + + // Add a small delay between order creations + tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; + + println!("Creating second test order (will be set to Paid state)..."); + let order2 = db + .create_and_store_order(150000, 4, Some(options.clone())) + .await + .expect("Failed to create second order"); + println!("Second order created with ID: {}", order2.id); + + // Add a small delay before refreshing + tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; + + // Test refreshing active orders + println!("Testing refresh_active_orders..."); + let result = db.refresh_active_orders().await; + + match result { + Ok(refreshed_orders) => { + assert_eq!( + refreshed_orders.len(), + 2, + "Should have refreshed 2 active orders" + ); + + // Verify each refreshed order + let mut found_order1 = false; + let mut found_order2 = false; + + for order in &refreshed_orders { + println!("Checking refreshed order: {}", order.id); + + if order.id == order1.id { + found_order1 = true; + assert_eq!(order.lsp_balance_sat, 100000); + assert_eq!(order.client_balance_sat, 0); + assert!(matches!(order.state2, Some(BtOrderState2::Created))); + } else if order.id == order2.id { + found_order2 = true; + assert_eq!(order.lsp_balance_sat, 150000); + assert_eq!(order.client_balance_sat, 0); + } + + // Verify order is in an active state + assert!( + matches!( + order.state2, + Some(BtOrderState2::Created) | Some(BtOrderState2::Paid) + ), + "Order should be in Created or Paid state" + ); + } + + assert!(found_order1, "First order not found in refreshed orders"); + assert!(found_order2, "Second order not found in refreshed orders"); + + // Verify database state + let conn = db.conn.lock().await; + for order in &refreshed_orders { + let row = conn + .query_row( + "SELECT id, state2, fee_sat FROM orders WHERE id = ?1", + [&order.id], + |row| { + Ok(( + row.get::<_, String>(0)?, + row.get::<_, String>(1)?, + row.get::<_, u64>(2)?, + )) + }, + ) + .unwrap(); + + assert_eq!(row.0, order.id); + assert!( + row.1 == "Created" || row.1 == "Paid", + "Database order state should be Created or Paid" + ); + } + } + Err(e) => panic!("Failed to refresh active orders: {:?}", e), + } + + // Test with no active orders + // First, expire all orders to make them inactive + let conn = db.conn.lock().await; + conn.execute("UPDATE orders SET state2 = 'Expired'", []) + .unwrap(); + drop(conn); // Release the lock + + // Now test refresh_active_orders with no active orders + let empty_result = db.refresh_active_orders().await.unwrap(); + assert_eq!( + empty_result.len(), + 0, + "Should return empty vec when no active orders exist" + ); + } + + #[tokio::test] + #[ignore = "calls live Blocktank staging"] + async fn test_get_min_zero_conf_tx_fee() { + let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) + .await + .unwrap(); + + // First create an order to get a valid order ID + let options = CreateOrderOptions { + client_balance_sat: 0, + coupon_code: "".to_string(), + zero_conf: true, + zero_reserve: false, + announce_channel: false, + ..Default::default() + }; + + println!("Creating test order..."); + let order = db + .create_and_store_order(100000, 4, Some(options)) + .await + .expect("Failed to create order"); + + println!("Order created with ID: {}", order.id); + + // Test getting min zero conf fee + let result = db.get_min_zero_conf_tx_fee(order.id).await; + assert!( + result.is_ok(), + "Failed to get min zero conf fee: {:?}", + result.err() + ); + + let fee_window = result.unwrap(); + assert!( + fee_window.sat_per_vbyte > 0.0, + "sat_per_vbyte should be greater than 0" + ); + assert!( + !fee_window.validity_ends_at.is_empty(), + "validity_ends_at should not be empty" + ); + + // Test with invalid order ID + let error_result = db.get_min_zero_conf_tx_fee("invalid_id".to_string()).await; + assert!(error_result.is_err(), "Expected error for invalid order ID"); + + match error_result { + Err(BlocktankError::DataError { error_details }) => { + assert!(error_details.contains("Failed to get minimum zero-conf transaction fee")); + } + _ => panic!("Expected DataError"), + } + } + + #[tokio::test] + #[ignore = "calls live Blocktank staging"] + async fn test_estimate_order_fee() { + let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) + .await + .unwrap(); + + let options = Some(CreateOrderOptions { + client_balance_sat: 0, + coupon_code: "".to_string(), + zero_conf: true, + zero_reserve: false, + announce_channel: false, + ..Default::default() + }); + + // Test valid estimation + let result = db.estimate_order_fee(100000, 4, options.clone()).await; + assert!( + result.is_ok(), + "Failed to estimate order fee: {:?}", + result.err() + ); + + let fee_estimate = result.unwrap(); + assert!( + fee_estimate.fee_sat > 0, + "Fee estimate should be greater than 0" + ); + assert!( + fee_estimate.min_0_conf_tx_fee.sat_per_vbyte > 0.0, + "min_0_conf_tx_fee.sat_per_vbyte should be greater than 0" + ); + + // Test with invalid parameters + let error_result = db.estimate_order_fee(0, 0, None).await; + assert!( + error_result.is_err(), + "Expected error for invalid parameters" + ); + + match error_result { + Err(BlocktankError::DataError { error_details }) => { + assert!(error_details.contains("Failed to estimate order fee")); + } + _ => panic!("Expected DataError"), + } + } + + #[tokio::test] + #[ignore = "calls live Blocktank staging"] + async fn test_estimate_order_fee_full() { + let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) + .await + .unwrap(); + + let options = Some(CreateOrderOptions { + client_balance_sat: 20000, + coupon_code: "".to_string(), + zero_conf: true, + zero_reserve: false, + announce_channel: false, + ..Default::default() + }); + + // Test valid full estimation + let result = db.estimate_order_fee_full(100000, 4, options.clone()).await; + assert!( + result.is_ok(), + "Failed to estimate full order fee: {:?}", + result.err() + ); + + let fee_estimate = result.unwrap(); + assert!( + fee_estimate.fee_sat > 0, + "Fee estimate should be greater than 0" + ); + assert!( + fee_estimate.network_fee_sat > 0, + "Network fee should be greater than 0" + ); + assert!( + fee_estimate.service_fee_sat > 0, + "Service fee should be greater than 0" + ); + assert!( + fee_estimate.min_0_conf_tx_fee.sat_per_vbyte > 0.0, + "min_0_conf_tx_fee.sat_per_vbyte should be greater than 0" + ); + + // Test with invalid parameters + let error_result = db.estimate_order_fee_full(0, 0, None).await; + assert!( + error_result.is_err(), + "Expected error for invalid parameters" + ); + + match error_result { + Err(BlocktankError::DataError { error_details }) => { + assert!(error_details.contains("Failed to estimate full order fee")); + } + _ => panic!("Expected DataError"), + } + } + #[tokio::test] async fn test_upsert_cjit_entry() { - let db = BlocktankDB::new(":memory:", None).await.unwrap(); + let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) + .await + .unwrap(); // Get current timestamp in ISO 8601 format let now = chrono::Utc::now(); @@ -860,7 +1373,9 @@ mod tests { #[tokio::test] async fn test_upsert_cjit_entries() { - let db = BlocktankDB::new(":memory:", None).await.unwrap(); + let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) + .await + .unwrap(); // Create multiple test CJIT entries let mut entries = Vec::new(); @@ -948,7 +1463,9 @@ mod tests { #[tokio::test] async fn test_upsert_cjit_entries_empty() { - let db = BlocktankDB::new(":memory:", None).await.unwrap(); + let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) + .await + .unwrap(); // Test with empty vector let result = db.upsert_cjit_entries(&[]).await; @@ -961,7 +1478,9 @@ mod tests { #[tokio::test] async fn test_get_cjit_entries() { - let db = BlocktankDB::new(":memory:", None).await.unwrap(); + let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) + .await + .unwrap(); // Get current timestamp and future timestamp let now = chrono::Utc::now(); @@ -1090,9 +1609,161 @@ mod tests { assert_eq!(specific_entry.source, test_entry1.source); } + #[tokio::test] + #[ignore = "calls live Blocktank staging"] + async fn test_cjit_entry_integration() { + // Initialize database with staging server + let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) + .await + .unwrap(); + + // Create a test CJIT entry + let options = Some(CreateCjitOptions { + source: Some("integration_test".to_string()), + discount_code: None, + }); + + println!("Creating CJIT entry..."); + let channel_size_sat = 100000; // 100k sats + let invoice_sat = 20000; // 20k sats + let invoice_description = "Integration test CJIT entry"; + let node_id = "03c8533232c155c41c42e5a8f8487b192dd36f1d354b86ef461cc82e67e3388839"; // Example node ID + let channel_expiry_weeks = 4; + + let result = db + .create_cjit_entry( + channel_size_sat, + invoice_sat, + invoice_description, + node_id, + channel_expiry_weeks, + options.clone(), + ) + .await; + + // Verify creation was successful + assert!( + result.is_ok(), + "Failed to create CJIT entry: {:?}", + result.err() + ); + let cjit_entry = result.unwrap(); + + println!("Created CJIT entry with ID: {}", cjit_entry.id); + + // Verify the entry properties + assert_eq!(cjit_entry.channel_size_sat, channel_size_sat); + assert_eq!(cjit_entry.channel_expiry_weeks, channel_expiry_weeks); + assert_eq!(cjit_entry.node_id, node_id); + assert_eq!(cjit_entry.state, CJitStateEnum::Created); + assert!(cjit_entry.fee_sat > 0); + assert!(cjit_entry.network_fee_sat > 0); + assert!(cjit_entry.service_fee_sat > 0); + + // Verify the invoice + assert_eq!(cjit_entry.invoice.state, BtBolt11InvoiceState::Pending); + assert!(!cjit_entry.invoice.request.is_empty()); + + // Verify source was set correctly + assert_eq!(cjit_entry.source, Some("integration_test".to_string())); + + // Test fetching the created entry + let fetched_entries = db + .get_cjit_entries(Some(&vec![cjit_entry.id.clone()]), None) + .await + .unwrap(); + + assert_eq!( + fetched_entries.len(), + 1, + "Should retrieve exactly one entry" + ); + let fetched_entry = &fetched_entries[0]; + + // Verify fetched entry matches created entry + assert_eq!(fetched_entry.id, cjit_entry.id); + assert_eq!(fetched_entry.channel_size_sat, channel_size_sat); + assert_eq!(fetched_entry.channel_expiry_weeks, channel_expiry_weeks); + assert_eq!(fetched_entry.node_id, node_id); + assert_eq!(fetched_entry.state, CJitStateEnum::Created); + + // Test filtering by state + let created_entries = db + .get_cjit_entries(None, Some(CJitStateEnum::Created)) + .await + .unwrap(); + assert!( + created_entries.iter().any(|e| e.id == cjit_entry.id), + "Should find the entry when filtering by Created state" + ); + + // Verify no entries in other states + let completed_entries = db + .get_cjit_entries(None, Some(CJitStateEnum::Completed)) + .await + .unwrap(); + assert!( + !completed_entries.iter().any(|e| e.id == cjit_entry.id), + "Should not find the entry when filtering by Completed state" + ); + + println!("CJIT entry integration test completed successfully"); + } + + #[tokio::test] + #[ignore = "calls live Blocktank staging"] + async fn test_cjit_entry_invalid_params() { + let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) + .await + .unwrap(); + + // Test with invalid channel size (too small) + let result = db + .create_cjit_entry( + 1000, // Very small channel size + 100, + "Test invalid channel size", + "03c8533232c155c41c42e5a8f8487b192dd36f1d354b86ef461cc82e67e3388839", + 4, + None, + ) + .await; + assert!(result.is_err(), "Should fail with too small channel size"); + + // Test with invalid node ID + let result = db + .create_cjit_entry( + 100000, + 1000, + "Test invalid node ID", + "invalid_node_id", + 4, + None, + ) + .await; + assert!(result.is_err(), "Should fail with invalid node ID"); + + // Test with invalid expiry weeks (too long) + let result = db + .create_cjit_entry( + 100000, + 1000, + "Test invalid expiry", + "03c8533232c155c41c42e5a8f8487b192dd36f1d354b86ef461cc82e67e3388839", + 100, // Too many weeks + None, + ) + .await; + assert!(result.is_err(), "Should fail with too many expiry weeks"); + + println!("CJIT entry invalid parameters test completed successfully"); + } + #[tokio::test] async fn test_get_active_cjit_entries() { - let db = BlocktankDB::new(":memory:", None).await.unwrap(); + let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) + .await + .unwrap(); // Get current timestamp and future timestamp let now = chrono::Utc::now(); @@ -1223,6 +1894,170 @@ mod tests { ); } + #[tokio::test] + #[ignore = "calls live Blocktank staging"] + async fn test_refresh_active_cjit_entries() { + // Initialize database with staging server + let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) + .await + .unwrap(); + + let options = Some(CreateCjitOptions { + source: Some("integration_test".to_string()), + discount_code: None, + }); + + // Create two test entries that will start in Created state + println!("Creating first test CJIT entry..."); + let entry1 = db + .create_cjit_entry( + 100000, // channel_size_sat + 20000, // invoice_sat + "Test CJIT 1", // description + "03c8533232c155c41c42e5a8f8487b192dd36f1d354b86ef461cc82e67e3388839", // node_id + 4, // channel_expiry_weeks + options.clone(), + ) + .await + .expect("Failed to create first CJIT entry"); + println!("First CJIT entry created with ID: {}", entry1.id); + + // Add a small delay between entry creations + tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; + + println!("Creating second test CJIT entry..."); + let entry2 = db + .create_cjit_entry( + 150000, // channel_size_sat + 30000, // invoice_sat + "Test CJIT 2", // description + "03c8533232c155c41c42e5a8f8487b192dd36f1d354b86ef461cc82e67e3388839", // node_id + 4, // channel_expiry_weeks + options.clone(), + ) + .await + .expect("Failed to create second CJIT entry"); + println!("Second CJIT entry created with ID: {}", entry2.id); + + // Test refreshing active CJIT entries + println!("Testing refresh_active_cjit_entries..."); + let result = db.refresh_active_cjit_entries().await; + + match result { + Ok(refreshed_entries) => { + // Verify we got entries back + assert!( + !refreshed_entries.is_empty(), + "Should have received refreshed entries" + ); + + // All refreshed entries should be in an active state + for entry in &refreshed_entries { + println!("Checking refreshed entry: {}", entry.id); + assert!( + matches!(entry.state, CJitStateEnum::Created | CJitStateEnum::Failed), + "Entry {} should be in Created or Failed state, but was in {:?} state", + entry.id, + entry.state + ); + + // Verify the basic entry properties are preserved + if entry.id == entry1.id { + assert_eq!(entry.channel_size_sat, 100000); + } else if entry.id == entry2.id { + assert_eq!(entry.channel_size_sat, 150000); + } + + // Verify LSP node data is loaded correctly + assert!(!entry.lsp_node.pubkey.is_empty()); + assert!(!entry.lsp_node.connection_strings.is_empty()); + } + + // Verify database state + let conn = db.conn.lock().await; + for entry in &refreshed_entries { + let row = conn + .query_row( + "SELECT id FROM cjit_entries WHERE id = ?1", + [&entry.id], + |row| Ok(row.get::<_, String>(0)?), + ) + .unwrap(); + + assert_eq!(row, entry.id); + } + } + Err(e) => panic!("Failed to refresh active CJIT entries: {:?}", e), + } + + // Test with no active entries by manually marking all entries as completed in the database + { + let conn = db.conn.lock().await; + conn.execute("UPDATE cjit_entries SET state = 'Completed'", []) + .unwrap(); + } + + // Now test refresh_active_cjit_entries with no active entries + let empty_result = db.refresh_active_cjit_entries().await.unwrap(); + assert_eq!( + empty_result.len(), + 0, + "Should return empty vec when no active entries exist" + ); + } + + #[tokio::test] + async fn test_regtest_mine() { + // Staging's regtest routes need this key; skip without it. + let Ok(auth) = std::env::var("BLOCKTANK_REGTEST_AUTH") else { + return; + }; + let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) + .await + .unwrap(); + // Test mining 1 block + let result = db.regtest_mine(Some(1), Some(auth.as_str())).await; + assert!(result.is_ok(), "Failed to mine 1 block: {:?}", result.err()); + } + + #[tokio::test] + async fn test_regtest_deposit() { + // Staging's regtest routes need this key; skip without it. + let Ok(auth) = std::env::var("BLOCKTANK_REGTEST_AUTH") else { + return; + }; + let db = BlocktankDB::new(":memory:", Some(STAGING_SERVER)) + .await + .unwrap(); + + let test_address = "bcrt1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu"; + + // Test deposit with specific amount + let result = db + .regtest_deposit(test_address, Some(50000), Some(auth.as_str())) + .await; + + match result { + Ok(txid) => { + println!("Successfully deposited to address, txid: {}", txid); + assert!(!txid.is_empty(), "Transaction ID should not be empty"); + } + Err(err) => { + if err.to_string().contains("not in regtest mode") + || err.to_string().contains("Bad Request") + { + println!("Skipping test_regtest_deposit: Not in regtest mode or not supported in this environment"); + return; + } else { + panic!( + "API call to regtest_deposit failed with unexpected error: {:?}", + err + ); + } + } + } + } + #[tokio::test] async fn test_remove_all_orders() { let temp_dir = tempfile::tempdir().expect("Failed to create temp directory");