derec-library 0.0.9

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
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 DeRec Alliance. All rights reserved.

//! C FFI for the DeRec sharing flow.
//!
//! Protocol semantics live in `library/src/primitives/sharing/`. Items below
//! describe only the FFI surface and the custom binary format used to ferry
//! the per-channel committed shares.
//!
//! # Committed-shares binary format
//!
//! [`protect_secret`] returns its share set as a single FFI container:
//!
//! ```text
//! [count: u32 LE]
//! for each entry (sorted by channel ID):
//!   [channel_id: u64 LE]
//!   [share_len: u32 LE]
//!   [serialized CommittedDeRecShare protobuf]
//! ```
//!
//! # Weighted channels
//!
//! [`protect_secret`] takes the channels to share with as two aligned arrays
//! of `channels_len` entries: `channels_ptr[i]` is a channel ID and
//! `weights_ptr[i]` its weight, the number of subshares that channel's share
//! carries. Every channel is listed with its weight; an ordinary Helper has
//! weight `1`. When `channels_len > 0` both pointers must be non-null.

use crate::{
    interop::ffi::common::{
        DeRecBuffer, empty_buffer, parse_transport_protocol_list, vec_into_buffer,
        write_len_prefixed, write_u32_le, write_u64_le,
    },
    interop::ffi::error::{
        DEREC_CODE_FFI_BAD_PROTO, DEREC_CODE_FFI_BAD_SHARED_KEY, DEREC_CODE_FFI_BAD_UTF8,
        DEREC_CODE_FFI_NULL_PTR, DeRecError, ffi_error, from_lib_error, success,
    },
    types::{ChannelId, WeightedChannel},
};
use derec_proto::{
    CommittedDeRecShare, DeRecMessage, StoreShareRequestMessage, StoreShareResponseMessage,
};
use prost::Message as _;
use std::collections::HashMap;
use std::str;

#[repr(C)]
pub struct ProtectSecretResult {
    pub error: DeRecError,
    /// Committed shares in the format documented at the module level.
    pub shares_wire_bytes: DeRecBuffer,
}

#[repr(C)]
pub struct ProduceStoreShareRequestMessageResult {
    pub error: DeRecError,
    pub wire_bytes: DeRecBuffer,
}

#[repr(C)]
pub struct ExtractStoreShareRequestResult {
    pub error: DeRecError,
    pub channel_id: u64,
    /// Inner `StoreShareRequestMessage` proto bytes for chaining into
    /// [`produce_store_share_response_message`].
    pub request_proto_bytes: DeRecBuffer,
}

/// `committed_share_bytes` is the serialized [`CommittedDeRecShare`] the
/// helper should persist locally for later recovery responses.
#[repr(C)]
pub struct ProduceStoreShareResponseMessageResult {
    pub error: DeRecError,
    pub wire_bytes: DeRecBuffer,
    pub committed_share_bytes: DeRecBuffer,
    pub secret_id: u64,
    pub version: u32,
}

#[repr(C)]
pub struct ExtractStoreShareResponseResult {
    pub error: DeRecError,
    pub channel_id: u64,
    /// Inner `StoreShareResponseMessage` proto bytes for chaining into
    /// [`process_store_share_response_message`].
    pub response_proto_bytes: DeRecBuffer,
}

#[repr(C)]
pub struct ProcessStoreShareResponseMessageResult {
    pub error: DeRecError,
}

