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
// SPDX-License-Identifier: CC0-1.0

//! FFI Bindings
//!
//! This module contains all bindings to the C library types and functions.
//! It is split into several modules, each one corresponding to a `.h` file
//! in the C library.
//!
//! All types are converted to CamelCase and prefixed with the letter C;
//! function names are unchanged.

use libc::size_t;
use std::fmt;

/// Used with `evalTCOProgram` to enforce consensus limits.
pub const BUDGET_MAX: ubounded = 4000050;
/// The max value of UBOUNDED_MAX
pub const UBOUNDED_MAX: ubounded = u32::MAX;

/// Used in the C code for various purposes; actually defined as `uint_least32_t`
/// which seems not to have an equivalent in Rust libc.
// There are sanity checks for both these types in c_jets/c_env.rs
#[allow(non_camel_case_types)]
pub type ubounded = u32;

extern "C" {
    pub static c_sizeof_ubounded: size_t;
    pub static c_alignof_ubounded: size_t;
}

pub mod bounded {
    use super::ubounded;
    extern "C" {
        pub static c_overhead: ubounded;
    }

    /// constant Overhead of each jet
    pub fn cost_overhead() -> ubounded {
        unsafe { c_overhead }
    }
}

/// Used in C code to give the project a Win32 vibe; actually defined as
/// `uint_least16_t`.
// There are sanity checks for both these types in c_jets/c_env.rs
#[allow(non_camel_case_types)]
pub type UWORD = usize;

extern "C" {
    pub static c_sizeof_UWORD: size_t;
    pub static c_alignof_UWORD: size_t;
}

/// Simplicity error codes
///
/// If you update this list, please also update [`SimplicityErr::from_i32`].
#[repr(C)]
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum SimplicityErr {
    NoError = 0,
    Malloc = -1,
    BitstreamEof = -2,
    NotYetImplemented = -3,
    DataOutOfRange = -4,
    DataOutOfOrder = -6,
    FailCode = -8,
    StopCode = -10,
    Hidden = -12,
    BitstreamUnusedBytes = -14,
    BitstreamUnusedBits = -16,
    TypeInferenceUnification = -18,
    TypeInferenceOccursCheck = -20,
    TypeInferenceNotProgram = -22,
    WitnessEof = -24,
    WitnessUnusedBits = -26,
    UnsharedSubexpression = -28,
    Cmr = -30,
    Amr = -32,
    ExecBudget = -34,
    ExecMemory = -36,
    ExecJet = -38,
    ExecAssert = -40,
    AntiDoS = -42,
    HiddenRoot = -44,
}

extern "C" {
    pub static c_sizeof_simplicity_err: size_t;
    pub static c_alignof_simplicity_err: size_t;
}

impl fmt::Display for SimplicityErr {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(self, f)
    }
}

impl SimplicityErr {
    /// Converts the error code into a `Result` by splitting off the `NoError` case.
    pub fn into_result(self) -> Result<(), Self> {
        if self == SimplicityErr::NoError {
            Ok(())
        } else {
            Err(self)
        }
    }

    /// Converts an `i32` result to either a positive value or an error code
    ///
    /// # Panics
    /// Panics if the i32 result is not one of the error values returned from Simplicity.
    pub fn from_i32(n: i32) -> Result<u32, Self> {
        match n {
            n if n >= 0 => Ok(n as u32),
            -1 => Err(SimplicityErr::Malloc),
            -2 => Err(SimplicityErr::BitstreamEof),
            -3 => Err(SimplicityErr::NotYetImplemented),
            -4 => Err(SimplicityErr::DataOutOfRange),
            -6 => Err(SimplicityErr::DataOutOfOrder),
            -8 => Err(SimplicityErr::FailCode),
            -10 => Err(SimplicityErr::StopCode),
            -12 => Err(SimplicityErr::Hidden),
            -14 => Err(SimplicityErr::BitstreamUnusedBytes),
            -16 => Err(SimplicityErr::BitstreamUnusedBits),
            -18 => Err(SimplicityErr::TypeInferenceUnification),
            -20 => Err(SimplicityErr::TypeInferenceOccursCheck),
            -22 => Err(SimplicityErr::TypeInferenceNotProgram),
            -24 => Err(SimplicityErr::WitnessEof),
            -26 => Err(SimplicityErr::WitnessUnusedBits),
            -28 => Err(SimplicityErr::UnsharedSubexpression),
            -30 => Err(SimplicityErr::Cmr),
            -32 => Err(SimplicityErr::Amr),
            -34 => Err(SimplicityErr::ExecBudget),
            -36 => Err(SimplicityErr::ExecMemory),
            -38 => Err(SimplicityErr::ExecJet),
            -40 => Err(SimplicityErr::ExecAssert),
            -42 => Err(SimplicityErr::AntiDoS),
            -44 => Err(SimplicityErr::HiddenRoot),
            x => panic!("unexpected error code {}", x),
        }
    }
}

