scale-core 0.1.2

low level datastructures and functionality for compiling for SCALE via wasm
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
// Copyright (c) 2021, COSIC-KU Leuven, Kasteelpark Arenberg 10, bus 2452, B-3001 Leuven-Heverlee, Belgium.
// Copyright (c) 2021, Cosmian Tech SAS, 53-55 rue La Boétie, Paris, France.

#![cfg_attr(not(feature = "emulate"), no_std)]
#![cfg_attr(not(feature = "emulate"), feature(wasm_simd, simd_ffi))]

#[cfg(feature = "emulate")]
pub use std::process::exit;

scale_impl_generator::impls!();

#[cfg(not(feature = "emulate"))]
mod types {
    #[repr(transparent)]
    #[derive(Copy, Clone)]
    pub struct ClearModp(pub core::arch::wasm32::v128);
    #[repr(transparent)]
    #[derive(Copy, Clone)]
    pub struct SecretModp(f32);
    #[repr(transparent)]
    #[derive(Copy, Clone)]
    pub struct SecretI64(f64);
    #[repr(transparent)]
    #[derive(Copy, Clone)]
    pub struct SecretBit(pub(crate) SecretModp);
    #[repr(transparent)]
    #[derive(Copy, Clone)]
    pub struct RawSecretBit(pub(crate) f64);
}

#[cfg(feature = "emulate")]
mod types {
    #[repr(transparent)]
    #[derive(Copy, Clone)]
    pub struct ClearModp(pub(crate) i64);
    #[repr(transparent)]
    #[derive(Copy, Clone)]
    pub struct SecretModp(pub(crate) ClearModp);
    #[repr(transparent)]
    #[derive(Copy, Clone)]
    pub struct SecretI64(pub(crate) i64);
    #[repr(transparent)]
    #[derive(Copy, Clone)]
    // FIXME: use `bool` as the field
    pub struct SecretBit(pub(crate) i64);
    // Due to the fact that our rust -> wasm -> scasm pipeline
    // does not support `externref` yet, so we can't properly
    // encode more than 4 different register types, we need
    // to have this hacky datastructure that the raw asm
    // instructions use.
    #[repr(transparent)]
    #[derive(Copy, Clone)]
    pub struct RawSecretBit(pub(crate) i64);
}

pub use types::*;

macro_rules! any_register {
    ($($bound:path),*) => {
        /// A helper trait that is implemented for all register types
        /// and has bounds for all operations implemented by those types.
        /// This allows one to easily write code that is generic over
        /// the various register types.
        pub trait AnyRegister: $($bound+)* Sized {}
    };
}

impl AnyRegister for ClearModp {}
impl AnyRegister for SecretModp {}
impl AnyRegister for i64 {}
impl AnyRegister for SecretI64 {}

use core::ops::*;

any_register! {
    Stack,
    alloc::GetAllocator,
    Add<Output = Self>,
    Sub<Output = Self>,
    Mul<Output = Self>,
    StoreInMem<i64>,
    LoadFromMem<i64>
}

pub trait InnerModp:
    AnyRegister
    + From<ClearModp>
    + Into<SecretModp>
    + RevealIfSecret
    + Mul<ClearModp, Output = Self>
    + Add<ClearModp, Output = Self>
    + Sub<ClearModp, Output = Self>
    + Mul<SecretModp, Output = SecretModp>
    + Add<SecretModp, Output = SecretModp>
    + Sub<SecretModp, Output = SecretModp>
{
}

impl InnerModp for ClearModp {}
impl InnerModp for SecretModp {}

pub trait Modp<Other: InnerModp>:
    InnerModp
    + Mul<Other, Output = SecretModp>
    + Add<Other, Output = SecretModp>
    + Sub<Other, Output = SecretModp>
{
}

impl Modp<ClearModp> for SecretModp {}
impl Modp<SecretModp> for ClearModp {}
impl Modp<SecretModp> for SecretModp {}