/// Splits `secret_data` into one committed share per weighted channel; see
/// [`crate::primitives::sharing::request::split`] for the weight and threshold
/// rules. Channels are given as the aligned `channels_ptr` / `weights_ptr`
/// arrays described in the module-level "Weighted channels" section; the
/// result does not depend on the order they are listed in.
///
/// # Safety
///
/// Non-null input pointers must point to the corresponding readable ranges:
/// `secret_data_len` bytes, and `channels_len` entries for each of
/// `channels_ptr` and `weights_ptr`.
#[unsafe(no_mangle)]
#[allow(clippy::too_many_arguments)]
pub extern "C" fn protect_secret(
    secret_id: u64,
    secret_data_ptr: *const u8,
    secret_data_len: usize,
    channels_ptr: *const u64,
    weights_ptr: *const u32,
    channels_len: usize,
    threshold: usize,
    version: u32,
) -> ProtectSecretResult {
    let with_err = |error| ProtectSecretResult {
        error,
        shares_wire_bytes: empty_buffer(),
    };

    let secret_data = match parse_buffer(secret_data_ptr, secret_data_len, "secret_data_ptr") {
        Ok(b) => b,
        Err(e) => return with_err(e),
    };
    let channels = match parse_weighted_channels(channels_ptr, weights_ptr, channels_len) {
        Ok(c) => c,
        Err(e) => return with_err(e),
    };

    match crate::primitives::sharing::request::split(
        &channels,
        secret_id,
        version,
        secret_data,
        threshold,
    ) {
        Ok(r) => ProtectSecretResult {
            error: success(),
            shares_wire_bytes: vec_into_buffer(serialize_committed_shares(&r.shares)),
        },
        Err(e) => with_err(from_lib_error(e)),
    }
}

/// # Safety
///
/// Non-null input pointers must point to the corresponding readable byte ranges.
#[unsafe(no_mangle)]
#[allow(clippy::too_many_arguments)]
pub extern "C" fn produce_store_share_request_message(
    channel_id: u64,
    version: u32,
    secret_id: u64,
    committed_share_ptr: *const u8,
    committed_share_len: usize,
    keep_list_ptr: *const u32,
    keep_list_len: usize,
    description_ptr: *const u8,
    description_len: usize,
    shared_key_ptr: *const u8,
    shared_key_len: usize,
    // `reply_to` is optional: pass `reply_to_len == 0` for "no override"
    // (the responder routes to the transports recorded for the channel).
    // When set, the bytes are a length-delimited sequence of
    // protobuf-encoded `TransportProtocol` entries, each preceded by its
    // varint byte length, in preference order; the responder answers this
    // exchange there without persisting the endpoints.
    reply_to_ptr: *const u8,
    reply_to_len: usize,
) -> ProduceStoreShareRequestMessageResult {
    let with_err = |error| ProduceStoreShareRequestMessageResult {
        error,
        wire_bytes: empty_buffer(),
    };

    let committed_share_bytes = match parse_buffer(
        committed_share_ptr,
        committed_share_len,
        "committed_share_ptr",
    ) {
        Ok(b) => b,
        Err(e) => return with_err(e),
    };
    if keep_list_ptr.is_null() && keep_list_len > 0 {
        return with_err(ffi_error(DEREC_CODE_FFI_NULL_PTR, "keep_list_ptr is null"));
    }
    let keep_list: &[u32] = if keep_list_len == 0 {
        &[]
    } else {
        unsafe { std::slice::from_raw_parts(keep_list_ptr, keep_list_len) }
    };
    let description_bytes = match parse_buffer(description_ptr, description_len, "description_ptr")
    {
        Ok(b) => b,
        Err(e) => return with_err(e),
    };
    let description = match str::from_utf8(description_bytes) {
        Ok(s) => s,
        Err(_) => {
            return with_err(ffi_error(
                DEREC_CODE_FFI_BAD_UTF8,
                "description is not valid UTF-8",
            ));
        }
    };
    let shared_key = match parse_shared_key(shared_key_ptr, shared_key_len) {
        Ok(k) => k,
        Err(e) => return with_err(e),
    };

    let committed_share = match CommittedDeRecShare::decode(committed_share_bytes) {
        Ok(s) => s,
        Err(e) => {
            return with_err(ffi_error(
                DEREC_CODE_FFI_BAD_PROTO,
                format!("failed to decode CommittedDeRecShare: {e}"),
            ));
        }
    };

    let reply_to = match parse_transport_protocol_list(reply_to_ptr, reply_to_len, "reply_to_ptr") {
        Ok(rt) => rt,
        Err(e) => return with_err(e),
    };

    match crate::primitives::sharing::request::produce(
        ChannelId(channel_id),
        version,
        secret_id,
        &committed_share,
        keep_list,
        description,
        &shared_key,
        &reply_to,
    ) {
        Ok(r) => ProduceStoreShareRequestMessageResult {
            error: success(),
            wire_bytes: vec_into_buffer(r.envelope),
        },
        Err(e) => with_err(from_lib_error(e)),
    }
}

