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
// Rust Monero Library
// Written in 2019 by
//   h4sh3d <h4sh3d@protonmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//

//! RingCT primitive types
//!
//! Support for parsing RingCT signature in Monero transactions.
//!

use std::fmt;

use crate::consensus::encode::{self, serialize, Decodable, Decoder, Encodable, Encoder, VarInt};
use crate::cryptonote::hash;
#[cfg(feature = "serde_support")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "serde_support")]
use serde_big_array_unchecked_docs::*;

///Serde support for array's bigger than 32
#[allow(missing_docs)]
#[cfg(feature = "serde_support")]
pub mod serde_big_array_unchecked_docs {
    use serde_big_array::big_array;
    big_array! { BigArray; }
}

/// RingCT possible errors
#[derive(Debug)]
pub enum Error {
    /// Invalid RingCT type
    UnknownRctType,
}

// ====================================================================
/// Raw 32 bytes key
#[derive(Clone)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct Key {
    /// The actual key
    pub key: [u8; 32],
}

impl_hex_display!(Key, key);

impl_consensus_encoding!(Key, key);

// ====================================================================
/// Raw 64 bytes key
#[derive(Clone)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct Key64 {
    /// The actual key
    #[cfg_attr(feature = "serde_support", serde(with = "BigArray"))]
    pub key: [u8; 64],
}

impl_hex_display!(Key64, key);

impl_consensus_encoding!(Key64, key);

// ====================================================================
/// Confidential transaction key
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct CtKey {
    //pub dest: Key,
    /// Mask
    pub mask: Key,
}

impl_consensus_encoding!(CtKey, mask);

// ====================================================================
/// Multisig
#[derive(Debug)]
#[allow(non_snake_case)]
pub struct MultisigKLRki {
    /// K value
    pub K: Key,
    /// L value
    pub L: Key,
    /// R value
    pub R: Key,
    /// ki value
    pub ki: Key,
}

impl_consensus_encoding!(MultisigKLRki, K, L, R, ki);

// ====================================================================
/// Vector of multisig output keys
#[derive(Debug)]
pub struct MultisigOut {
    /// Vector of keys
    pub c: Vec<Key>,
}

impl_consensus_encoding!(MultisigOut, c);

// ====================================================================
/// Diffie-Hellman info
/// Mask and amount for transaction before Bulletproof2 and only 8 bytes hash for the amount in
/// Bulletproof2 type
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub enum EcdhInfo {
    /// Standard format, before bp2
    Standard {
        /// Mask value
        mask: Key,
        /// Amount value
        amount: Key,
    },
    /// bp2 format
    Bulletproof2 {
        /// Amount value
        amount: hash::Hash8,
    },
}

impl EcdhInfo {
    /// Decode Diffie-Hellman info given the RingCT type
    fn consensus_decode<D: Decoder>(
        d: &mut D,
        rct_type: RctType,
    ) -> Result<EcdhInfo, encode::Error> {
        match rct_type {
            RctType::Full | RctType::Simple | RctType::Bulletproof | RctType::Null => {
                Ok(EcdhInfo::Standard {
                    mask: Decodable::consensus_decode(d)?,
                    amount: Decodable::consensus_decode(d)?,
                })
            }
            RctType::Bulletproof2 => Ok(EcdhInfo::Bulletproof2 {
                amount: Decodable::consensus_decode(d)?,
            }),
        }
    }
}

impl<S: Encoder> Encodable<S> for EcdhInfo {
    fn consensus_encode(&self, s: &mut S) -> Result<(), encode::Error> {
        match self {
            EcdhInfo::Standard { mask, amount } => {
                mask.consensus_encode(s)?;
                amount.consensus_encode(s)?;
            }
            EcdhInfo::Bulletproof2 { amount } => {
                amount.consensus_encode(s)?;
            }
        }
        Ok(())
    }
}

// ====================================================================
/// Borromean signature for range commitment
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct BoroSig {
    /// s0 value
    pub s0: Key64,
    /// s1 value
    pub s1: Key64,
    /// ee value
    pub ee: Key,
}

impl_consensus_encoding!(BoroSig, s0, s1, ee);

// ====================================================================
/// Mg sig
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct MgSig {
    /// Matrice of keys
    pub ss: Vec<Vec<Key>>,
    /// cc value
    pub cc: Key,
}

impl<S: Encoder> Encodable<S> for MgSig {
    fn consensus_encode(&self, s: &mut S) -> Result<(), encode::Error> {
        for ss in self.ss.iter() {
            encode_sized_vec!(ss, s);
        }
        self.cc.consensus_encode(s)
    }
}

// ====================================================================
/// Range signature for range commitment
#[derive(Debug, Clone)]
#[allow(non_snake_case)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct RangeSig {
    /// asig value
    pub asig: BoroSig,
    /// Ci value
    pub Ci: Key64,
}