pub mod bitstream {
    use super::bitstring::CBitstring;
    use libc::{c_int, c_uchar, size_t};

    /// Stream of bits.
    #[repr(C)]
    #[derive(Copy, Clone)]
    pub struct CBitstream {
        pub arr: *const c_uchar,
        pub len: size_t,
        pub offset: c_uchar,
    }

    impl From<&[u8]> for CBitstream {
        fn from(sl: &[u8]) -> CBitstream {
            CBitstream {
                arr: sl.as_ptr(),
                len: sl.len(),
                offset: 0,
            }
        }
    }

    extern "C" {
        pub static c_sizeof_bitstream: size_t;
        pub static c_alignof_bitstream: size_t;

        pub fn closeBitstream(stream: *mut CBitstream) -> bool;
        pub fn readNBits(n: c_int, stream: *mut CBitstream) -> i32;
        pub fn decodeUptoMaxInt(stream: *mut CBitstream) -> i32;
        pub fn readBitstring(result: *mut CBitstring, n: size_t, stream: *mut CBitstream) -> i32;
    }
}

pub mod bitstring {
    use libc::{c_uchar, size_t};

    /// String of bits.
    #[repr(C)]
    #[derive(Copy, Clone)]
    pub struct CBitstring {
        arr: *const c_uchar,
        len: size_t,
        offset: size_t,
    }

    impl Default for CBitstring {
        fn default() -> Self {
            CBitstring {
                arr: std::ptr::null(),
                len: 0,
                offset: 0,
            }
        }
    }

    extern "C" {
        pub static c_sizeof_bitstring: size_t;
        pub static c_alignof_bitstring: size_t;
    }
}

pub mod dag {
    use super::bitstring::CBitstring;
    use super::sha256::CSha256Midstate;
    use super::ty::CType;
    use super::SimplicityErr;
    use libc::{c_void, size_t};

    /// Kind of Simplicity node.
    #[repr(C)]
    #[derive(Copy, Clone, Eq, PartialEq, Debug)]
    pub enum CTag {
        COMP,
        CASE,
        ASSERTL,
        ASSERTR,
        PAIR,
        DISCONNECT,
        INJL,
        INJR,
        TAKE,
        DROP,
        IDEN,
        UNIT,
        HIDDEN,
        WITNESS,
        JET,
        WORD,
    }

    /// Used to count the different kinds of combinators in a Simplicity DAG.
    #[repr(C)]
    #[derive(Copy, Clone, Eq, PartialEq, Debug, Default)]
    pub struct CCombinatorCounters {
        pub comp_cnt: size_t,
        pub case_cnt: size_t,
        pub pair_cnt: size_t,
        pub disconnect_cnt: size_t,
        pub injl_cnt: size_t,
        pub injr_cnt: size_t,
        pub take_cnt: size_t,
        pub drop_cnt: size_t,
    }

    #[repr(C)]
    #[derive(Copy, Clone)]
    /// Anonymous
    pub union CAuxTypes {
        /// scratch space for verifyCanonicalOrder
        pub aux: size_t,
        /// source type, target type
        pub types: [size_t; 2],
    }

    #[repr(C)]
    #[derive(Copy, Clone, Eq, PartialEq, Debug)]
    /// Anonymous
    pub struct CSourceIx {
        source_ix: size_t,
    }