/// # Safety
///
/// Non-null input pointers must point to the corresponding readable byte ranges.
#[unsafe(no_mangle)]
pub extern "C" fn extract_store_share_request(
    request_ptr: *const u8,
    request_len: usize,
    shared_key_ptr: *const u8,
    shared_key_len: usize,
) -> ExtractStoreShareRequestResult {
    let with_err = |error| ExtractStoreShareRequestResult {
        error,
        channel_id: 0,
        request_proto_bytes: empty_buffer(),
    };

    let request_bytes = match parse_buffer(request_ptr, request_len, "request_ptr") {
        Ok(b) => b,
        Err(e) => return with_err(e),
    };
    let shared_key = match parse_shared_key(shared_key_ptr, shared_key_len) {
        Ok(k) => k,
        Err(e) => return with_err(e),
    };

    let channel_id = match DeRecMessage::decode(request_bytes) {
        Ok(e) => e.channel_id,
        Err(e) => {
            return with_err(ffi_error(
                DEREC_CODE_FFI_BAD_PROTO,
                format!("failed to decode envelope: {e}"),
            ));
        }
    };

    match crate::primitives::sharing::request::extract(request_bytes, &shared_key) {
        Ok(r) => ExtractStoreShareRequestResult {
            error: success(),
            channel_id,
            request_proto_bytes: vec_into_buffer(r.request.encode_to_vec()),
        },
        Err(e) => with_err(from_lib_error(e)),
    }
}

/// `request_proto_ptr` / `request_proto_len` must be the `request_proto_bytes`
/// returned by [`extract_store_share_request`].
///
/// # Safety
///
/// Non-null input pointers must point to the corresponding readable byte ranges.
#[unsafe(no_mangle)]
pub extern "C" fn produce_store_share_response_message(
    channel_id: u64,
    request_proto_ptr: *const u8,
    request_proto_len: usize,
    shared_key_ptr: *const u8,
    shared_key_len: usize,
) -> ProduceStoreShareResponseMessageResult {
    let with_err = |error| ProduceStoreShareResponseMessageResult {
        error,
        wire_bytes: empty_buffer(),
        committed_share_bytes: empty_buffer(),
        secret_id: 0,
        version: 0,
    };

    let request_bytes =
        match parse_buffer(request_proto_ptr, request_proto_len, "request_proto_ptr") {
            Ok(b) => b,
            Err(e) => return with_err(e),
        };
    let shared_key = match parse_shared_key(shared_key_ptr, shared_key_len) {
        Ok(k) => k,
        Err(e) => return with_err(e),
    };

    let request = match StoreShareRequestMessage::decode(request_bytes) {
        Ok(r) => r,
        Err(e) => {
            return with_err(ffi_error(
                DEREC_CODE_FFI_BAD_PROTO,
                format!("failed to decode request: {e}"),
            ));
        }
    };

    match crate::primitives::sharing::response::produce(
        ChannelId(channel_id),
        &request,
        &shared_key,
    ) {
        Ok(r) => ProduceStoreShareResponseMessageResult {
            error: success(),
            wire_bytes: vec_into_buffer(r.envelope),
            committed_share_bytes: vec_into_buffer(r.committed_share.encode_to_vec()),
            secret_id: r.secret_id,
            version: r.version,
        },
        Err(e) => with_err(from_lib_error(e)),
    }
}

