stoffelcrypto 0.1.0

Asynchronous HoneyBadgerMPC protocols, preprocessing, and arithmetic for Stoffel.
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
588
589
590
591
592
593
594
595
596
597
use std::{mem::ManuallyDrop, slice};

use ark_bls12_381::Fr;
use ark_ff::{BigInteger, PrimeField};

use crate::{
    common::{
        share::{
            shamir::{self, Shamirshare},
            ShareError,
        },
        SecretSharingScheme,
    },
    ffi::c_bindings::{ByteSlice, U256Slice, UsizeSlice, U256},
    honeybadger::robust_interpolate::{robust_interpolate, InterpolateError},
};

#[repr(C)]
pub enum ShareErrorCode {
    ShareSuccess,
    // Insufficient shares to reconstruct the secret
    InsufficientShares,
    // Mismatch degree between shares
    DegreeMismatch,
    // Mismatch index between shares
    IdMismatch,
    // Errors specific to invalid input parameters or conditions
    InvalidInput,
    // Types are different
    TypeMismatch,
    // No suitable FFT evaluation domain could be found
    NoSuitableDomain,
    // Errors related to polynomial operations, potentially with an underlying cause.
    PolynomialOperationError,
    // Errors that occur during the decoding process.
    DecodingError,
}
// opaque pointer for GenericField
#[repr(C)]
pub struct FieldOpaque {
    _data: (),
    _marker: core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>,
}

pub enum GenericField {
    Bls12_381Fr(Fr),
}

#[repr(C)]
pub enum FieldKind {
    Bls12_381Fr,
}

#[no_mangle]
pub extern "C" fn field_ptr_to_bytes(field: *mut FieldOpaque, be: bool) -> ByteSlice {
    let field_ref = unsafe { &*(field as *mut GenericField) };
    match field_ref {
        GenericField::Bls12_381Fr(f) => {
            let bytes = if be {
                f.into_bigint().to_bytes_be()
            } else {
                f.into_bigint().to_bytes_le()
            };
            let mut bytes = ManuallyDrop::new(bytes);
            ByteSlice {
                pointer: bytes.as_mut_ptr(),
                len: bytes.len(),
            }
        }
    }
}

#[repr(C)]
#[derive(Clone, Debug)]
pub struct ShamirShare {
    pub share: *mut FieldOpaque,
    pub id: usize,
    pub degree: usize,
}

#[repr(C)]
pub struct ShamirShareSlice {
    pub pointer: *mut ShamirShare,
    pub len: usize,
}

#[repr(C)]
#[derive(Clone, Debug)]
pub struct RobustShare {
    pub share: *mut FieldOpaque,
    pub id: usize,
    pub degree: usize,
}

#[repr(C)]
pub struct RobustShareSlice {
    pub pointer: *mut RobustShare,
    pub len: usize,
}

#[repr(C)]
#[derive(Clone, Debug)]
pub struct NonRobustShare {
    pub share: *mut FieldOpaque,
    pub id: usize,
    pub degree: usize,
}

#[repr(C)]
pub struct NonRobustShareSlice {
    pub pointer: *mut NonRobustShare,
    pub len: usize,
}

// free the memory of a Shamirshare
#[no_mangle]
pub extern "C" fn free_shamir_share(share: ShamirShare) {
    if !share.share.is_null() {
        unsafe {
            let _ = Box::from_raw(share.share as *mut GenericField);
        }
    }
}

// free the memory of a RobustShare
#[no_mangle]
pub extern "C" fn free_robust_share(share: RobustShare) {
    if !share.share.is_null() {
        unsafe {
            let _ = Box::from_raw(share.share as *mut GenericField);
        }
    }
}

// free the memory of a NonRobustShare
#[no_mangle]
pub extern "C" fn free_non_robust_share(share: NonRobustShare) {
    if !share.share.is_null() {
        unsafe {
            let _ = Box::from_raw(share.share as *mut GenericField);
        }
    }
}