impl_consensus_encoding!(RangeSig, asig, Ci);

// ====================================================================
/// Bulletproof format
#[derive(Debug, Clone)]
#[allow(non_snake_case)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct Bulletproof {
    /// A value
    pub A: Key,
    /// S value
    pub S: Key,
    /// T1 value
    pub T1: Key,
    /// T2 value
    pub T2: Key,
    /// taux value
    pub taux: Key,
    /// mu value
    pub mu: Key,
    /// L value
    pub L: Vec<Key>,
    /// R value
    pub R: Vec<Key>,
    /// a value
    pub a: Key,
    /// b value
    pub b: Key,
    /// t value
    pub t: Key,
}

impl_consensus_encoding!(Bulletproof, A, S, T1, T2, taux, mu, L, R, a, b, t);

// ====================================================================
/// RingCT base signature format
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct RctSigBase {
    /// The RingCT type of signatures
    pub rct_type: RctType,
    /// Transaction fee
    pub txn_fee: VarInt,
    //pub message: Key,
    //pub mix_ring: Vec<Vec<CtKey>>,
    /// Pseudo outs key vector
    pub pseudo_outs: Vec<Key>,
    /// Ecdh info vector
    pub ecdh_info: Vec<EcdhInfo>,
    /// Out pk vector
    pub out_pk: Vec<CtKey>,
}

impl RctSigBase {
    /// Decode a RingCT base signature given the number of inputs and outputs of the transaction
    pub fn consensus_decode<D: Decoder>(
        d: &mut D,
        inputs: usize,
        outputs: usize,
    ) -> Result<Option<RctSigBase>, encode::Error> {
        let rct_type: RctType = Decodable::consensus_decode(d)?;
        match rct_type {
            RctType::Null => Ok(None),
            RctType::Full | RctType::Simple | RctType::Bulletproof | RctType::Bulletproof2 => {
                let mut pseudo_outs: Vec<Key> = vec![];
                // TxnFee
                let txn_fee: VarInt = Decodable::consensus_decode(d)?;
                // RctType
                if rct_type == RctType::Simple {
                    pseudo_outs = decode_sized_vec!(inputs, d);
                }
                // EcdhInfo
                let mut ecdh_info: Vec<EcdhInfo> = vec![];
                for _ in 0..outputs {
                    ecdh_info.push(EcdhInfo::consensus_decode(d, rct_type)?);
                }
                // OutPk
                let out_pk: Vec<CtKey> = decode_sized_vec!(outputs, d);
                Ok(Some(RctSigBase {
                    rct_type,
                    txn_fee,
                    pseudo_outs,
                    ecdh_info,
                    out_pk,
                }))
            }
        }
    }
}

impl<S: Encoder> Encodable<S> for RctSigBase {
    fn consensus_encode(&self, s: &mut S) -> Result<(), encode::Error> {
        self.rct_type.consensus_encode(s)?;
        match self.rct_type {
            RctType::Null => Ok(()),
            RctType::Full | RctType::Simple | RctType::Bulletproof | RctType::Bulletproof2 => {
                self.txn_fee.consensus_encode(s)?;
                if self.rct_type == RctType::Simple {
                    encode_sized_vec!(self.pseudo_outs, s);
                }
                encode_sized_vec!(self.ecdh_info, s);
                encode_sized_vec!(self.out_pk, s);
                Ok(())
            }
        }
    }
}

impl hash::Hashable for RctSigBase {
    fn hash(&self) -> hash::Hash {
        hash::Hash::hash(&serialize(self))
    }
}

// ====================================================================
/// RingCT types
#[derive(Debug, PartialEq, Clone, Copy)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub enum RctType {
    /// Null type
    Null,
    /// Full type
    Full,
    /// Simple type
    Simple,
    /// First Bulletproof type
    Bulletproof,
    /// Bulletproof2 type, used in the current network
    Bulletproof2,
}

impl RctType {
    /// Return if the format use one of the bulletproof format
    pub fn is_rct_bp(self) -> bool {
        match self {
            RctType::Bulletproof | RctType::Bulletproof2 => true,
            _ => false,
        }
    }
}

impl<D: Decoder> Decodable<D> for RctType {
    fn consensus_decode(d: &mut D) -> Result<RctType, encode::Error> {
        let rct_type: u8 = Decodable::consensus_decode(d)?;
        match rct_type {
            0 => Ok(RctType::Null),
            1 => Ok(RctType::Full),
            2 => Ok(RctType::Simple),
            3 => Ok(RctType::Bulletproof),
            4 => Ok(RctType::Bulletproof2),
            _ => Err(Error::UnknownRctType.into()),
        }
    }
}