/// # Safety
///
/// Non-null input pointers must point to the corresponding readable byte ranges.
#[unsafe(no_mangle)]
pub extern "C" fn extract_store_share_response(
    response_ptr: *const u8,
    response_len: usize,
    shared_key_ptr: *const u8,
    shared_key_len: usize,
) -> ExtractStoreShareResponseResult {
    let with_err = |error| ExtractStoreShareResponseResult {
        error,
        channel_id: 0,
        response_proto_bytes: empty_buffer(),
    };

    let response_bytes = match parse_buffer(response_ptr, response_len, "response_ptr") {
        Ok(b) => b,
        Err(e) => return with_err(e),
    };
    let shared_key = match parse_shared_key(shared_key_ptr, shared_key_len) {
        Ok(k) => k,
        Err(e) => return with_err(e),
    };

    let channel_id = match DeRecMessage::decode(response_bytes) {
        Ok(e) => e.channel_id,
        Err(e) => {
            return with_err(ffi_error(
                DEREC_CODE_FFI_BAD_PROTO,
                format!("failed to decode envelope: {e}"),
            ));
        }
    };

    match crate::primitives::sharing::response::extract(response_bytes, &shared_key) {
        Ok(r) => ExtractStoreShareResponseResult {
            error: success(),
            channel_id,
            response_proto_bytes: vec_into_buffer(r.response.encode_to_vec()),
        },
        Err(e) => with_err(from_lib_error(e)),
    }
}

/// `response_proto_ptr` / `response_proto_len` must be the
/// `response_proto_bytes` returned by [`extract_store_share_response`].
///
/// # Safety
///
/// Non-null input pointers must point to the corresponding readable byte ranges.
#[unsafe(no_mangle)]
pub extern "C" fn process_store_share_response_message(
    version: u32,
    response_proto_ptr: *const u8,
    response_proto_len: usize,
) -> ProcessStoreShareResponseMessageResult {
    let with_err = |error| ProcessStoreShareResponseMessageResult { error };

    let response_bytes =
        match parse_buffer(response_proto_ptr, response_proto_len, "response_proto_ptr") {
            Ok(b) => b,
            Err(e) => return with_err(e),
        };

    let response = match StoreShareResponseMessage::decode(response_bytes) {
        Ok(r) => r,
        Err(e) => {
            return with_err(ffi_error(
                DEREC_CODE_FFI_BAD_PROTO,
                format!("failed to decode response: {e}"),
            ));
        }
    };

    match crate::primitives::sharing::response::process(version, &response) {
        Ok(()) => ProcessStoreShareResponseMessageResult { error: success() },
        Err(e) => with_err(from_lib_error(e)),
    }
}

fn serialize_committed_shares(shares: &HashMap<ChannelId, CommittedDeRecShare>) -> Vec<u8> {
    let mut entries: Vec<_> = shares.iter().collect();
    entries.sort_by_key(|(channel_id, _)| <u64 as From<ChannelId>>::from(**channel_id));

    let mut out = Vec::new();

    let count = u32::try_from(entries.len()).expect("too many share entries");
    write_u32_le(&mut out, count);

    for (channel_id, share) in entries {
        write_u64_le(&mut out, <u64 as From<ChannelId>>::from(*channel_id));
        write_len_prefixed(&mut out, &share.encode_to_vec());
    }

    out
}

/// Pairs each channel ID with its weight from the two aligned arrays
/// described in the module-level "Weighted channels" section.
fn parse_weighted_channels(
    channels_ptr: *const u64,
    weights_ptr: *const u32,
    len: usize,
) -> Result<Vec<WeightedChannel>, DeRecError> {
    if len == 0 {
        return Ok(Vec::new());
    }
    if channels_ptr.is_null() {
        return Err(ffi_error(DEREC_CODE_FFI_NULL_PTR, "channels_ptr is null"));
    }
    if weights_ptr.is_null() {
        return Err(ffi_error(DEREC_CODE_FFI_NULL_PTR, "weights_ptr is null"));
    }
    let channels = unsafe { std::slice::from_raw_parts(channels_ptr, len) };
    let weights = unsafe { std::slice::from_raw_parts(weights_ptr, len) };
    Ok(channels
        .iter()
        .zip(weights)
        .map(|(&channel_id, &weight)| (ChannelId(channel_id), weight))
        .collect())
}