    #[repr(C)]
    #[derive(Copy, Clone, Eq, PartialEq, Debug)]
    /// Anonymous
    pub struct CChild2 {
        child: [size_t; 2],
    }

    #[repr(C)]
    #[derive(Copy, Clone)]
    /// Anonymous
    pub union CSourceChildValue {
        source_ix: CSourceIx,
        child: CChild2,
        compact_value: CBitstring,
    }

    #[repr(C)]
    #[derive(Copy, Clone)]
    pub struct CDagNode {
        pub jet: *const c_void,
        pub cmr: CSha256Midstate,
        pub aux_types: CAuxTypes,
        pub source_ix_or_child_or_compact_value: CSourceChildValue,
        pub target_ix: size_t,
        pub cost: super::ubounded,
        pub tag: CTag,
    }

    #[repr(C)]
    #[derive(Copy, Clone, Eq, PartialEq, Debug, Default)]
    /// Static analyses for a particular node of a Simplicity DAG
    pub struct CAnalyses {
        pub annotated_merkle_root: CSha256Midstate,
    }

    extern "C" {
        pub static c_sizeof_tag: size_t;
        pub static c_alignof_tag: size_t;
        pub static c_sizeof_combinator_counters: size_t;
        pub static c_alignof_combinator_counters: size_t;
        pub static c_sizeof_dag_node: size_t;
        pub static c_alignof_dag_node: size_t;
        pub static c_sizeof_analyses: size_t;
        pub static c_alignof_analyses: size_t;

        /// Given the IMR of a jet specification, return the CMR of a jet that implements
        /// that specification
        pub fn mkJetCMR(imr: *const u32, weight: u64) -> CSha256Midstate;

        /// Compute the CMR of a jet of scribe(v) : ONE |- TWO^(2^n) that outputs a given
        /// bitstring
        pub fn computeWordCMR(value: *const CBitstring, n: size_t) -> CSha256Midstate;

        /// Given a well-formed dag[i + 1], set the `cmr` field of every node in `dag`
        pub fn computeCommitmentMerkleRoot(dag: *mut CDagNode, i: size_t);

        /// Given a well-typed dag representing a Simplicity expression, compute
        /// the annotated Merkle roots of all subexpressions.
        pub fn computeAnnotatedMerkleRoot(
            analyses: *mut CAnalyses,
            dag: *const CDagNode,
            ty: *const CType,
            len: size_t,
        );

        /// Verifies that the 'dag' is in canonical order, meaning that nodes
        /// under the left branches have lower indices than nodes under
        pub fn verifyCanonicalOrder(dag: *mut CDagNode, len: size_t) -> SimplicityErr;

        /// Fills in the 'WITNESS' nodes of a 'dag' with the data from 'witness'
        pub fn fillWitnessData(
            dag: *mut CDagNode,
            type_dag: *mut CType,
            len: size_t,
            witness: CBitstring,
        ) -> SimplicityErr;

        /// Computes the identity Merkle roots of every subexpression in a well-typed 'dag' with witnesses    .
        pub fn verifyNoDuplicateIdentityRoots(
            imr: *mut CSha256Midstate,
            dag: *const CDagNode,
            type_dag: *const CType,
            len: size_t,
        ) -> SimplicityErr;
    }

    /// Convenience wrapper around mkJetCMR that operates on u8 bytes instead of u32
    #[allow(non_snake_case)]
    pub fn c_mkJetCMR(midstate: hashes::sha256::Midstate, weight: u64) -> hashes::sha256::Midstate {
        let mut imr = [0; 32];
        for (idx, chunk) in midstate.0.chunks(4).enumerate() {
            imr[idx] = u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
        }
        unsafe { mkJetCMR(imr.as_ptr(), weight) }.into()
    }
}

pub mod deserialize {
    use super::bitstream::CBitstream;
    use super::bitstring::CBitstring;
    use super::dag::{CCombinatorCounters, CDagNode};
    use super::SimplicityErr;