impl<S: Encoder> Encodable<S> for RctType {
    fn consensus_encode(&self, s: &mut S) -> Result<(), encode::Error> {
        match self {
            RctType::Null => 0u8.consensus_encode(s)?,
            RctType::Full => 1u8.consensus_encode(s)?,
            RctType::Simple => 2u8.consensus_encode(s)?,
            RctType::Bulletproof => 3u8.consensus_encode(s)?,
            RctType::Bulletproof2 => 4u8.consensus_encode(s)?,
        }
        Ok(())
    }
}

// ====================================================================
/// Prunable part of RingCT signature format
#[derive(Debug, Clone)]
#[allow(non_snake_case)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct RctSigPrunable {
    /// Range signatures
    pub range_sigs: Vec<RangeSig>,
    /// Bulletproofs
    pub bulletproofs: Vec<Bulletproof>,
    /// MG signatures
    pub MGs: Vec<MgSig>,
    /// Pseudo out vector
    pub pseudo_outs: Vec<Key>,
}

impl RctSigPrunable {
    /// Decode a prunable RingCT signature given the number of inputs and outputs in the
    /// transaction, the RingCT type and the number of mixins
    #[allow(non_snake_case)]
    pub fn consensus_decode<D: Decoder>(
        d: &mut D,
        rct_type: RctType,
        inputs: usize,
        outputs: usize,
        mixin: usize,
    ) -> Result<Option<RctSigPrunable>, encode::Error> {
        match rct_type {
            RctType::Null => Ok(None),
            RctType::Full | RctType::Simple | RctType::Bulletproof | RctType::Bulletproof2 => {
                let mut bulletproofs: Vec<Bulletproof> = vec![];
                let mut range_sigs: Vec<RangeSig> = vec![];
                if rct_type.is_rct_bp() {
                    match rct_type {
                        RctType::Bulletproof2 => {
                            bulletproofs = Decodable::consensus_decode(d)?;
                        }
                        _ => {
                            let size: u32 = Decodable::consensus_decode(d)?;
                            bulletproofs = decode_sized_vec!(size, d);
                        }
                    };
                } else {
                    range_sigs = decode_sized_vec!(outputs, d);
                }

                let is_full = rct_type == RctType::Full;
                let mg_elements = if is_full { 1 } else { inputs };
                let mut MGs: Vec<MgSig> = vec![];
                for _ in 0..mg_elements {
                    let mut ss: Vec<Vec<Key>> = vec![];
                    for _ in 0..=mixin {
                        let mg_ss2_elements = if is_full { 1 + inputs } else { 2 };
                        let ss_elems: Vec<Key> = decode_sized_vec!(mg_ss2_elements, d);
                        ss.push(ss_elems);
                    }
                    let cc = Decodable::consensus_decode(d)?;
                    MGs.push(MgSig { ss, cc });
                }

                let mut pseudo_outs: Vec<Key> = vec![];
                match rct_type {
                    RctType::Bulletproof | RctType::Bulletproof2 => {
                        pseudo_outs = decode_sized_vec!(inputs, d);
                    }
                    _ => (),
                }
                Ok(Some(RctSigPrunable {
                    range_sigs,
                    bulletproofs,
                    MGs,
                    pseudo_outs,
                }))
            }
        }
    }

    /// Encode the prunable RingCT signature part given the RingCT type of the transaction
    pub fn consensus_encode<S: Encoder>(
        &self,
        s: &mut S,
        rct_type: RctType,
    ) -> Result<(), encode::Error> {
        match rct_type {
            RctType::Null => Ok(()),
            RctType::Full | RctType::Simple | RctType::Bulletproof | RctType::Bulletproof2 => {
                if rct_type.is_rct_bp() {
                    match rct_type {
                        RctType::Bulletproof2 => {
                            self.bulletproofs.consensus_encode(s)?;
                        }
                        _ => {
                            let size: u32 = self.bulletproofs.len() as u32;
                            size.consensus_encode(s)?;
                            encode_sized_vec!(self.bulletproofs, s);
                        }
                    }
                } else {
                    encode_sized_vec!(self.range_sigs, s);
                }
                encode_sized_vec!(self.MGs, s);
                match rct_type {
                    RctType::Bulletproof | RctType::Bulletproof2 => {
                        encode_sized_vec!(self.pseudo_outs, s);
                    }
                    _ => (),
                }
                Ok(())
            }
        }
    }
}

// ====================================================================
/// A RingCT signature
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct RctSig {
    /// The base part
    pub sig: Option<RctSigBase>,
    /// The prunable part
    pub p: Option<RctSigPrunable>,
}

// ====================================================================
/// A raw signature
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct Signature {
    /// c value
    pub c: Key,
    /// r value
    pub r: Key,
}

impl_consensus_encoding!(Signature, c, r);