// free the memory of a ShamirshareSlice
#[no_mangle]
pub extern "C" fn free_shamir_share_slice(slice: ShamirShareSlice) {
    if !slice.pointer.is_null() {
        for i in 0..slice.len {
            let share = unsafe { &*(slice.pointer.add(i)) };
            assert!(!share.share.is_null());
            unsafe {
                let _ = Box::from_raw(share.share as *mut GenericField);
            }
        }
        unsafe {
            let _ = Vec::from_raw_parts(slice.pointer, slice.len, slice.len);
        }
    }
}

// free the memory of a RobustShareSlice
#[no_mangle]
pub extern "C" fn free_robust_share_slice(slice: RobustShareSlice) {
    if !slice.pointer.is_null() {
        for i in 0..slice.len {
            let share = unsafe { &*(slice.pointer.add(i)) };
            assert!(!share.share.is_null());
            unsafe {
                let _ = Box::from_raw(share.share as *mut GenericField);
            }
        }
        unsafe {
            let _ = Vec::from_raw_parts(slice.pointer, slice.len, slice.len);
        }
    }
}

// free the memory of a NonRobustShareSlice
#[no_mangle]
pub extern "C" fn free_non_robust_share_slice(slice: NonRobustShareSlice) {
    if !slice.pointer.is_null() {
        for i in 0..slice.len {
            let share = unsafe { &*(slice.pointer.add(i)) };
            assert!(!share.share.is_null());
            unsafe {
                let _ = Box::from_raw(share.share as *mut GenericField);
            }
        }
        unsafe {
            let _ = Vec::from_raw_parts(slice.pointer, slice.len, slice.len);
        }
    }
}
impl From<ShamirShare> for Shamirshare<Fr> {
    fn from(value: ShamirShare) -> Self {
        let share_field = unsafe { &*(value.share as *mut GenericField) };
        let share_value = match share_field {
            GenericField::Bls12_381Fr(f) => *f,
        };
        Shamirshare::<Fr>::new(share_value, value.id, value.degree)
    }
}

impl From<Shamirshare<Fr>> for ShamirShare {
    fn from(value: Shamirshare<Fr>) -> Self {
        let share_enum = GenericField::Bls12_381Fr(value.share[0]);
        let share_ptr = Box::into_raw(Box::new(share_enum)) as *mut FieldOpaque;
        Self {
            share: share_ptr,
            id: value.id,
            degree: value.degree,
        }
    }
}

impl From<RobustShare> for robust_interpolate::RobustShare<Fr> {
    fn from(value: RobustShare) -> Self {
        let share_field = unsafe { &*(value.share as *mut GenericField) };
        let share_value = match share_field {
            GenericField::Bls12_381Fr(f) => *f,
        };
        robust_interpolate::RobustShare::<Fr>::new(share_value, value.id, value.degree)
    }
}

impl From<robust_interpolate::RobustShare<Fr>> for RobustShare {
    fn from(value: robust_interpolate::RobustShare<Fr>) -> Self {
        let share_enum = GenericField::Bls12_381Fr(value.share[0]);
        let share_ptr = Box::into_raw(Box::new(share_enum)) as *mut FieldOpaque;
        Self {
            share: share_ptr,
            id: value.id,
            degree: value.degree,
        }
    }
}

impl From<NonRobustShare> for shamir::NonRobustShare<Fr> {
    fn from(value: NonRobustShare) -> Self {
        let share_field = unsafe { &*(value.share as *mut GenericField) };
        let share_value = match share_field {
            GenericField::Bls12_381Fr(f) => *f,
        };
        shamir::NonRobustShare::<Fr>::new(share_value, value.id, value.degree)
    }
}

impl From<shamir::NonRobustShare<Fr>> for NonRobustShare {
    fn from(value: shamir::NonRobustShare<Fr>) -> Self {
        let share_enum = GenericField::Bls12_381Fr(value.share[0]);
        let share_ptr = Box::into_raw(Box::new(share_enum)) as *mut FieldOpaque;
        Self {
            share: share_ptr,
            id: value.id,
            degree: value.degree,
        }
    }
}

