Skip to content

Commit 90084d5

Browse files
chore: run cargo fmt
1 parent 5cb680a commit 90084d5

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

74 files changed

+2434
-1883
lines changed

dash-spv-ffi/src/callbacks.rs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1+
use dashcore::hashes::Hash;
12
use std::ffi::CString;
23
use std::os::raw::{c_char, c_void};
3-
use dashcore::hashes::Hash;
44

55
pub type ProgressCallback =
66
extern "C" fn(progress: f64, message: *const c_char, user_data: *mut c_void);
@@ -256,7 +256,12 @@ impl FFIEventCallbacks {
256256
);
257257
let txid_bytes = txid.as_byte_array();
258258
let hash_bytes = block_hash.as_byte_array();
259-
callback(txid_bytes.as_ptr() as *const [u8; 32], block_height, hash_bytes.as_ptr() as *const [u8; 32], self.user_data);
259+
callback(
260+
txid_bytes.as_ptr() as *const [u8; 32],
261+
block_height,
262+
hash_bytes.as_ptr() as *const [u8; 32],
263+
self.user_data,
264+
);
260265
tracing::info!("✅ Mempool transaction confirmed callback completed");
261266
} else {
262267
tracing::debug!("Mempool transaction confirmed callback not set");

dash-spv-ffi/src/client.rs

Lines changed: 33 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -45,27 +45,27 @@ enum CallbackInfo {
4545
}
4646

4747
/// # Safety
48-
///
48+
///
4949
/// `CallbackInfo` is only `Send` if the following conditions are met:
5050
/// - All callback functions must be safe to call from any thread
5151
/// - The `user_data` pointer must either:
5252
/// - Point to thread-safe data (i.e., data that implements `Send`)
5353
/// - Be properly synchronized by the caller (e.g., using mutexes)
5454
/// - Be null
55-
///
55+
///
5656
/// The caller is responsible for ensuring these conditions are met. Violating
5757
/// these requirements will result in undefined behavior.
5858
unsafe impl Send for CallbackInfo {}
5959

6060
/// # Safety
61-
///
61+
///
6262
/// `CallbackInfo` is only `Sync` if the following conditions are met:
6363
/// - All callback functions must be safe to call concurrently from multiple threads
6464
/// - The `user_data` pointer must either:
6565
/// - Point to thread-safe data (i.e., data that implements `Sync`)
6666
/// - Be properly synchronized by the caller (e.g., using mutexes)
6767
/// - Be null
68-
///
68+
///
6969
/// The caller is responsible for ensuring these conditions are met. Violating
7070
/// these requirements will result in undefined behavior.
7171
unsafe impl Sync for CallbackInfo {}
@@ -157,9 +157,10 @@ pub unsafe extern "C" fn dash_spv_ffi_client_new(
157157
let config = &(*config);
158158
let runtime = match tokio::runtime::Builder::new_multi_thread()
159159
.thread_name("dash-spv-worker")
160-
.worker_threads(1) // Reduce threads for mobile
160+
.worker_threads(1) // Reduce threads for mobile
161161
.enable_all()
162-
.build() {
162+
.build()
163+
{
163164
Ok(rt) => Arc::new(rt),
164165
Err(e) => {
165166
set_last_error(&format!("Failed to create runtime: {}", e));
@@ -360,25 +361,25 @@ pub unsafe extern "C" fn dash_spv_ffi_client_stop(client: *mut FFIDashSpvClient)
360361
}
361362

362363
/// Sync the SPV client to the chain tip.
363-
///
364+
///
364365
/// # Safety
365-
///
366+
///
366367
/// This function is unsafe because:
367368
/// - `client` must be a valid pointer to an initialized `FFIDashSpvClient`
368369
/// - `user_data` must satisfy thread safety requirements:
369370
/// - If non-null, it must point to data that is safe to access from multiple threads
370371
/// - The caller must ensure proper synchronization if the data is mutable
371372
/// - The data must remain valid for the entire duration of the sync operation
372373
/// - `completion_callback` must be thread-safe and can be called from any thread
373-
///
374+
///
374375
/// # Parameters
375-
///
376+
///
376377
/// - `client`: Pointer to the SPV client
377378
/// - `completion_callback`: Optional callback invoked on completion
378379
/// - `user_data`: Optional user data pointer passed to callbacks
379-
///
380+
///
380381
/// # Returns
381-
///
382+
///
382383
/// 0 on success, error code on failure
383384
#[no_mangle]
384385
pub unsafe extern "C" fn dash_spv_ffi_client_sync_to_tip(
@@ -418,7 +419,10 @@ pub unsafe extern "C" fn dash_spv_ffi_client_sync_to_tip(
418419
{
419420
if let Some(callback) = completion_callback {
420421
let msg = CString::new("Sync completed successfully")
421-
.unwrap_or_else(|_| CString::new("Sync completed").expect("hardcoded string is safe"));
422+
.unwrap_or_else(|_| {
423+
CString::new("Sync completed")
424+
.expect("hardcoded string is safe")
425+
});
422426
// SAFETY: The callback and user_data are safely managed through the registry
423427
// The registry ensures proper lifetime management and thread safety
424428
callback(true, msg.as_ptr(), user_data);
@@ -440,7 +444,8 @@ pub unsafe extern "C" fn dash_spv_ffi_client_sync_to_tip(
440444
if let Some(callback) = completion_callback {
441445
let msg = match CString::new(format!("Sync failed: {}", e)) {
442446
Ok(s) => s,
443-
Err(_) => CString::new("Sync failed").expect("hardcoded string is safe"),
447+
Err(_) => CString::new("Sync failed")
448+
.expect("hardcoded string is safe"),
444449
};
445450
// SAFETY: The callback and user_data are safely managed through the registry
446451
// The registry ensures proper lifetime management and thread safety
@@ -544,26 +549,26 @@ pub unsafe extern "C" fn dash_spv_ffi_client_test_sync(client: *mut FFIDashSpvCl
544549
}
545550

546551
/// Sync the SPV client to the chain tip with detailed progress updates.
547-
///
552+
///
548553
/// # Safety
549-
///
554+
///
550555
/// This function is unsafe because:
551556
/// - `client` must be a valid pointer to an initialized `FFIDashSpvClient`
552557
/// - `user_data` must satisfy thread safety requirements:
553558
/// - If non-null, it must point to data that is safe to access from multiple threads
554559
/// - The caller must ensure proper synchronization if the data is mutable
555560
/// - The data must remain valid for the entire duration of the sync operation
556561
/// - Both `progress_callback` and `completion_callback` must be thread-safe and can be called from any thread
557-
///
562+
///
558563
/// # Parameters
559-
///
564+
///
560565
/// - `client`: Pointer to the SPV client
561566
/// - `progress_callback`: Optional callback invoked periodically with sync progress
562567
/// - `completion_callback`: Optional callback invoked on completion
563568
/// - `user_data`: Optional user data pointer passed to all callbacks
564-
///
569+
///
565570
/// # Returns
566-
///
571+
///
567572
/// 0 on success, error code on failure
568573
#[no_mangle]
569574
pub unsafe extern "C" fn dash_spv_ffi_client_sync_to_tip_with_progress(
@@ -674,8 +679,11 @@ pub unsafe extern "C" fn dash_spv_ffi_client_sync_to_tip_with_progress(
674679
{
675680
match monitor_result {
676681
Ok(_) => {
677-
let msg = CString::new("Sync completed successfully")
678-
.unwrap_or_else(|_| CString::new("Sync completed").expect("hardcoded string is safe"));
682+
let msg =
683+
CString::new("Sync completed successfully").unwrap_or_else(|_| {
684+
CString::new("Sync completed")
685+
.expect("hardcoded string is safe")
686+
});
679687
// SAFETY: The callback and user_data are safely managed through the registry.
680688
// The registry ensures proper lifetime management and thread safety.
681689
// The string pointer is only valid for the duration of the callback.
@@ -686,7 +694,9 @@ pub unsafe extern "C" fn dash_spv_ffi_client_sync_to_tip_with_progress(
686694
Err(e) => {
687695
let msg = match CString::new(format!("Sync failed: {}", e)) {
688696
Ok(s) => s,
689-
Err(_) => CString::new("Sync failed").expect("hardcoded string is safe"),
697+
Err(_) => {
698+
CString::new("Sync failed").expect("hardcoded string is safe")
699+
}
690700
};
691701
// SAFETY: Same as above
692702
callback(false, msg.as_ptr(), user_data);

dash-spv-ffi/src/platform_integration.rs

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,9 @@ pub unsafe extern "C" fn ffi_dash_spv_get_core_handle(
4141
return ptr::null_mut();
4242
}
4343

44-
Box::into_raw(Box::new(CoreSDKHandle { client }))
44+
Box::into_raw(Box::new(CoreSDKHandle {
45+
client,
46+
}))
4547
}
4648

4749
/// Releases a CoreSDKHandle
@@ -105,7 +107,10 @@ pub unsafe extern "C" fn ffi_dash_spv_get_quorum_public_key(
105107

106108
// TODO: Implement actual quorum public key retrieval
107109
// For now, return a placeholder error
108-
FFIResult::error(FFIErrorCode::NotImplemented, "Quorum public key retrieval not yet implemented")
110+
FFIResult::error(
111+
FFIErrorCode::NotImplemented,
112+
"Quorum public key retrieval not yet implemented",
113+
)
109114
}
110115

111116
/// Gets the platform activation height from the Core chain
@@ -136,4 +141,4 @@ pub unsafe extern "C" fn ffi_dash_spv_get_platform_activation_height(
136141
FFIErrorCode::NotImplemented,
137142
"Platform activation height retrieval not yet implemented",
138143
)
139-
}
144+
}

dash-spv-ffi/tests/test_event_callbacks.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
use dash_spv_ffi::*;
21
use dash_spv_ffi::callbacks::{BlockCallback, TransactionCallback};
2+
use dash_spv_ffi::*;
33
use std::ffi::{c_char, c_void, CStr, CString};
44
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
55
use std::sync::Arc;

dash-spv-ffi/tests/test_mempool_tracking.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
1+
use dash_spv_ffi::callbacks::{
2+
MempoolConfirmedCallback, MempoolRemovedCallback, MempoolTransactionCallback,
3+
};
14
use dash_spv_ffi::*;
2-
use dash_spv_ffi::callbacks::{MempoolTransactionCallback, MempoolConfirmedCallback, MempoolRemovedCallback};
35
use std::ffi::{CStr, CString};
46
use std::os::raw::{c_char, c_void};
57
use std::sync::{Arc, Mutex};

dash-spv-ffi/tests/test_platform_integration.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,4 +56,4 @@ mod test_platform_integration {
5656
*/
5757
}
5858
}
59-
}
59+
}

dash-spv-ffi/tests/unit/test_async_operations.rs

Lines changed: 52 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -266,7 +266,7 @@ mod tests {
266266
) {
267267
let data = unsafe { &*(user_data as *const ReentrantData) };
268268
let count = data.count.fetch_add(1, Ordering::SeqCst);
269-
269+
270270
// Check if callback is already active (reentrancy detection)
271271
if data.callback_active.swap(true, Ordering::SeqCst) {
272272
data.reentrancy_detected.store(true, Ordering::SeqCst);
@@ -281,16 +281,16 @@ mod tests {
281281
// Attempt to start another sync operation from within callback
282282
// This tests that the FFI layer properly handles reentrancy
283283
let start_time = Instant::now();
284-
284+
285285
// Try to call test_sync which is a simpler operation
286286
let test_result = unsafe { dash_spv_ffi_client_test_sync(data.client) };
287287
let elapsed = start_time.elapsed();
288-
288+
289289
// If this takes too long, it might indicate a deadlock
290290
if elapsed > Duration::from_secs(1) {
291291
data.deadlock_detected.store(true, Ordering::SeqCst);
292292
}
293-
293+
294294
if test_result != 0 {
295295
println!("Reentrant call failed with error code: {}", test_result);
296296
}
@@ -319,7 +319,7 @@ mod tests {
319319
Some(reentrant_callback),
320320
&reentrant_data as *const _ as *mut c_void,
321321
);
322-
322+
323323
// Wait for operations to complete
324324
thread::sleep(Duration::from_millis(500));
325325

@@ -381,24 +381,32 @@ mod tests {
381381
user_data: *mut c_void,
382382
) {
383383
let data = unsafe { &*(user_data as *const ThreadSafetyData) };
384-
384+
385385
// Increment concurrent callback count
386-
let current_concurrent = data.concurrent_callbacks.fetch_add(1, Ordering::SeqCst) + 1;
387-
386+
let current_concurrent =
387+
data.concurrent_callbacks.fetch_add(1, Ordering::SeqCst) + 1;
388+
388389
// Update max concurrent callbacks
389390
loop {
390391
let max = data.max_concurrent.load(Ordering::SeqCst);
391-
if current_concurrent <= max ||
392-
data.max_concurrent.compare_exchange(max, current_concurrent,
393-
Ordering::SeqCst,
394-
Ordering::SeqCst).is_ok() {
392+
if current_concurrent <= max
393+
|| data
394+
.max_concurrent
395+
.compare_exchange(
396+
max,
397+
current_concurrent,
398+
Ordering::SeqCst,
399+
Ordering::SeqCst,
400+
)
401+
.is_ok()
402+
{
395403
break;
396404
}
397405
}
398406

399407
// Test shared state access (potential race condition)
400408
let count = data.count.fetch_add(1, Ordering::SeqCst);
401-
409+
402410
// Try to detect race conditions by accessing shared state
403411
{
404412
let mut state = match data.shared_state.try_lock() {
@@ -415,7 +423,7 @@ mod tests {
415423

416424
// Simulate some work
417425
thread::sleep(Duration::from_micros(100));
418-
426+
419427
// Decrement concurrent callback count
420428
data.concurrent_callbacks.fetch_sub(1, Ordering::SeqCst);
421429
}
@@ -429,34 +437,36 @@ mod tests {
429437

430438
// Create thread-safe wrapper for the data
431439
let thread_data_arc = Arc::new(thread_data);
432-
440+
433441
// Spawn multiple threads that will trigger callbacks
434-
let handles: Vec<_> = (0..3).map(|i| {
435-
let thread_data_clone = thread_data_arc.clone();
436-
let barrier_clone = barrier.clone();
437-
438-
thread::spawn(move || {
439-
// Synchronize thread start
440-
barrier_clone.wait();
441-
442-
// Each thread performs multiple operations
443-
for j in 0..5 {
444-
println!("Thread {} iteration {}", i, j);
445-
446-
// Invoke callback directly
447-
thread_safe_callback(
448-
true,
449-
std::ptr::null(),
450-
&*thread_data_clone as *const ThreadSafetyData as *mut c_void
451-
);
452-
453-
// Note: We can't safely pass client pointers across threads
454-
// so we'll focus on testing concurrent callback invocations
455-
456-
thread::sleep(Duration::from_millis(10));
457-
}
442+
let handles: Vec<_> = (0..3)
443+
.map(|i| {
444+
let thread_data_clone = thread_data_arc.clone();
445+
let barrier_clone = barrier.clone();
446+
447+
thread::spawn(move || {
448+
// Synchronize thread start
449+
barrier_clone.wait();
450+
451+
// Each thread performs multiple operations
452+
for j in 0..5 {
453+
println!("Thread {} iteration {}", i, j);
454+
455+
// Invoke callback directly
456+
thread_safe_callback(
457+
true,
458+
std::ptr::null(),
459+
&*thread_data_clone as *const ThreadSafetyData as *mut c_void,
460+
);
461+
462+
// Note: We can't safely pass client pointers across threads
463+
// so we'll focus on testing concurrent callback invocations
464+
465+
thread::sleep(Duration::from_millis(10));
466+
}
467+
})
458468
})
459-
}).collect();
469+
.collect();
460470

461471
// Wait for all threads to complete
462472
for handle in handles {
@@ -479,11 +489,11 @@ mod tests {
479489
let state = thread_data_arc.shared_state.lock().unwrap();
480490
let mut sorted_state = state.clone();
481491
sorted_state.sort();
482-
492+
483493
// Check for duplicates (would indicate race condition)
484494
let mut duplicates = 0;
485495
for i in 1..sorted_state.len() {
486-
if sorted_state[i] == sorted_state[i-1] {
496+
if sorted_state[i] == sorted_state[i - 1] {
487497
duplicates += 1;
488498
}
489499
}

0 commit comments

Comments
 (0)