    extern "C" {
        pub fn decodeMallocDag(
            dag: *mut *mut CDagNode,
            combinator_counters: *mut CCombinatorCounters,
            stream: *mut CBitstream,
        ) -> i32;

        pub fn decodeWitnessData(
            witness: *mut CBitstring,
            stream: *mut CBitstream,
        ) -> SimplicityErr;
    }
}

pub mod eval {
    use super::dag::CDagNode;
    use super::ty::CType;
    use super::SimplicityErr;
    use super::{ubounded, UWORD};
    use crate::c_jets::c_env::CElementsTxEnv;
    use libc::{c_uchar, size_t};
    use std::ptr;

    pub const CHECK_NONE: c_uchar = 0;
    pub const CHECK_EXEC: c_uchar = 0x10;
    pub const CHECK_CASE: c_uchar = 0x60;
    pub const CHECK_ALL: c_uchar = 0xFF;

    extern "C" {
        /// Run the Bit Machine on the well-typed Simplicity expression 'dag[len]'.
        pub fn evalTCOExpression(
            anti_dos_checks: c_uchar,
            output: *mut UWORD,
            input: *const UWORD,
            dag: *const CDagNode,
            type_dag: *mut CType,
            len: size_t,
            budget: *const ubounded,
            env: *const CElementsTxEnv,
        ) -> SimplicityErr;

        /// Given a well-typed dag representing a Simplicity expression,
        /// compute the memory and CPU requirements for evaluation.
        ///
        /// Refer to C documentation for preconditions.
        pub fn analyseBounds(
            cell_bound: *mut ubounded,
            UWORD_bound: *mut ubounded,
            frame_bound: *mut ubounded,
            cost_bound: *mut ubounded,
            max_cells: ubounded,
            max_cost: ubounded,
            dag: *const CDagNode,
            type_dag: *const CType,
            len: size_t,
        ) -> SimplicityErr;
    }

    /// Run the Bit Machine on the well-typed Simplicity program 'dag[len]'.
    ///
    /// Defined insine in eval.h; since it is a 1-liner we just copy it into Rust.
    ///
    /// # Safety
    ///
    /// This function directly wraps `evalTCOExpression`; see the documentation for
    /// that function in the C source code for preconditions.
    #[allow(non_snake_case)]
    pub unsafe fn evalTCOProgram(
        dag: *const CDagNode,
        type_dag: *mut CType,
        len: size_t,
        budget: *const ubounded,
        env: *const CElementsTxEnv,
    ) -> SimplicityErr {
        evalTCOExpression(
            CHECK_ALL,
            ptr::null_mut(),
            ptr::null(),
            dag,
            type_dag,
            len,
            budget,
            env,
        )
    }
}

pub mod sha256 {
    use hashes::sha256::Midstate;
    use libc::size_t;

    /// The 256-bit array of a SHA-256 hash or midstate.
    #[repr(C)]
    #[derive(Copy, Clone, Eq, PartialEq, Debug, Default)]
    pub struct CSha256Midstate {
        pub s: [u32; 8],
    }

    impl From<CSha256Midstate> for Midstate {
        fn from(c_midstate: CSha256Midstate) -> Midstate {
            let mut inner = [0; 32];
            for (idx, chunk) in c_midstate.s.iter().enumerate() {
                inner[idx * 4..(idx + 1) * 4].copy_from_slice(&chunk.to_be_bytes());
            }
            Midstate(inner)
        }
    }

    impl From<Midstate> for CSha256Midstate {
        fn from(midstate: Midstate) -> CSha256Midstate {
            let mut s = [0; 8];
            for (idx, chunk) in midstate.0.chunks(4).enumerate() {
                s[idx] = u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
            }
            CSha256Midstate { s }
        }
    }

    extern "C" {
        pub static c_sizeof_sha256_midstate: size_t;
        pub static c_alignof_sha256_midstate: size_t;
    }
}

/// Renamed from `type` in the C code
pub mod ty {
    use super::sha256::CSha256Midstate;
    use libc::size_t;

    /// Name of a Simplicity type
    #[repr(C)]
    #[derive(Copy, Clone, Eq, PartialEq, Debug)]
    pub enum CTypeName {
        ONE,
        SUM,
        PRODUCT,
    }

