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
// Copyright (c) 2022-2023 The MobileCoin Foundation

use core::mem::MaybeUninit;

use mc_core::{
    account::PublicSubaddress,
    keys::{RootViewPrivate, SubaddressSpendPrivate},
};
use mc_transaction_types::BlockVersion;

use ledger_mob_apdu::tx::TxOnetimeKey;

use super::Error;

#[cfg(feature = "mlsag")]
use super::ring::RingSigner;

#[cfg(feature = "summary")]
use super::{summary::Summarizer, MAX_RECORDS};

#[cfg(feature = "ident")]
use super::ident::Ident;

pub struct Function {
    inner: FunctionType,
}

impl Default for Function {
    fn default() -> Self {
        Self {
            inner: FunctionType::None,
        }
    }
}

/// Enum for internal state machines to allow stack to be shared between functions
/// and encapsulate [out-pointer](https://doc.rust-lang.org/core/mem/union.MaybeUninit.html#out-pointers) usage to mitigate stack issues
#[allow(clippy::large_enum_variant)]
enum FunctionType {
    None,

    #[cfg(feature = "summary")]
    Summarize(MaybeUninit<Summarizer<MAX_RECORDS>>),

    #[cfg(feature = "mlsag")]
    RingSign(MaybeUninit<RingSigner>),

    #[cfg(feature = "ident")]
    Ident(Ident),
}

impl Default for FunctionType {
    fn default() -> Self {
        Self::None
    }
}

impl Function {
    /// Create a new / empty function context
    pub const fn new() -> Self {
        Self {
            inner: FunctionType::None,
        }
    }

    /// Setup ring-signer context
    ///
    /// this uses out-pointer based init to avoid stack allocation
    /// see: <https://doc.rust-lang.org/core/mem/union.MaybeUninit.html#out-pointers>
    #[cfg(feature = "mlsag")]
    #[allow(clippy::too_many_arguments)]
    #[cfg_attr(feature = "noinline", inline(never))]
    pub fn ring_signer_init(
        &mut self,
        ring_size: usize,
        real_index: usize,
        root_view_private: &RootViewPrivate,
        subaddress_spend_private: &SubaddressSpendPrivate,
        value: u64,
        message: &[u8],
        token_id: u64,
        onetime_private_key: Option<TxOnetimeKey>,
    ) -> Result<&mut RingSigner, Error> {
        // Clear function prior to init (executes drop)
        self.clear();

        // Setup uninitialised context
        self.inner = FunctionType::RingSign(MaybeUninit::uninit());

        // Return uninitialised context pointer
        let p = match &mut self.inner {
            FunctionType::RingSign(s) => s.as_mut_ptr(),
            _ => unreachable!(),
        };

        // Initialise ring signer
        if let Err(e) = unsafe {
            RingSigner::init(
                p,
                ring_size,
                real_index,
                root_view_private,
                subaddress_spend_private,
                value,
                message,
                token_id,
                onetime_private_key,
            )
        } {
            // Clear context and return error
            self.clear();

            return Err(e);
        }

        // Return initialised ring signer
        Ok(unsafe { &mut *p })
    }

    /// Fetch ring signer context
    #[cfg(feature = "mlsag")]
    pub fn ring_signer(&mut self) -> Option<&mut RingSigner> {
        match &mut self.inner {
            FunctionType::RingSign(s) => Some(unsafe { &mut *s.as_mut_ptr() }),
            _ => None,
        }
    }

    /// Fetch ring signer context
    #[cfg(feature = "mlsag")]
    pub fn ring_signer_ref(&self) -> Option<&RingSigner> {
        match &self.inner {
            FunctionType::RingSign(s) => Some(unsafe { &*s.as_ptr() }),
            _ => None,
        }
    }

    /// Setup summarizer context
    ///
    /// this uses out-pointer based init to avoid stack allocation
    /// see: <https://doc.rust-lang.org/core/mem/union.MaybeUninit.html#out-pointers>
    #[cfg(feature = "summary")]
    #[cfg_attr(feature = "noinline", inline(never))]
    pub fn summarizer_init(
        &mut self,
        message: &[u8; 32],
        block_version: BlockVersion,
        num_outputs: usize,
        num_inputs: usize,
        view_private_key: &RootViewPrivate,
        change_subaddress: &PublicSubaddress,
    ) -> Result<&mut Summarizer<MAX_RECORDS>, Error> {
        // Clear function prior to init (executes drop)

        self.clear();

        // Setup uninitialised context
        self.inner = FunctionType::Summarize(MaybeUninit::uninit());

        // Return uninitialised context pointer
        let p = match &mut self.inner {
            FunctionType::Summarize(s) => s.as_mut_ptr(),
            _ => unreachable!(),
        };

        // Initialise summarizer memory
        if let Err(e) = unsafe {
            Summarizer::init(
                p,
                message,
                block_version,
                num_outputs,
                num_inputs,
                view_private_key,
                change_subaddress,
            )
        } {
            // Clear context and return error
            self.clear();

            return Err(e);
        }

        // Return summarizer context
        Ok(unsafe { &mut *p })
    }