pub trait StoreInMem<Index> {
    /// Internal operation for writing to memory. If you want
    /// to use memory, consider using one of the safe wrappers like
    /// `Array`, `Slice` or `Box`.
    unsafe fn store_in_mem(&self, idx: Index);
}

pub trait LoadFromMem<Index> {
    fn load_from_mem(idx: Index) -> Self;
}

impl<T: StoreInMem<i64>> StoreInMem<(i64, i64)> for Option<T> {
    unsafe fn store_in_mem(&self, idk: (i64, i64)) {
        match self {
            None => 0_i64.store_in_mem(idk.0),
            Some(a) => {
                1_i64.store_in_mem(idk.0);
                a.store_in_mem(idk.1);
            }
        };
    }
}

impl<T: LoadFromMem<i64>> LoadFromMem<(i64, i64)> for Option<T> {
    fn load_from_mem(idk: (i64, i64)) -> Option<T> {
        let ind = i64::load_from_mem(idk.0);
        match ind {
            1 => Some(T::load_from_mem(idk.1)),
            _ => None,
        }
    }
}

mod stack_address;

#[repr(transparent)]
#[derive(Copy, Clone)]
pub struct StackAddress(i64);

pub trait Stack {
    /// Push a new item to the stack
    ///
    /// SAFETY: this function is unsafe, because runtime function calls also
    /// generate these instructions, and thus modifying the stack must be done
    /// very carefully.
    unsafe fn push(val: &Self);
    /// Read and remove the top item from the stack
    ///
    /// SAFETY: this function is unsafe, because runtime function calls also
    /// generate these instructions, and thus modifying the stack must be done
    /// very carefully.
    unsafe fn pop() -> Self;
    /// Read an item at the given stack address
    unsafe fn peek(addr: StackAddress) -> Self;
    /// Replace the item at the given stack address
    ///
    /// SAFETY: this function is unsafe, because runtime function calls also
    /// generate these instructions, and thus modifying the stack must be done
    /// very carefully.
    unsafe fn poke(addr: StackAddress, val: &Self);
    /// Get the stack address of the top most element on the stack
    fn get_stack_pointer() -> StackAddress;
    /// Get the value at the stack address "stackpointer - offset"
    unsafe fn peek_from_top(offset: i64) -> Self;
    /// Overwrite the value at the stack address "stackpointer - offset"
    unsafe fn poke_from_top(offset: i64, val: &Self);
}

use core::mem::MaybeUninit;

impl<T: alloc::GetAllocator + Stack, const N: usize> Stack for [T; N] {
    #[inline(always)]
    unsafe fn push(array: &Self) {
        for val in array.iter() {
            T::push(&val);
        }
    }
    #[inline(always)]
    unsafe fn pop() -> Self {
        let mut array: [MaybeUninit<T>; N] = MaybeUninit::uninit().assume_init();
        for i in (0..N).rev() {
            array[i] = MaybeUninit::new(T::pop());
        }
        core::mem::transmute_copy(&array)
    }

    #[inline(always)]
    unsafe fn peek(addr: StackAddress) -> Self {
        let mut array: [MaybeUninit<T>; N] = MaybeUninit::uninit().assume_init();
        for i in 0..N {
            array[i] = MaybeUninit::new(T::peek(addr + i as _));
        }
        core::mem::transmute_copy(&array)
    }

    #[inline(always)]
    unsafe fn poke(addr: StackAddress, array: &Self) {
        for (i, val) in array.iter().enumerate() {
            T::poke(addr + i as _, &val);
        }
    }

    #[inline(always)]
    unsafe fn peek_from_top(offset: i64) -> Self {
        let mut array: [MaybeUninit<T>; N] = MaybeUninit::uninit().assume_init();
        for i in 0..N {
            array[i] = MaybeUninit::new(T::peek_from_top(offset + i as i64));
        }
        core::mem::transmute_copy(&array)
    }

