derec-library 0.0.1-alpha.8

Rust SDK for the DeRec protocol, including native and WebAssembly bindings.
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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 DeRec Alliance. All rights reserved.

//! Event-loop entry points: `start` / `process` / `accept` / `reject`.
//! Each one drives the protocol's async core via the per-handle tokio
//! runtime and returns either a typed result or a JSON event array.

use super::DeRecProtocolHandle;
use crate::ffi::common::{empty_buffer, vec_into_buffer, DeRecBuffer};
use crate::ffi::error::{
    ffi_error, from_lib_error, success, DeRecError, DEREC_CODE_FFI_BAD_PROTO,
    DEREC_CODE_FFI_BAD_UTF8, DEREC_CODE_FFI_INVALID_ENUM, DEREC_CODE_FFI_NULL_PTR,
};
use crate::ffi::protocol::events::encode_events;
use crate::ffi::protocol::flow as flow_params;

/// Start a new flow. `flow_kind` matches the constants in
/// [`crate::ffi::protocol::flow`]. `params_json_*` is a UTF-8 JSON blob
/// shaped to the matching `*ParamsJson` struct in that module.
///
/// # Safety
///
/// `handle` must be a valid pointer returned by
/// [`super::derec_protocol_new`]. `params_json_ptr`/`params_json_len`
/// must describe a readable byte range.
#[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 { std::slice::from_raw_parts(params_json_ptr, params_json_len) }.to_vec()
    };

    let flow = match flow_params::parse_flow(flow_kind, &params_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(),
    }
}

/// Result type for entry points that return a `Vec<DeRecEvent>`.
#[repr(C)]
pub struct DeRecProtocolEventsResult {
    pub error: DeRecError,
    /// UTF-8 JSON array of events. See [`crate::ffi::protocol::events`]
    /// for the per-variant shape. Caller releases via
    /// [`crate::ffi::derec_free_buffer`].
    pub events_json: DeRecBuffer,
}

impl From<DeRecError> for DeRecProtocolEventsResult {
    fn from(error: DeRecError) -> Self {
        Self {
            error,
            events_json: empty_buffer(),
        }
    }
}

/// Process an inbound `DeRecMessage` envelope. See
/// [`crate::protocol::DeRecProtocol::process`].
///
/// # Safety
///
/// `handle` must be a valid pointer returned by
/// [`super::derec_protocol_new`]. `message_ptr`/`message_len` must
/// describe a readable byte range.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn derec_protocol_process(
    handle: *mut DeRecProtocolHandle,
    message_ptr: *const u8,
    message_len: usize,
) -> DeRecProtocolEventsResult {
    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 { std::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) => {
            let json = encode_events(events);
            DeRecProtocolEventsResult {
                error: success(),
                events_json: vec_into_buffer(json),
            }
        }
        Err(e) => from_lib_error(e.source).into(),
    }
}

/// Accept a pending action from an `ActionRequired` event. See
/// [`crate::protocol::DeRecProtocol::accept`]. The `action_bytes` blob
/// is the exact payload the caller received in the event — the FFI
/// wire format is the encoding produced by
/// [`crate::protocol::pending_action_wire::serialize`].
///
/// # Safety
///
/// `handle` must be a valid pointer returned by
/// [`super::derec_protocol_new`]. `action_ptr`/`action_len` must
/// describe a readable byte range.
#[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 { std::slice::from_raw_parts(action_ptr, action_len) };
    let action = match crate::protocol::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(),
    }
}

/// Reject a pending action from an `ActionRequired` event. See
/// [`crate::protocol::DeRecProtocol::reject`]. `status` matches
/// `derec_proto::StatusEnum` and `memo_ptr`/`memo_len` is an optional
/// UTF-8 string body (`memo_len == 0` for absent).
///
/// # Safety
///
/// `handle` must be a valid pointer returned by
/// [`super::derec_protocol_new`]. `action_ptr`/`action_len` must
/// describe a readable byte range.
#[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 { std::slice::from_raw_parts(action_ptr, action_len) };
    let action = match crate::protocol::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 { std::slice::from_raw_parts(memo_ptr, memo_len) };
        match std::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 derec_proto::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),
    }
}

