ipfrs-interface 0.1.0

HTTP, gRPC, GraphQL and Python interfaces for IPFRS distributed storage
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
//! FFI (Foreign Function Interface) bindings for C interoperability
//!
//! This module provides a C-compatible API for IPFRS, allowing the library
//! to be used from C, C++, and other languages that support C FFI.
//!
//! # Safety
//!
//! All functions are marked as `unsafe extern "C"` and handle panics to prevent
//! undefined behavior. Proper null checks are performed on all pointer arguments.
//!
//! # Memory Management
//!
//! - Opaque pointers are used to hide Rust types from C
//! - Callers must free resources using the provided `*_free` functions
//! - Strings passed from C must be valid UTF-8 null-terminated strings
//! - Strings returned to C must be freed using `ipfrs_string_free`

use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_int};
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::ptr;
use std::slice;

/// FFI error codes
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IpfrsErrorCode {
    /// Operation succeeded
    Success = 0,
    /// Null pointer was passed
    NullPointer = -1,
    /// Invalid UTF-8 string
    InvalidUtf8 = -2,
    /// Invalid CID format
    InvalidCid = -3,
    /// Block not found
    NotFound = -4,
    /// I/O error
    IoError = -5,
    /// Out of memory
    OutOfMemory = -6,
    /// Internal error (panic caught)
    InternalError = -7,
    /// Invalid argument
    InvalidArgument = -8,
    /// Operation timed out
    Timeout = -9,
    /// Unknown error
    Unknown = -99,
}

/// Opaque handle to IPFRS client
#[repr(C)]
pub struct IpfrsClient {
    _private: [u8; 0],
}

/// Opaque handle to a block
#[repr(C)]
pub struct IpfrsBlock {
    _private: [u8; 0],
}

/// Internal representation of IPFRS client
struct ClientInner {
    // In a real implementation, this would contain:
    // - Gateway configuration
    // - Blockstore handle
    // - Tokio runtime handle
    // For now, we'll keep it simple
    _placeholder: u8,
}

/// Internal representation of a block
#[allow(dead_code)]
struct BlockInner {
    cid: String,
    data: Vec<u8>,
}

// Thread-local for storing last error message
thread_local! {
    static LAST_ERROR: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
}

/// Set the last error message
fn set_last_error(msg: String) {
    LAST_ERROR.with(|e| {
        *e.borrow_mut() = Some(msg);
    });
}

/// Clear the last error message
fn clear_last_error() {
    LAST_ERROR.with(|e| {
        *e.borrow_mut() = None;
    });
}

/// Initialize a new IPFRS client
///
/// # Arguments
///
/// * `config_path` - Path to configuration file (optional, can be NULL)
///
/// # Returns
///
/// Pointer to IpfrsClient on success, NULL on failure.
/// Use `ipfrs_get_last_error()` to retrieve error message.
///
/// # Safety
///
/// - `config_path` must be NULL or a valid null-terminated UTF-8 string
/// - Returned pointer must be freed with `ipfrs_client_free()`
#[no_mangle]
pub unsafe extern "C" fn ipfrs_client_new(config_path: *const c_char) -> *mut IpfrsClient {
    clear_last_error();

    let result = catch_unwind(AssertUnwindSafe(|| {
        // Parse config path if provided
        let _config = if !config_path.is_null() {
            let c_str = unsafe { CStr::from_ptr(config_path) };
            match c_str.to_str() {
                Ok(s) => Some(s.to_string()),
                Err(_) => {
                    set_last_error("Invalid UTF-8 in config_path".to_string());
                    return ptr::null_mut();
                }
            }
        } else {
            None
        };

        // Create client inner
        let inner = Box::new(ClientInner { _placeholder: 0 });

        Box::into_raw(inner) as *mut IpfrsClient
    }));

    match result {
        Ok(ptr) => ptr,
        Err(_) => {
            set_last_error("Panic occurred in ipfrs_client_new".to_string());
            ptr::null_mut()
        }
    }
}