    #[inline(always)]
    unsafe fn poke_from_top(offset: i64, array: &Self) {
        for (i, val) in array.iter().enumerate() {
            T::poke_from_top(offset + i as i64, &val);
        }
    }

    #[inline(always)]
    fn get_stack_pointer() -> StackAddress {
        panic!("this operation makes no sense")
    }
}

pub trait Reveal {
    type Output;
    fn reveal(&self) -> Self::Output;
}

pub trait RevealIfSecret {
    type Output;
    fn reveal_if_secret(&self) -> Self::Output;
}

mod clear_modp;
mod i64;
mod io;
mod print;
mod secret_bit;
mod secret_i64;
mod secret_modp;
mod system;

pub use io::*;
pub use print::*;
pub use system::*;

#[cfg(not(feature = "emulate"))]
extern "Rust" {
    fn __black_box(i: i64) -> i64;
    /// This is a helper doing `startopen` and `stopopen` at the same time for a single register.
    /// We don't have a setup for passing arrays to assembly yet, so we do this for now.
    pub fn reveal(s: SecretModp) -> ClearModp;
    /// A helper for multi-return-value instructions to extract the next instruction
    fn pop_secret_modp() -> SecretModp;
    /// A helper for multi-return-value instructions to extract the next instruction
    fn pop_secret_bit() -> RawSecretBit;
    /// A helper for multi-return-value instructions to extract the next instruction
    fn pop_secret_i64() -> SecretI64;
    // A helper for bit operations [again here only do one at a time for now]
    //   - Let the assembler to the merging
    fn __bit() -> SecretModp;
}

#[inline(always)]
#[cfg(not(feature = "emulate"))]
pub fn __triple() -> (SecretModp, SecretModp, SecretModp) {
    extern "C" {
        fn __triple();
    }
    unsafe {
        __triple();
        (pop_secret_modp(), pop_secret_modp(), pop_secret_modp())
    }
}

#[inline(always)]
#[cfg(not(feature = "emulate"))]
pub fn __square() -> (SecretModp, SecretModp) {
    extern "C" {
        fn __square();
    }
    unsafe {
        __square();
        (pop_secret_modp(), pop_secret_modp())
    }
}

/// We reserve 1000 memory entries for the testing data
/// This is done in the first instructions, so we know
/// testing data is allocated from position 0 to 999
const TEST_MEMORY_OFFSET: i64 = 0;

#[cfg(feature = "emulate")]
#[inline(never)]
pub fn black_box(i: i64) -> i64 {
    i
}

#[cfg(not(feature = "emulate"))]
#[inline(always)]
/// This function prevents wasm-opt from optimizing out operations on the value
/// if said value is constant or dead code.
pub fn black_box(i: i64) -> i64 {
    unsafe { __black_box(i) }
}

#[cfg(feature = "emulate")]
#[inline(never)]
pub unsafe fn reveal(s: SecretModp) -> ClearModp {
    s.0
}

#[panic_handler]
#[cfg(not(feature = "emulate"))]
fn panic_handler(_: &core::panic::PanicInfo) -> ! {
    /*
    // FIXME: this requires some fancy memory operations to work
    if let Some(loc) = info.location() {
        print!("panic in line ", i64::from(loc.line()));
    }*/
    unsafe { __crash() }
}

#[cfg(feature = "emulate")]
mod emulated_impls;

#[cfg(feature = "emulate")]
pub use emulated_impls::__mul2sint;

#[cfg(feature = "emulate")]
use num_bigint::BigInt;

#[cfg(feature = "emulate")]
// __triple and __square are here, because they have multiple return values and this isn't supported properly
// in our wasm transpiler. Look at the code generator for these to see how wasm handles it.
pub fn __triple() -> (SecretModp, SecretModp, SecretModp) {
    let value: BigInt = From::from(1);
    let s = SecretModp(value.into());
    (s, s, s)
}