fn parse_buffer<'a>(ptr: *const u8, len: usize, name: &str) -> Result<&'a [u8], DeRecError> {
    if ptr.is_null() && len > 0 {
        return Err(ffi_error(
            DEREC_CODE_FFI_NULL_PTR,
            format!("{name} is null"),
        ));
    }
    if len == 0 {
        Ok(&[])
    } else {
        Ok(unsafe { std::slice::from_raw_parts(ptr, len) })
    }
}

fn parse_shared_key(ptr: *const u8, len: usize) -> Result<[u8; 32], DeRecError> {
    let bytes = parse_buffer(ptr, len, "shared_key_ptr")?;
    bytes.try_into().map_err(|_| {
        ffi_error(
            DEREC_CODE_FFI_BAD_SHARED_KEY,
            "shared_key must be exactly 32 bytes",
        )
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::interop::ffi::common::derec_free_buffer;
    use derec_proto::DeRecShare;

    /// Decodes the committed-shares container into each channel's subshare count.
    fn subshare_counts(result: ProtectSecretResult) -> HashMap<u64, usize> {
        assert_eq!(result.error.code, 0, "protect_secret should succeed");
        let buffer = result.shares_wire_bytes;
        let bytes = unsafe { std::slice::from_raw_parts(buffer.ptr, buffer.len) }.to_vec();
        derec_free_buffer(buffer.ptr, buffer.len);

        let read_u32 = |at: usize| u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap());
        let read_u64 = |at: usize| u64::from_le_bytes(bytes[at..at + 8].try_into().unwrap());
        let count = read_u32(0) as usize;
        let mut offset = 4;
        let mut counts = HashMap::new();
        for _ in 0..count {
            let channel_id = read_u64(offset);
            let share_len = read_u32(offset + 8) as usize;
            offset += 12;
            let committed = CommittedDeRecShare::decode(&bytes[offset..offset + share_len])
                .expect("committed share should decode");
            offset += share_len;
            let share =
                DeRecShare::decode(&committed.de_rec_share[..]).expect("inner share should decode");
            counts.insert(channel_id, share.subshares.len());
        }
        counts
    }

    fn protect(channels: &[u64], weights: &[u32], threshold: usize) -> ProtectSecretResult {
        let secret = b"super_secret_value";
        protect_secret(
            42,
            secret.as_ptr(),
            secret.len(),
            channels.as_ptr(),
            weights.as_ptr(),
            channels.len(),
            threshold,
            1,
        )
    }

    #[test]
    fn protect_secret_with_unit_weights_gives_each_channel_one_subshare() {
        let counts = subshare_counts(protect(&[1, 2, 3], &[1, 1, 1], 2));
        assert_eq!(counts, HashMap::from([(1, 1), (2, 1), (3, 1)]));
    }

    #[test]
    fn protect_secret_gives_a_weighted_channel_its_subshares() {
        let counts = subshare_counts(protect(&[3, 1, 2], &[2, 1, 1], 3));
        assert_eq!(counts, HashMap::from([(1, 1), (2, 1), (3, 2)]));
    }

    #[test]
    fn protect_secret_rejects_a_null_weights_pointer_with_a_length() {
        let secret = b"super_secret_value";
        let channels = [1u64, 2, 3];
        let result = protect_secret(
            42,
            secret.as_ptr(),
            secret.len(),
            channels.as_ptr(),
            std::ptr::null(),
            channels.len(),
            2,
            1,
        );
        assert_eq!(result.error.code, DEREC_CODE_FFI_NULL_PTR);
    }

    #[test]
    fn protect_secret_rejects_a_null_channels_pointer_with_a_length() {
        let secret = b"super_secret_value";
        let weights = [1u32, 1, 1];
        let result = protect_secret(
            42,
            secret.as_ptr(),
            secret.len(),
            std::ptr::null(),
            weights.as_ptr(),
            weights.len(),
            2,
            1,
        );
        assert_eq!(result.error.code, DEREC_CODE_FFI_NULL_PTR);
    }
}