/// Rebuild this protocol's `secret_id` namespace from a recovered
/// `Secret`. See [`crate::protocol::DeRecProtocol::restore`] for the
/// full contract and error semantics.
///
/// `params_json_*` is a UTF-8 JSON blob of the shape:
///
/// ```json
/// {
///   "version": 7,
///   "recovered_secret": {
///     "helpers": [{ "channel_id": "11", "transport_uri": "...",
///                   "shared_key": [..32 bytes..],
///                   "communication_info": {} }],
///     "secrets": [{ "id": [..], "name": "...", "data": [..] }],
///     "replicas": [{ "channel_id": "21", "transport_uri": "...",
///                    "replica_id": "0xCAFE", "sender_kind": 3,
///                    "communication_info": {} }],
///     "owner_replica_id": "48879",
///     "replica_group_shared_key": [..32 bytes..]
///   }
/// }
/// ```
///
/// Field names mirror `SecretWire` in `protocol/events/wire.rs` — the
/// same shape `SecretRecovered` carries. `channel_id`, `replica_id`,
/// and `owner_replica_id` are decimal `u64` strings (empty / absent
/// means zero).
///
/// # Safety
///
/// `handle` must be a valid pointer returned by
/// [`super::derec_protocol_new`]. `params_json_ptr`/`params_json_len`
/// must describe a readable byte range.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn derec_protocol_restore(
    handle: *mut DeRecProtocolHandle,
    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 or len == 0",
        )
        .into();
    }
    let bytes = unsafe { std::slice::from_raw_parts(params_json_ptr, params_json_len) };
    let json = match std::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);
            DeRecProtocolEventsResult {
                error: success(),
                events_json: vec_into_buffer(json),
            }
        }
        Err(e) => from_lib_error(e).into(),
    }
}

#[derive(serde::Deserialize)]
struct RestoreParamsJson {
    version: u32,
    recovered_secret: SecretJsonIn,
}

#[derive(serde::Deserialize)]
struct SecretJsonIn {
    #[serde(default)]
    helpers: Vec<HelperJsonIn>,
    #[serde(default)]
    secrets: Vec<UserSecretJsonIn>,
    #[serde(default)]
    replicas: Option<ReplicasJsonIn>,
    #[serde(default)]
    owner_replica_id: String,
}

#[derive(serde::Deserialize)]
struct ReplicasJsonIn {
    #[serde(default)]
    replicas: Vec<ReplicaJsonIn>,
    #[serde(default)]
    shared_key: Vec<u8>,
}

#[derive(serde::Deserialize)]
struct HelperJsonIn {
    channel_id: String,
    transport_uri: String,
    shared_key: Vec<u8>,
    #[serde(default)]
    communication_info: std::collections::HashMap<String, String>,
}

#[derive(serde::Deserialize)]
struct ReplicaJsonIn {
    channel_id: String,
    transport_uri: String,
    #[serde(default)]
    communication_info: std::collections::HashMap<String, String>,
    replica_id: String,
    sender_kind: i32,
}

#[derive(serde::Deserialize)]
struct UserSecretJsonIn {
    id: Vec<u8>,
    name: String,
    data: Vec<u8>,
}

impl SecretJsonIn {
    fn into_secret(self) -> Result<crate::protocol::types::Secret, String> {
        fn parse_u64(s: &str, ctx: &str) -> Result<u64, String> {
            if s.is_empty() {
                return Ok(0);
            }
            s.parse::<u64>()
                .map_err(|e| format!("{ctx} must be a u64 decimal string: {e}"))
        }

        let helpers = self
            .helpers
            .into_iter()
            .map(|h| -> Result<_, String> {
                Ok(crate::protocol::types::HelperInfo {
                    channel_id: parse_u64(&h.channel_id, "helper.channel_id")?,
                    transport_uri: h.transport_uri,
                    shared_key: h.shared_key,
                    communication_info: h.communication_info,
                })
            })
            .collect::<Result<Vec<_>, _>>()?;

        let replicas = self
            .replicas
            .map(|g| -> Result<_, String> {
                let replicas = g
                    .replicas
                    .into_iter()
                    .map(|r| -> Result<_, String> {
                        Ok(crate::protocol::types::ReplicaInfo {
                            channel_id: parse_u64(&r.channel_id, "replica.channel_id")?,
                            transport_uri: r.transport_uri,
                            communication_info: r.communication_info,
                            replica_id: parse_u64(&r.replica_id, "replica.replica_id")?,
                            sender_kind: r.sender_kind,
                        })
                    })
                    .collect::<Result<Vec<_>, _>>()?;
                Ok(crate::protocol::types::Replicas {
                    replicas,
                    shared_key: g.shared_key,
                })
            })
            .transpose()?;

        let secrets = self
            .secrets
            .into_iter()
            .map(|s| crate::protocol::types::UserSecret {
                id: s.id,
                name: s.name,
                data: s.data,
            })
            .collect();

        Ok(crate::protocol::types::Secret {
            helpers,
            secrets,
            replicas,
            owner_replica_id: parse_u64(&self.owner_replica_id, "owner_replica_id")?,
        })
    }
}