/// Free an IPFRS client
///
/// # Safety
///
/// - `client` must be a valid pointer returned from `ipfrs_client_new()`
/// - `client` must not be used after this call
/// - `client` must not be NULL
#[no_mangle]
pub unsafe extern "C" fn ipfrs_client_free(client: *mut IpfrsClient) {
    if client.is_null() {
        return;
    }

    let _ = catch_unwind(AssertUnwindSafe(|| unsafe {
        let _ = Box::from_raw(client as *mut ClientInner);
    }));
}

/// Add data to IPFRS and return its CID
///
/// # Arguments
///
/// * `client` - Pointer to IpfrsClient
/// * `data` - Pointer to data buffer
/// * `data_len` - Length of data in bytes
/// * `out_cid` - Output pointer to receive CID string (must be freed with ipfrs_string_free)
///
/// # Returns
///
/// Error code (0 for success)
///
/// # Safety
///
/// - `client` must be a valid pointer from `ipfrs_client_new()`
/// - `data` must point to at least `data_len` bytes
/// - `out_cid` must be a valid pointer to a char pointer
#[no_mangle]
pub unsafe extern "C" fn ipfrs_add(
    client: *mut IpfrsClient,
    data: *const u8,
    data_len: usize,
    out_cid: *mut *mut c_char,
) -> c_int {
    clear_last_error();

    // Null pointer checks
    if client.is_null() {
        set_last_error("client is NULL".to_string());
        return IpfrsErrorCode::NullPointer as c_int;
    }
    if data.is_null() {
        set_last_error("data is NULL".to_string());
        return IpfrsErrorCode::NullPointer as c_int;
    }
    if out_cid.is_null() {
        set_last_error("out_cid is NULL".to_string());
        return IpfrsErrorCode::NullPointer as c_int;
    }

    let result = catch_unwind(AssertUnwindSafe(|| {
        let _inner = &*(client as *mut ClientInner);
        let data_slice = unsafe { slice::from_raw_parts(data, data_len) };

        // In a real implementation, this would:
        // 1. Chunk the data
        // 2. Create blocks
        // 3. Store them in the blockstore
        // 4. Return the root CID

        // For now, create a mock CID based on data length
        let mock_cid = format!("bafkreidummy{:016x}", data_slice.len());

        // Convert to C string
        match CString::new(mock_cid) {
            Ok(c_string) => {
                unsafe {
                    *out_cid = c_string.into_raw();
                }
                IpfrsErrorCode::Success as c_int
            }
            Err(_) => {
                set_last_error("Failed to create CID string".to_string());
                IpfrsErrorCode::InternalError as c_int
            }
        }
    }));

    match result {
        Ok(code) => code,
        Err(_) => {
            set_last_error("Panic occurred in ipfrs_add".to_string());
            IpfrsErrorCode::InternalError as c_int
        }
    }
}