impl From<ShareError> for ShareErrorCode {
    fn from(e: ShareError) -> Self {
        match e {
            ShareError::InsufficientShares => Self::InsufficientShares,
            ShareError::DegreeMismatch => Self::DegreeMismatch,
            ShareError::IdMismatch => Self::IdMismatch,
            ShareError::InvalidInput => Self::InvalidInput,
            ShareError::TypeMismatch => Self::TypeMismatch,
            ShareError::NoSuitableDomain(_) => Self::NoSuitableDomain,
        }
    }
}

impl From<InterpolateError> for ShareErrorCode {
    fn from(e: InterpolateError) -> Self {
        match e {
            InterpolateError::PolynomialOperationError(_) => Self::PolynomialOperationError,
            InterpolateError::InvalidInput(_) => Self::InvalidInput,
            InterpolateError::DecodingError(_) => Self::DecodingError,
            InterpolateError::NoSuitableDomain(_) => Self::NoSuitableDomain,
            InterpolateError::ShareError(se) => se.into(),
        }
    }
}

// create new Shamirshare
#[no_mangle]
pub extern "C" fn shamir_share_new(
    secret: U256,
    id: usize,
    degree: usize,
    field_kind: FieldKind,
) -> ShamirShare {
    match field_kind {
        FieldKind::Bls12_381Fr => {
            let share = Shamirshare::<Fr>::new(secret.into(), id, degree).into();
            return share;
        }
    };
}

// compute the shamir shares of all ids for a secret
#[no_mangle]
pub extern "C" fn shamir_share_compute_shares(
    secret: U256,
    degree: usize,
    ids: Option<&UsizeSlice>,
    field_kind: FieldKind,
    output_shares: *mut ShamirShareSlice,
) -> ShareErrorCode {
    let mut rng = ark_std::rand::thread_rng();
    let ids = ids.and_then(|ids| {
        let ids_slice = unsafe { slice::from_raw_parts(ids.pointer, ids.len) };
        Some(ids_slice)
    });
    match field_kind {
        FieldKind::Bls12_381Fr => {
            let compute_result: Result<Vec<Shamirshare<Fr>>, ShareError> =
                Shamirshare::compute_shares(secret.into(), 0, degree, ids, &mut rng);
            match compute_result {
                Ok(shares) => {
                    let shares_vec = shares
                        .into_iter()
                        .map(|share| share.into())
                        .collect::<Vec<ShamirShare>>();
                    // prevent Rust from dropping the vec
                    let mut shares_vec = ManuallyDrop::new(shares_vec);
                    unsafe {
                        *output_shares = ShamirShareSlice {
                            pointer: shares_vec.as_mut_ptr(),
                            len: shares_vec.len(),
                        };
                    };
                    return ShareErrorCode::ShareSuccess;
                }
                Err(e) => return e.into(),
            }
        }
    }
}

// recover the secret of the input shares
#[no_mangle]
pub extern "C" fn shamir_share_recover_secret(
    shares: ShamirShareSlice,
    output_secret: *mut U256,
    output_coeffs: *mut U256Slice,
    field_kind: FieldKind,
) -> ShareErrorCode {
    let shares_slice = unsafe { Vec::from_raw_parts(shares.pointer, shares.len, shares.len) };
    // since the pointer comes from C, we should not drop it here
    // use free_shamir_share_bls12_slice() instead
    let shares_slice = ManuallyDrop::new(shares_slice);
    match field_kind {
        FieldKind::Bls12_381Fr => {
            let shares = shares_slice
                .iter()
                .map(|f| f.clone().into())
                .collect::<Vec<Shamirshare<Fr>>>();
            let recover_result = Shamirshare::recover_secret(&shares, 0, 0);
            match recover_result {
                Ok((coeffs, secret)) => {
                    let bls12fr_coeffs =
                        coeffs.into_iter().map(|c| c.into()).collect::<Vec<U256>>();
                    // prevent Rust from dropping the vec
                    let mut bls12fr_coeffs = ManuallyDrop::new(bls12fr_coeffs);
                    let coeffs_pointer = U256Slice {
                        pointer: bls12fr_coeffs.as_mut_ptr(),
                        len: bls12fr_coeffs.len(),
                    };
                    // store results to the pointer
                    unsafe {
                        *output_coeffs = coeffs_pointer;
                        *output_secret = secret.into();
                    }

                    return ShareErrorCode::ShareSuccess;
                }
                Err(e) => return e.into(),
            }
        }
    }
}