    /// Fetch summarizer context
    #[cfg(feature = "summary")]
    pub fn summarizer(&mut self) -> Option<&mut Summarizer<MAX_RECORDS>> {
        match &mut self.inner {
            FunctionType::Summarize(s) => Some(unsafe { &mut *s.as_mut_ptr() }),
            _ => None,
        }
    }

    /// Fetch summarizer context
    #[cfg(feature = "summary")]
    pub fn summarizer_ref(&self) -> Option<&Summarizer<MAX_RECORDS>> {
        match &self.inner {
            FunctionType::Summarize(s) => Some(unsafe { &*s.as_ptr() }),
            _ => None,
        }
    }

    /// Initialise identity function
    #[cfg(feature = "ident")]
    #[cfg_attr(feature = "noinline", inline(never))]
    pub fn ident_init(
        &mut self,
        identity_index: u32,
        uri: &str,
        challenge: &[u8],
    ) -> Result<&mut Ident, Error> {
        // Clear function prior to init (executes drop)
        self.clear();

        // Setup ident context
        self.inner = FunctionType::Ident(Ident::new(identity_index, uri, challenge)?);

        // Return ident context
        match &mut self.inner {
            FunctionType::Ident(s) => Ok(s),
            _ => unreachable!(),
        }
    }

    /// Fetch ident context
    #[cfg(feature = "ident")]
    pub fn ident_ref(&self) -> Option<&Ident> {
        match &self.inner {
            FunctionType::Ident(s) => Some(s),
            _ => None,
        }
    }

    /// Clear context, executing drop if required
    #[cfg_attr(feature = "noinline", inline(never))]
    pub fn clear(&mut self) {
        match &mut self.inner {
            #[cfg(feature = "mlsag")]
            FunctionType::RingSign(s) => unsafe {
                s.assume_init_drop();
            },
            #[cfg(feature = "summary")]
            FunctionType::Summarize(s) => unsafe { s.assume_init_drop() },
            _ => (),
        }

        self.inner = FunctionType::None;
    }
}

#[cfg(test)]
mod test {
    use mc_core::account::{Account, PublicSubaddress};
    use mc_crypto_keys::{RistrettoPrivate, RistrettoPublic};
    use mc_transaction_types::BlockVersion;
    use mc_util_from_random::FromRandom;
    use rand::random;
    use rand_core::OsRng;

    use super::Function;

    // Set function container to ident mode
    fn ident_init(f: &mut Function) {
        f.ident_init(0, "test.lol", &random::<[u8; 32]>()).unwrap();
    }

    // Set function container to summary generator mode
    fn summary_init(f: &mut Function) {
        let account = Account::new(
            RistrettoPrivate::from_random(&mut OsRng {}).into(),
            RistrettoPrivate::from_random(&mut OsRng {}).into(),
        );

        let change_view_private = RistrettoPrivate::from_random(&mut OsRng {});
        let change_spend_private = RistrettoPrivate::from_random(&mut OsRng {});
        let change = PublicSubaddress {
            view_public: RistrettoPublic::from(&change_view_private).into(),
            spend_public: RistrettoPublic::from(&change_spend_private).into(),
        };

        f.summarizer_init(
            &[0u8; 32],
            BlockVersion::THREE,
            3,
            2,
            account.view_private_key(),
            &change,
        )
        .unwrap();
    }

    // Set function container to ring signing mode
    fn ring_init(f: &mut Function) {
        let account = Account::new(
            RistrettoPrivate::from_random(&mut OsRng {}).into(),
            RistrettoPrivate::from_random(&mut OsRng {}).into(),
        );

        let change_spend_private = RistrettoPrivate::from_random(&mut OsRng {});

        let onetime_private_key = RistrettoPrivate::from_random(&mut OsRng {});

        f.ring_signer_init(
            11,
            3,
            account.view_private_key(),
            &change_spend_private.into(),
            random(),
            &random::<[u8; 32]>(),
            2,
            Some(onetime_private_key.into()),
        )
        .unwrap();
    }

    fn clear(f: &mut Function) {
        f.clear();
    }

    /// Miri test for function init / state changes
    #[test]
    fn miri_function_states() {
        let mut f = Function::new();

        // Collect state transition functions
        let states = &[ident_init, summary_init, ring_init, clear];

        // Iterate through possible state transitions
        for i in 0..states.len() {
            for j in 0..states.len() {
                // Call first state
                states[i](&mut f);
                // Call next state
                states[j](&mut f);
            }
        }
    }
}