#[cfg(feature = "emulate")]
pub fn __square() -> (SecretModp, SecretModp) {
    let value: BigInt = From::from(1);
    let s = SecretModp(value.into());
    (s, s)
}

#[cfg(feature = "emulate")]
pub unsafe fn __bit() -> SecretModp {
    let s = SecretModp::from(0);
    s
}

pub trait Test {
    #[track_caller]
    fn test(self);
}

pub trait TestValue {
    #[track_caller]
    fn test_value(self, val: Self);
}

// Note test_mem is never implemented for secret types
//   - This makes things a bit simpler
pub trait TestMem {
    #[track_caller]
    fn test_mem<const I: u32>(self, t_location: ConstU32<I>);
}

pub trait Output {
    fn output<const C: u32>(self, ch: Channel<C>);
}

pub trait Input {
    fn input<const C: u32>(ch: Channel<C>) -> Self;
}

#[cfg(not(feature = "emulate"))]
mod testing;

#[cfg(feature = "emulate")]
mod testing_emulated;

pub mod alloc;

pub use scale_impl_generator::main;

#[doc(hidden)]
#[macro_export]
macro_rules! __main {
    (KAPPA = $kappa:expr;) => {
        use $crate::print;
        use $crate::*;
        type SecretInteger<const K: u64> = scale_std::integer::SecretInteger<K, $kappa>;
        type SecretFixed<const K: u64, const F: u64> =
            scale_std::fixed_point::SecretFixed<K, F, $kappa>;
        type SecretFloat<const V: u64, const P: u64> =
            scale_std::floating_point::SecretFloat<V, P, $kappa, true>;
        type ClearFloat<const V: u64, const P: u64> =
            scale_std::floating_point::ClearFloat<V,P,true>;
        #[cfg(not(test))]
        mod helper {
            #[no_mangle]
            fn main() {
                extern "Rust" {
                    fn init_wasm_heap_memory();
                }
                unsafe {
                    init_wasm_heap_memory();
                }
                super::main();
                #[cfg(feature = "emulate")]
                $crate::exit(0);
            }
        }
    };
    (KAPPA = $kappa:expr; DETECT_OVERFLOW = $detect_overflow:expr) => {
        use $crate::print;
        use $crate::*;
        type SecretInteger<const K: u64> = scale_std::integer::SecretInteger<K, $kappa>;
        type SecretFixed<const K: u64, const F: u64> =
            scale_std::fixed_point::SecretFixed<K, F, $kappa>;
        type SecretFloat<const V: u64, const P: u64> =
            scale_std::floating_point::SecretFloat<V, P, $kappa, $detect_overflow>;
        type ClearFloat<const V: u64, const P: u64> =
            scale_std::floating_point::ClearFloat<V,P,$detect_overflow>
        #[cfg(not(test))]
        mod helper {
            #[no_mangle]
            fn main() {
                extern "Rust" {
                    fn init_wasm_heap_memory();
                }
                unsafe {
                    init_wasm_heap_memory();
                }
                super::main();
                #[cfg(feature = "emulate")]
                $crate::exit(0);
            }
        }
    };
}

#[macro_export]
macro_rules! panic {
    ($($tt:tt)*) => {{
        $crate::print!($($tt)*);
        unsafe { $crate::__crash() }
    }};
}

#[macro_export]
macro_rules! assert {
    ($e:expr) => {
        if !$e {
            $crate::panic!("assertion failed: ", stringify!($e));
        }
    };
}

/* Comparison outputting a A */
pub trait ScaleCmp<Other, A> {
    fn lt(self, other: Other) -> A;
    fn le(self, other: Other) -> A;
    fn gt(self, other: Other) -> A;
    fn ge(self, other: Other) -> A;
    fn eq(self, other: Other) -> A;
    fn ne(self, other: Other) -> A;
}