/// Get data from IPFRS by CID
///
/// # Arguments
///
/// * `client` - Pointer to IpfrsClient
/// * `cid` - Null-terminated CID string
/// * `out_data` - Output pointer to receive data buffer (must be freed with ipfrs_data_free)
/// * `out_len` - Output pointer to receive data length
///
/// # Returns
///
/// Error code (0 for success)
///
/// # Safety
///
/// - `client` must be a valid pointer from `ipfrs_client_new()`
/// - `cid` must be a valid null-terminated UTF-8 string
/// - `out_data` must be a valid pointer
/// - `out_len` must be a valid pointer
#[no_mangle]
pub unsafe extern "C" fn ipfrs_get(
    client: *mut IpfrsClient,
    cid: *const c_char,
    out_data: *mut *mut u8,
    out_len: *mut usize,
) -> c_int {
    clear_last_error();

    // Null pointer checks
    if client.is_null() {
        set_last_error("client is NULL".to_string());
        return IpfrsErrorCode::NullPointer as c_int;
    }
    if cid.is_null() {
        set_last_error("cid is NULL".to_string());
        return IpfrsErrorCode::NullPointer as c_int;
    }
    if out_data.is_null() {
        set_last_error("out_data is NULL".to_string());
        return IpfrsErrorCode::NullPointer as c_int;
    }
    if out_len.is_null() {
        set_last_error("out_len is NULL".to_string());
        return IpfrsErrorCode::NullPointer as c_int;
    }

    let result = catch_unwind(AssertUnwindSafe(|| {
        let _inner = &*(client as *mut ClientInner);

        // Parse CID
        let c_str = unsafe { CStr::from_ptr(cid) };
        let cid_str = match c_str.to_str() {
            Ok(s) => s,
            Err(_) => {
                set_last_error("Invalid UTF-8 in CID".to_string());
                return IpfrsErrorCode::InvalidUtf8 as c_int;
            }
        };

        // In a real implementation, this would:
        // 1. Look up the CID in the blockstore
        // 2. Retrieve and reconstruct the data
        // 3. Return it to the caller

        // For now, return mock data
        let mock_data = format!("Data for CID: {}", cid_str).into_bytes();
        let len = mock_data.len();

        // Allocate buffer and copy data
        let mut boxed_data = mock_data.into_boxed_slice();
        let data_ptr = boxed_data.as_mut_ptr();
        std::mem::forget(boxed_data); // Prevent deallocation

        unsafe {
            *out_data = data_ptr;
            *out_len = len;
        }

        IpfrsErrorCode::Success as c_int
    }));

    match result {
        Ok(code) => code,
        Err(_) => {
            set_last_error("Panic occurred in ipfrs_get".to_string());
            IpfrsErrorCode::InternalError as c_int
        }
    }
}

/// Check if a block exists by CID
///
/// # Arguments
///
/// * `client` - Pointer to IpfrsClient
/// * `cid` - Null-terminated CID string
/// * `out_exists` - Output pointer to receive existence flag (1 = exists, 0 = not found)
///
/// # Returns
///
/// Error code (0 for success)
///
/// # Safety
///
/// - `client` must be a valid pointer from `ipfrs_client_new()`
/// - `cid` must be a valid null-terminated UTF-8 string
/// - `out_exists` must be a valid pointer
#[no_mangle]
pub unsafe extern "C" fn ipfrs_has(
    client: *mut IpfrsClient,
    cid: *const c_char,
    out_exists: *mut c_int,
) -> c_int {
    clear_last_error();

    // Null pointer checks
    if client.is_null() {
        set_last_error("client is NULL".to_string());
        return IpfrsErrorCode::NullPointer as c_int;
    }
    if cid.is_null() {
        set_last_error("cid is NULL".to_string());
        return IpfrsErrorCode::NullPointer as c_int;
    }
    if out_exists.is_null() {
        set_last_error("out_exists is NULL".to_string());
        return IpfrsErrorCode::NullPointer as c_int;
    }

    let result = catch_unwind(AssertUnwindSafe(|| {
        let _inner = &*(client as *mut ClientInner);

        // Parse CID
        let c_str = unsafe { CStr::from_ptr(cid) };
        let _cid_str = match c_str.to_str() {
            Ok(s) => s,
            Err(_) => {
                set_last_error("Invalid UTF-8 in CID".to_string());
                return IpfrsErrorCode::InvalidUtf8 as c_int;
            }
        };

        // In a real implementation, check blockstore
        // For now, always return true
        unsafe {
            *out_exists = 1;
        }

        IpfrsErrorCode::Success as c_int
    }));

    match result {
        Ok(code) => code,
        Err(_) => {
            set_last_error("Panic occurred in ipfrs_has".to_string());
            IpfrsErrorCode::InternalError as c_int
        }
    }
}

/// Get the last error message
///
/// # Returns
///
/// Pointer to null-terminated error string, or NULL if no error.
/// The string is valid until the next FFI call on this thread.
/// DO NOT free this pointer.
#[no_mangle]
pub extern "C" fn ipfrs_get_last_error() -> *const c_char {
    LAST_ERROR.with(|e| {
        e.borrow()
            .as_ref()
            .map_or(ptr::null(), |s| s.as_ptr() as *const c_char)
    })
}