// create new RobustShare
#[no_mangle]
pub extern "C" fn robust_share_new(
    secret: U256,
    id: usize,
    degree: usize,
    field_kind: FieldKind,
) -> RobustShare {
    match field_kind {
        FieldKind::Bls12_381Fr => {
            let share =
                robust_interpolate::RobustShare::<Fr>::new(secret.into(), id, degree).into();
            return share;
        }
    };
}

/// Generates `n` secret shares for a `value` using a degree `t` polynomial,
/// such that `f(0) = value`. Any `t + 1` shares can reconstruct the secret.
///
/// Shares are evaluations of `f(x)` on an FFT domain.
///
/// # Errors
/// - `InvalidInput` if `n` is not greater than `t`.
/// - `NoSuitableDomain` if a suitable FFT evaluation domain of size `n` isn't found.
#[no_mangle]
pub extern "C" fn robust_share_compute_shares(
    secret: U256,
    degree: usize,
    n: usize,
    output_shares: *mut RobustShareSlice,
    field_kind: FieldKind,
) -> ShareErrorCode {
    let mut rng = ark_std::rand::thread_rng();
    match field_kind {
        FieldKind::Bls12_381Fr => {
            let compute_result: Result<Vec<robust_interpolate::RobustShare<Fr>>, InterpolateError> =
                robust_interpolate::RobustShare::compute_shares(
                    secret.into(),
                    n,
                    degree,
                    None,
                    &mut rng,
                );
            match compute_result {
                Ok(shares) => {
                    let shares_vec = shares
                        .into_iter()
                        .map(|share| share.into())
                        .collect::<Vec<RobustShare>>();
                    // prevent Rust from dropping the vec
                    let mut shares_vec = ManuallyDrop::new(shares_vec);
                    let output_shares_t = RobustShareSlice {
                        pointer: shares_vec.as_mut_ptr(),
                        len: shares_vec.len(),
                    };
                    let ptr = Box::into_raw(Box::new(output_shares_t)) as *mut RobustShareSlice;
                    unsafe {
                        *output_shares = *Box::from_raw(ptr);
                    }

                    return ShareErrorCode::ShareSuccess;
                }
                Err(e) => return e.into(),
            }
        }
    }
}

/// Full robust interpolation combining optimistic decoding and error correction
///
/// # Arguments
/// * `n` - total number of shares
/// * `shares` - pointer to the RobustShareSlice, unordered
#[no_mangle]
pub extern "C" fn robust_share_recover_secret(
    shares: RobustShareSlice,
    n: usize,
    t: usize,
    output_secret: *mut U256,
    output_coeffs: *mut U256Slice,
    field_kind: FieldKind,
) -> ShareErrorCode {
    let shares_slice = unsafe { Vec::from_raw_parts(shares.pointer, shares.len, shares.len) };
    // since the pointer comes from C, we should not drop it here
    // use free_robust_share_bls12_slice() instead
    let shares_slice = ManuallyDrop::new(shares_slice);
    match field_kind {
        FieldKind::Bls12_381Fr => {
            let shares = shares_slice
                .iter()
                .map(|f| f.clone().into())
                .collect::<Vec<robust_interpolate::RobustShare<Fr>>>();
            let recover_result = robust_interpolate::RobustShare::recover_secret(&shares, n, t);
            match recover_result {
                Ok((coeffs, secret)) => {
                    let bls12fr_coeffs =
                        coeffs.into_iter().map(|c| c.into()).collect::<Vec<U256>>();
                    // prevent Rust from dropping the vec
                    let mut bls12fr_coeffs = ManuallyDrop::new(bls12fr_coeffs);
                    // store results to the pointer
                    unsafe {
                        *output_coeffs = U256Slice {
                            pointer: bls12fr_coeffs.as_mut_ptr(),
                            len: bls12fr_coeffs.len(),
                        };
                        *output_secret = secret.into();
                    }

                    return ShareErrorCode::ShareSuccess;
                }
                Err(e) => return e.into(),
            }
        }
    }
}