pub trait ScaleCmpZ<A> {
    fn ltz(self) -> A;
    fn lez(self) -> A;
    fn gtz(self) -> A;
    fn gez(self) -> A;
    fn eqz(self) -> A;
    fn nez(self) -> A;
}

pub trait Rand {
    fn rand(self) -> i64;
}

pub trait Randomize {
    fn randomize() -> Self;
}

#[macro_export]
macro_rules! execute_garbled_circuit {
    ($id:ident($($arg:expr),*) -> $($ret:ty),*) => {{
        $(Stack::push(&$arg);)*
        execute_garbled_circuit(ConstU32::<$id>);
        ($(<$ret>::pop()),*)
    }};
}

#[macro_export]
macro_rules! execute_local_function {
    ($id:ident($($arg:expr),*) -> $($ret:ty),*) => {{
        $(Stack::push(&$arg);)*
        execute_local_function(ConstU32::<$id>);
        ($(<$ret>::pop()),*)
    }};
}

#[derive(Copy, Clone)]
pub struct Player<const ID: u32>;

#[derive(Copy, Clone)]
pub struct ConstU32<const U: u32>;

#[derive(Copy, Clone)]
pub struct ConstU64<const U: u64>;

#[derive(Copy, Clone)]
pub struct ConstBool<const U: bool>;

#[derive(Copy, Clone)]
pub struct ConstI32<const I: i32>;

#[derive(Copy, Clone)]
pub struct Channel<const ID: u32>;

/// Internal helper to map user-visible types
/// to internal types.
trait AssemblyType {
    type Type;
    fn to_asm(self) -> Self::Type;
}

impl AssemblyType for i64 {
    type Type = i64;

    #[inline(always)]
    fn to_asm(self) -> Self::Type {
        self
    }
}

impl AssemblyType for ClearModp {
    type Type = ClearModp;

    #[inline(always)]
    fn to_asm(self) -> Self::Type {
        self
    }
}

impl AssemblyType for SecretModp {
    type Type = SecretModp;

    #[inline(always)]
    fn to_asm(self) -> Self::Type {
        self
    }
}

impl AssemblyType for SecretBit {
    type Type = SecretBit;

    #[inline(always)]
    fn to_asm(self) -> Self::Type {
        self
    }
}

impl AssemblyType for SecretI64 {
    type Type = SecretI64;

    #[inline(always)]
    fn to_asm(self) -> Self::Type {
        self
    }
}

impl<const I: u32> AssemblyType for Channel<I> {
    type Type = u32;

    #[inline(always)]
    fn to_asm(self) -> Self::Type {
        I
    }
}

impl<const I: i32> AssemblyType for ConstI32<I> {
    type Type = i32;

    #[inline(always)]
    fn to_asm(self) -> Self::Type {
        I
    }
}

impl<const I: u32> AssemblyType for ConstU32<I> {
    type Type = u32;

    #[inline(always)]
    fn to_asm(self) -> Self::Type {
        I
    }
}

impl<const I: u64> AssemblyType for ConstU64<I> {
    type Type = u64;

    #[inline(always)]
    fn to_asm(self) -> Self::Type {
        I
    }
}

impl<const I: bool> AssemblyType for ConstBool<I> {
    type Type = bool;

    #[inline(always)]
    fn to_asm(self) -> Self::Type {
        I
    }
}

impl<const I: u32> AssemblyType for Player<I> {
    type Type = u32;

    #[inline(always)]
    fn to_asm(self) -> Self::Type {
        I
    }
}

impl AssemblyType for Never {
    type Type = Never;
    #[inline(always)]
    fn to_asm(self) -> Self::Type {
        self
    }
}

type Never = <F as HasOutput>::Output;
/// Helper type giving us access to the `!` type on the stable compiler
pub trait HasOutput {
    type Output;
}

impl<O> HasOutput for fn() -> O {
    type Output = O;
}

type F = fn() -> !;