/// Free a string returned by IPFRS functions
///
/// # Safety
///
/// - `s` must be a pointer returned by an IPFRS function (e.g., from ipfrs_add)
/// - `s` must not be used after this call
/// - `s` can be NULL (no-op)
#[no_mangle]
pub unsafe extern "C" fn ipfrs_string_free(s: *mut c_char) {
    if s.is_null() {
        return;
    }

    let _ = catch_unwind(AssertUnwindSafe(|| unsafe {
        let _ = CString::from_raw(s);
    }));
}

/// Free data returned by ipfrs_get
///
/// # Safety
///
/// - `data` must be a pointer returned by `ipfrs_get()`
/// - `len` must be the length returned by `ipfrs_get()`
/// - `data` must not be used after this call
/// - `data` can be NULL (no-op)
#[no_mangle]
pub unsafe extern "C" fn ipfrs_data_free(data: *mut u8, len: usize) {
    if data.is_null() {
        return;
    }

    let _ = catch_unwind(AssertUnwindSafe(|| unsafe {
        let _ = Vec::from_raw_parts(data, len, len);
    }));
}

/// Get library version string
///
/// # Returns
///
/// Pointer to static version string. DO NOT free this pointer.
#[no_mangle]
pub extern "C" fn ipfrs_version() -> *const c_char {
    // Use a static string to avoid allocation
    static VERSION: &[u8] = b"ipfrs-interface 0.1.0\0";
    VERSION.as_ptr() as *const c_char
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_client_lifecycle() {
        unsafe {
            let client = ipfrs_client_new(ptr::null());
            assert!(!client.is_null());
            ipfrs_client_free(client);
        }
    }

    #[test]
    fn test_add_and_get() {
        unsafe {
            let client = ipfrs_client_new(ptr::null());
            assert!(!client.is_null());

            // Add data
            let data = b"Hello, IPFRS!";
            let mut cid_ptr: *mut c_char = ptr::null_mut();
            let result = ipfrs_add(client, data.as_ptr(), data.len(), &mut cid_ptr);
            assert_eq!(result, IpfrsErrorCode::Success as c_int);
            assert!(!cid_ptr.is_null());

            // Get data back
            let mut out_data: *mut u8 = ptr::null_mut();
            let mut out_len: usize = 0;
            let result = ipfrs_get(client, cid_ptr, &mut out_data, &mut out_len);
            assert_eq!(result, IpfrsErrorCode::Success as c_int);
            assert!(!out_data.is_null());
            assert!(out_len > 0);

            // Clean up
            ipfrs_string_free(cid_ptr);
            ipfrs_data_free(out_data, out_len);
            ipfrs_client_free(client);
        }
    }

    #[test]
    fn test_has_block() {
        unsafe {
            let client = ipfrs_client_new(ptr::null());
            assert!(!client.is_null());

            let cid = CString::new("bafytest123").unwrap();
            let mut exists: c_int = 0;
            let result = ipfrs_has(client, cid.as_ptr(), &mut exists);
            assert_eq!(result, IpfrsErrorCode::Success as c_int);

            ipfrs_client_free(client);
        }
    }

    #[test]
    fn test_null_pointer_handling() {
        unsafe {
            // Test with null client
            let mut cid_ptr: *mut c_char = ptr::null_mut();
            let data = b"test";
            let result = ipfrs_add(ptr::null_mut(), data.as_ptr(), data.len(), &mut cid_ptr);
            assert_eq!(result, IpfrsErrorCode::NullPointer as c_int);
        }
    }

    #[test]
    fn test_version() {
        let version = ipfrs_version();
        assert!(!version.is_null());
        unsafe {
            let c_str = CStr::from_ptr(version);
            let version_str = c_str.to_str().unwrap();
            assert!(version_str.contains("ipfrs-interface"));
        }
    }
}