// create new NonRobustShare
#[no_mangle]
pub extern "C" fn non_robust_share_new(
    secret: U256,
    id: usize,
    degree: usize,
    field_kind: FieldKind,
) -> NonRobustShare {
    match field_kind {
        FieldKind::Bls12_381Fr => {
            let share = shamir::NonRobustShare::<Fr>::new(secret.into(), id, degree).into();
            return share;
        }
    };
}

// compute the non-robust shamir shares for a secret
#[no_mangle]
pub extern "C" fn non_robust_share_compute_shares(
    secret: U256,
    degree: usize,
    n: usize,
    output_shares: *mut NonRobustShareSlice,
    field_kind: FieldKind,
) -> ShareErrorCode {
    let mut rng = ark_std::rand::thread_rng();

    match field_kind {
        FieldKind::Bls12_381Fr => {
            let compute_result: Result<Vec<shamir::NonRobustShare<Fr>>, ShareError> =
                shamir::NonRobustShare::compute_shares(secret.into(), n, degree, None, &mut rng);
            match compute_result {
                Ok(shares) => {
                    let shares_vec = shares
                        .into_iter()
                        .map(|share| share.into())
                        .collect::<Vec<NonRobustShare>>();
                    // prevent Rust from dropping the vec
                    let mut shares_vec = ManuallyDrop::new(shares_vec);
                    unsafe {
                        *output_shares = NonRobustShareSlice {
                            pointer: shares_vec.as_mut_ptr(),
                            len: shares_vec.len(),
                        };
                    }

                    return ShareErrorCode::ShareSuccess;
                }
                Err(e) => return e.into(),
            }
        }
    }
}

// recover the secret of the input shares
#[no_mangle]
pub extern "C" fn non_robust_share_recover_secret(
    shares: NonRobustShareSlice,
    n: usize,
    output_secret: *mut U256,
    output_coeffs: *mut U256Slice,
    field_kind: FieldKind,
) -> ShareErrorCode {
    let shares_slice = unsafe { Vec::from_raw_parts(shares.pointer, shares.len, shares.len) };
    // since the pointer comes from C, we should not drop it here
    // use free_non_robust_share_bls12_slice() instead
    let shares_slice = ManuallyDrop::new(shares_slice);
    match field_kind {
        FieldKind::Bls12_381Fr => {
            let shares = shares_slice
                .iter()
                .map(|f| f.clone().into())
                .collect::<Vec<shamir::NonRobustShare<Fr>>>();
            let recover_result = shamir::NonRobustShare::recover_secret(&shares, n, 0);
            match recover_result {
                Ok((coeffs, secret)) => {
                    let bls12fr_coeffs =
                        coeffs.into_iter().map(|c| c.into()).collect::<Vec<U256>>();
                    // prevent Rust from dropping the vec
                    let mut bls12fr_coeffs = ManuallyDrop::new(bls12fr_coeffs);
                    // store results to the pointer
                    unsafe {
                        *output_coeffs = U256Slice {
                            pointer: bls12fr_coeffs.as_mut_ptr(),
                            len: bls12fr_coeffs.len(),
                        };
                        *output_secret = secret.into()
                    }

                    return ShareErrorCode::ShareSuccess;
                }
                Err(e) => return e.into(),
            }
        }
    }
}