use std::{slice, str};
use derec_proto::StatusEnum;
use super::DeRecProtocolHandle;
use crate::Error;
use crate::interop::ffi::common::{DeRecBuffer, empty_buffer, vec_into_buffer};
use crate::interop::ffi::error::{
DEREC_CODE_FFI_BAD_PROTO, DEREC_CODE_FFI_BAD_UTF8, DEREC_CODE_FFI_INVALID_ENUM,
DEREC_CODE_FFI_NULL_PTR, DeRecError, ffi_error, from_lib_error, success,
};
use crate::interop::ffi::protocol::events::encode_events;
use crate::interop::ffi::protocol::flow as flow_params;
use crate::interop::recovered_secret::RecoveredSecretIn;
use crate::protocol::RestoreError;
use crate::protocol::utils::pending_action_wire;
#[unsafe(no_mangle)]
pub unsafe extern "C" fn derec_protocol_start(
handle: *mut DeRecProtocolHandle,
flow_kind: u32,
params_json_ptr: *const u8,
params_json_len: usize,
) -> DeRecProtocolEventsResult {
if handle.is_null() {
return ffi_error(DEREC_CODE_FFI_NULL_PTR, "handle is null").into();
}
if params_json_len > 0 && params_json_ptr.is_null() {
return ffi_error(
DEREC_CODE_FFI_NULL_PTR,
"params_json_ptr is null but len > 0",
)
.into();
}
let params_bytes = if params_json_len == 0 {
b""[..].to_vec()
} else {
unsafe { slice::from_raw_parts(params_json_ptr, params_json_len) }.to_vec()
};
let flow = match flow_params::parse_flow(flow_kind, ¶ms_bytes) {
Ok(f) => f,
Err(e) => return ffi_error(DEREC_CODE_FFI_BAD_PROTO, e).into(),
};
let h = unsafe { &*handle };
let mut inner = h.lock_inner();
match h.runtime.block_on(inner.start(flow)) {
Ok(events) => {
let json = encode_events(events);
DeRecProtocolEventsResult {
error: success(),
events_json: vec_into_buffer(json),
}
}
Err(e) => from_lib_error(e).into(),
}
}
#[repr(C)]
pub struct DeRecProtocolEventsResult {
pub error: DeRecError,
pub events_json: DeRecBuffer,
}
#[repr(C)]
pub struct DeRecProtocolRestoreResult {
pub error: DeRecError,
pub events_json: DeRecBuffer,
pub conflicting_channel_ids_json: DeRecBuffer,
}
impl From<DeRecError> for DeRecProtocolRestoreResult {
fn from(error: DeRecError) -> Self {
Self {
error,
events_json: empty_buffer(),
conflicting_channel_ids_json: empty_buffer(),
}
}
}
impl From<DeRecError> for DeRecProtocolEventsResult {
fn from(error: DeRecError) -> Self {
Self {
error,
events_json: empty_buffer(),
}
}
}
#[repr(C)]
pub struct DeRecProtocolProcessResult {
pub error: DeRecError,
pub events_json: DeRecBuffer,
pub has_channel_id: bool,
pub channel_id: u64,
}
impl From<DeRecError> for DeRecProtocolProcessResult {
fn from(error: DeRecError) -> Self {
Self {
error,
events_json: empty_buffer(),
has_channel_id: false,
channel_id: 0,
}
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn derec_protocol_process(
handle: *mut DeRecProtocolHandle,
message_ptr: *const u8,
message_len: usize,
) -> DeRecProtocolProcessResult {
if handle.is_null() {
return ffi_error(DEREC_CODE_FFI_NULL_PTR, "handle is null").into();
}
if message_len > 0 && message_ptr.is_null() {
return ffi_error(DEREC_CODE_FFI_NULL_PTR, "message_ptr is null but len > 0").into();
}
let bytes = if message_len == 0 {
Vec::new()
} else {
unsafe { slice::from_raw_parts(message_ptr, message_len) }.to_vec()
};
let h = unsafe { &*handle };
let mut inner = h.lock_inner();
match h.runtime.block_on(inner.process(&bytes)) {
Ok(events) => DeRecProtocolProcessResult {
error: success(),
events_json: vec_into_buffer(encode_events(events)),
has_channel_id: false,
channel_id: 0,
},
Err(e) => DeRecProtocolProcessResult {
error: from_lib_error(e.source),
events_json: vec_into_buffer(encode_events(e.events)),
has_channel_id: e.channel_id.is_some(),
channel_id: e.channel_id.map_or(0, |id| id.0),
},
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn derec_protocol_tick(
handle: *mut DeRecProtocolHandle,
) -> DeRecProtocolEventsResult {
if handle.is_null() {
return ffi_error(DEREC_CODE_FFI_NULL_PTR, "handle is null").into();
}
let h = unsafe { &*handle };
let mut inner = h.lock_inner();
let events = h.runtime.block_on(inner.tick());
DeRecProtocolEventsResult {
error: success(),
events_json: vec_into_buffer(encode_events(events)),
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn derec_protocol_accept(
handle: *mut DeRecProtocolHandle,
action_ptr: *const u8,
action_len: usize,
) -> DeRecProtocolEventsResult {
if handle.is_null() {
return ffi_error(DEREC_CODE_FFI_NULL_PTR, "handle is null").into();
}
if action_len == 0 || action_ptr.is_null() {
return ffi_error(DEREC_CODE_FFI_NULL_PTR, "action_ptr is null or len == 0").into();
}
let bytes = unsafe { slice::from_raw_parts(action_ptr, action_len) };
let action = match pending_action_wire::deserialize(bytes) {
Ok(a) => a,
Err(e) => {
return ffi_error(
DEREC_CODE_FFI_BAD_PROTO,
format!("PendingAction decode: {e}"),
)
.into();
}
};
let h = unsafe { &*handle };
let mut inner = h.lock_inner();
match h.runtime.block_on(inner.accept(action)) {
Ok(events) => {
let json = encode_events(events);
DeRecProtocolEventsResult {
error: success(),
events_json: vec_into_buffer(json),
}
}
Err(e) => from_lib_error(e).into(),
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn derec_protocol_reject(
handle: *mut DeRecProtocolHandle,
action_ptr: *const u8,
action_len: usize,
status: i32,
memo_ptr: *const u8,
memo_len: usize,
) -> DeRecError {
if handle.is_null() {
return ffi_error(DEREC_CODE_FFI_NULL_PTR, "handle is null");
}
if action_len == 0 || action_ptr.is_null() {
return ffi_error(DEREC_CODE_FFI_NULL_PTR, "action_ptr is null or len == 0");
}
let bytes = unsafe { slice::from_raw_parts(action_ptr, action_len) };
let action = match pending_action_wire::deserialize(bytes) {
Ok(a) => a,
Err(e) => {
return ffi_error(
DEREC_CODE_FFI_BAD_PROTO,
format!("PendingAction decode: {e}"),
);
}
};
let memo = if memo_len == 0 {
String::new()
} else if memo_ptr.is_null() {
return ffi_error(DEREC_CODE_FFI_NULL_PTR, "memo_ptr is null but len > 0");
} else {
let bytes = unsafe { slice::from_raw_parts(memo_ptr, memo_len) };
match str::from_utf8(bytes) {
Ok(s) => s.to_owned(),
Err(_) => return ffi_error(DEREC_CODE_FFI_BAD_PROTO, "memo is not valid UTF-8"),
}
};
let status_enum = match StatusEnum::try_from(status) {
Ok(s) => s,
Err(_) => {
return ffi_error(
DEREC_CODE_FFI_INVALID_ENUM,
format!("invalid StatusEnum: {status}"),
);
}
};
let h = unsafe { &*handle };
let mut inner = h.lock_inner();
match h.runtime.block_on(inner.reject(action, status_enum, &memo)) {
Ok(()) => success(),
Err(e) => from_lib_error(e),
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn derec_protocol_restore(
handle: *mut DeRecProtocolHandle,
params_json_ptr: *const u8,
params_json_len: usize,
) -> DeRecProtocolRestoreResult {
if handle.is_null() {
return ffi_error(DEREC_CODE_FFI_NULL_PTR, "handle is null").into();
}
if params_json_len == 0 || params_json_ptr.is_null() {
return ffi_error(
DEREC_CODE_FFI_NULL_PTR,
"params_json_ptr is null or len == 0",
)
.into();
}
let bytes = unsafe { slice::from_raw_parts(params_json_ptr, params_json_len) };
let json = match str::from_utf8(bytes) {
Ok(s) => s,
Err(_) => {
return ffi_error(DEREC_CODE_FFI_BAD_UTF8, "params_json is not valid UTF-8").into();
}
};
let params: RestoreParamsJson = match serde_json::from_str(json) {
Ok(p) => p,
Err(e) => {
return ffi_error(
DEREC_CODE_FFI_BAD_PROTO,
format!("restore params JSON: {e}"),
)
.into();
}
};
let secret = match params.recovered_secret.into_secret() {
Ok(s) => s,
Err(e) => return ffi_error(DEREC_CODE_FFI_BAD_PROTO, e).into(),
};
let h = unsafe { &*handle };
let mut inner = h.lock_inner();
match h.runtime.block_on(inner.restore(&secret, params.version)) {
Ok(events) => {
let json = encode_events(events);
DeRecProtocolRestoreResult {
error: success(),
events_json: vec_into_buffer(json),
conflicting_channel_ids_json: empty_buffer(),
}
}
Err(e) => {
let conflicting = match &e {
Error::Restore(RestoreError::Conflict(ids)) => {
let ids: Vec<String> = ids.iter().map(|c| c.0.to_string()).collect();
vec_into_buffer(serde_json::to_vec(&ids).expect("a list of strings serializes"))
}
_ => empty_buffer(),
};
DeRecProtocolRestoreResult {
error: from_lib_error(e),
events_json: empty_buffer(),
conflicting_channel_ids_json: conflicting,
}
}
}
}
#[derive(serde::Deserialize)]
struct RestoreParamsJson {
version: u32,
recovered_secret: RecoveredSecretIn,
}