    #[repr(C)]
    #[derive(Copy, Clone)]
    /// Anonymous
    pub union CSkipBack {
        /// Used by `typeSkip`
        pub skip: size_t,
        /// Sometimes used as scratch space when traversing types
        pub back: size_t,
    }

    /// Simplicity type DAG
    #[repr(C)]
    #[derive(Copy, Clone)]
    pub struct CType {
        pub type_arg: [size_t; 2],
        pub skip_back: CSkipBack,
        pub type_merkle_root: CSha256Midstate,
        pub bit_size: super::ubounded,
        pub kind: CTypeName,
    }

    extern "C" {
        pub static c_sizeof_typename: size_t;
        pub static c_alignof_typename: size_t;
        pub static c_sizeof_type: size_t;
        pub static c_alignof_type: size_t;

        /// Given a well-formed 'type_dag', compute the bitSizes, skips, and type Merkle roots of all subexpressions.
        pub fn computeTypeAnalyses(type_dag: *mut CType, len: size_t);
    }
}

pub mod type_inference {
    use super::dag::{CCombinatorCounters, CDagNode};
    use super::ty::CType;
    use super::SimplicityErr;
    use libc::size_t;

    extern "C" {
        /// If the Simplicity DAG, 'dag', has a principal type (including constraints
        /// due to sharing of subexpressions), then allocate a well-formed type DAG
        /// containing all the types needed for all the subexpressions of 'dag'.
        pub fn mallocTypeInference(
            type_dag: *mut *mut CType,
            dag: *mut CDagNode,
            len: size_t,
            census: *const CCombinatorCounters,
        ) -> SimplicityErr;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::mem::{align_of, size_of};

    #[test]
    #[rustfmt::skip]
    fn test_sizes() {
        unsafe {
            assert_eq!(size_of::<ubounded>(), c_sizeof_ubounded);
            assert_eq!(size_of::<UWORD>(), c_sizeof_UWORD);
            assert_eq!(size_of::<SimplicityErr>(), c_sizeof_simplicity_err);

            assert_eq!(size_of::<bitstream::CBitstream>(), bitstream::c_sizeof_bitstream);
            assert_eq!(size_of::<bitstring::CBitstring>(), bitstring::c_sizeof_bitstring);
            assert_eq!(size_of::<dag::CTag>(), dag::c_sizeof_tag);
            assert_eq!(size_of::<dag::CCombinatorCounters>(), dag::c_sizeof_combinator_counters);
            assert_eq!(size_of::<dag::CDagNode>(), dag::c_sizeof_dag_node);
            assert_eq!(size_of::<dag::CAnalyses>(), dag::c_sizeof_analyses);
            assert_eq!(size_of::<sha256::CSha256Midstate>(), sha256::c_sizeof_sha256_midstate);
            assert_eq!(size_of::<ty::CType>(), ty::c_sizeof_type);
            assert_eq!(size_of::<ty::CTypeName>(), ty::c_sizeof_typename);
        }
    }

    #[test]
    #[rustfmt::skip]
    fn test_aligns() {
        unsafe {
            assert_eq!(align_of::<ubounded>(), c_alignof_ubounded);
            assert_eq!(align_of::<UWORD>(), c_alignof_UWORD);

            assert_eq!(align_of::<bitstream::CBitstream>(), bitstream::c_alignof_bitstream);
            assert_eq!(align_of::<bitstring::CBitstring>(), bitstring::c_alignof_bitstring);
            assert_eq!(align_of::<dag::CTag>(), dag::c_alignof_tag);
            assert_eq!(align_of::<dag::CCombinatorCounters>(), dag::c_alignof_combinator_counters);
            assert_eq!(align_of::<dag::CDagNode>(), dag::c_alignof_dag_node);
            assert_eq!(align_of::<dag::CAnalyses>(), dag::c_alignof_analyses);
            assert_eq!(align_of::<sha256::CSha256Midstate>(), sha256::c_alignof_sha256_midstate);
            assert_eq!(align_of::<ty::CType>(), ty::c_alignof_type);
        }
    }
}