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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
// Rust Wownero Library
// Written in 2019-2022 by
//    Monero Rust Contributors
// Adapted to Wownero in 2022 by
//    Boog900
//
// 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.
//

//! Ring Confidential Transaction primitive types.
//!
//! Support for parsing Ring Confidential Transaction signature within [`Transaction`].
//!
//! [`Transaction`]: crate::blockdata::transaction::Transaction
//!

use std::{fmt, io};

use crate::consensus::encode::{self, serialize, Decodable, Encodable, VarInt};
use crate::cryptonote::hash;
use crate::cryptonote::onetime_key::KeyGenerator;
use crate::util::key::H;
use crate::{PublicKey, ViewPair};

#[cfg(feature = "serde")]
use serde_big_array::BigArray;
#[cfg(feature = "serde")]
use serde_crate::{Deserialize, Serialize};

use curve25519_dalek::constants::ED25519_BASEPOINT_POINT;
use curve25519_dalek::edwards::EdwardsPoint;
use curve25519_dalek::scalar::Scalar;
use sealed::sealed;
use thiserror::Error;

use std::convert::TryInto;

/// Ring Confidential Transaction potential errors.
#[derive(Error, Debug, PartialEq)]
pub enum Error {
    /// Invalid RingCt type.
    #[error("Unknown RingCt type")]
    UnknownRctType,
}

// ====================================================================
/// Raw 32 bytes key.
#[derive(Clone, Copy, PartialEq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(crate = "serde_crate"))]
pub struct Key {
    /// The actual key.
    pub key: [u8; 32],
}

impl_hex_display!(Key, key);

impl_consensus_encoding!(Key, key);

impl Key {
    fn new() -> Key {
        Key { key: [0; 32] }
    }
}

impl From<[u8; 32]> for Key {
    fn from(key: [u8; 32]) -> Self {
        Self { key }
    }
}

// ====================================================================
/// An array of 64 32-byte keys.
#[derive(Debug, Clone, Copy, PartialEq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(crate = "serde_crate"))]
pub struct Key64 {
    /// The actual key.
    #[cfg_attr(feature = "serde", serde(with = "BigArray"))]
    pub keys: [Key; 64],
}

impl Key64 {
    fn new() -> Key64 {
        Key64 {
            keys: [Key::new(); 64],
        }
    }
}

impl From<[Key; 64]> for Key64 {
    fn from(keys: [Key; 64]) -> Self {
        Self { keys }
    }
}

impl Decodable for Key64 {
    fn consensus_decode<D: io::Read>(d: &mut D) -> Result<Key64, encode::Error> {
        let mut key64 = Key64::new();
        for i in 0..64 {
            let key: Key = Decodable::consensus_decode(d)?;
            key64.keys[i] = key;
        }
        Ok(key64)
    }
}

#[sealed]
impl crate::consensus::encode::Encodable for Key64 {
    fn consensus_encode<S: io::Write>(&self, s: &mut S) -> Result<usize, io::Error> {
        let mut len = 0;
        for i in 0..64 {
            len += self.keys[i].consensus_encode(s)?;
        }
        Ok(len)
    }
}

impl fmt::Display for Key64 {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        for key in self.keys.iter() {
            writeln!(fmt, "{}", key)?;
        }
        Ok(())
    }
}

// ====================================================================
/// Confidential transaction key.
#[derive(Debug, Clone, Copy, PartialEq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(crate = "serde_crate"))]
pub struct CtKey {
    //pub dest: Key,
    /// Mask.
    pub mask: Key,
}

impl fmt::Display for CtKey {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        writeln!(fmt, "Mask: {}", self.mask)
    }
}

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", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(crate = "serde_crate"))]
pub enum EcdhInfo {
    /// Standard format, before `Bulletproof2`.
    Standard {
        /// Mask value.
        mask: Key,
        /// Amount value.
        amount: Key,
    },
    /// Bulletproof format.
    Bulletproof {
        /// Amount value.
        amount: hash::Hash8,
    },
}

impl EcdhInfo {
    /// Opens the commitment and verifies it against the given one.
    pub fn open_commitment(
        &self,
        view_pair: &ViewPair,
        tx_pubkey: &PublicKey,
        index: usize,
        candidate_commitment: &EdwardsPoint,
    ) -> Option<Opening> {
        let shared_key = KeyGenerator::from_key(view_pair, *tx_pubkey).get_rvn_scalar(index);

        let (amount, blinding_factor) = match self {
            // ecdhDecode in rctOps.cpp else
            EcdhInfo::Standard { mask, amount } => {
                let shared_sec1 = hash::Hash::new(shared_key.as_bytes()).to_bytes();
                let shared_sec2 = hash::Hash::new(&shared_sec1).to_bytes();
                let mask_scalar = Scalar::from_bytes_mod_order(mask.key)
                    - Scalar::from_bytes_mod_order(shared_sec1);

                let amount_scalar = Scalar::from_bytes_mod_order(amount.key)
                    - Scalar::from_bytes_mod_order(shared_sec2);
                // get first 64 bits (d2b in rctTypes.cpp)
                let amount_significant_bytes = amount_scalar.to_bytes()[0..8]
                    .try_into()
                    .expect("Can't fail");
                let amount = u64::from_le_bytes(amount_significant_bytes);
                (amount, mask_scalar)
            }
            // ecdhDecode in rctOps.cpp if (v2)
            EcdhInfo::Bulletproof { amount } => {
                let amount = xor_amount(amount.0, shared_key.scalar);
                let mask = mask(shared_key.scalar);

                (u64::from_le_bytes(amount), mask)
            }
        };

        let amount_scalar = Scalar::from(amount);

        let expected_commitment = ED25519_BASEPOINT_POINT * blinding_factor
            + H.point.decompress().unwrap() * amount_scalar;

        if &expected_commitment != candidate_commitment {
            return None;
        }

        Some(Opening {
            amount,
            blinding_factor,
            commitment: expected_commitment,
        })
    }
}

/// The result of opening the commitment inside the transaction.
#[derive(Debug)]
pub struct Opening {
    /// The original amount of the output.
    pub amount: u64,
    /// The blinding factor used to blind the amount.
    pub blinding_factor: Scalar,
    /// The commitment used to verify the blinded amount.
    pub commitment: EdwardsPoint,
}

fn xor_amount(amount: [u8; 8], shared_key: Scalar) -> [u8; 8] {
    // ecdhHash in .cpp
    let mut amount_key = b"amount".to_vec();
    amount_key.extend(shared_key.as_bytes());

    // Hn("amount", Hn(rKbv,t))
    let hash_shared_key = hash::Hash::new(&amount_key).to_fixed_bytes();
    let hash_shared_key_significant_bytes = hash_shared_key[0..8]
        .try_into()
        .expect("hash_shared_key create above has 32 bytes");

    // amount_t = bt XOR Hn("amount", Hn("amount", Hn(rKbv,t)))
    // xor8(masked.amount, ecdhHash(sharedSec)); in .cpp
    (u64::from_le_bytes(amount) ^ u64::from_le_bytes(hash_shared_key_significant_bytes))
        .to_le_bytes()
}

fn mask(scalar: Scalar) -> Scalar {
    let mut commitment_key = b"commitment_mask".to_vec();
    commitment_key.extend(scalar.as_bytes());

    // yt in Z2M p 53
    hash::Hash::hash_to_scalar(&commitment_key).scalar
}

impl fmt::Display for EcdhInfo {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        match self {
            EcdhInfo::Standard { mask, amount } => {
                writeln!(fmt, "Standard")?;
                writeln!(fmt, "Mask: {}", mask)?;
                writeln!(fmt, "Amount: {}", amount)?;
            }
            EcdhInfo::Bulletproof { amount } => {
                writeln!(fmt, "Bulletproof2")?;
                writeln!(fmt, "Amount: {}", amount)?;
            }
        };
        Ok(())
    }
}

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

#[sealed]
impl crate::consensus::encode::Encodable for EcdhInfo {
    fn consensus_encode<S: io::Write>(&self, s: &mut S) -> Result<usize, io::Error> {
        let mut len = 0;
        match self {
            EcdhInfo::Standard { mask, amount } => {
                len += mask.consensus_encode(s)?;
                len += amount.consensus_encode(s)?;
            }
            EcdhInfo::Bulletproof { amount } => {
                len += amount.consensus_encode(s)?;
            }
        }
        Ok(len)
    }
}

// ====================================================================
/// Borromean signature for range commitment.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(crate = "serde_crate"))]
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);

// ====================================================================
/// Contains the necessary keys to represent Mlsag signature.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(crate = "serde_crate"))]
pub struct MgSig {
    /// Matrice of keys.
    pub ss: Vec<Vec<Key>>,
    /// cc value.
    pub cc: Key,
}

#[sealed]
impl crate::consensus::encode::Encodable for MgSig {
    fn consensus_encode<S: io::Write>(&self, s: &mut S) -> Result<usize, io::Error> {
        let mut len = 0;
        for ss in self.ss.iter() {
            len += encode_sized_vec!(ss, s);
        }
        len += self.cc.consensus_encode(s)?;
        Ok(len)
    }
}

// ====================================================================
/// Clsag signature.
#[derive(Debug, Clone)]
#[allow(non_snake_case)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(crate = "serde_crate"))]
pub struct Clsag {
    /// scalars.
    pub s: Vec<Key>,
    /// c1 value.
    pub c1: Key,
    /// commitment key image.
    pub D: Key,
}

#[sealed]
impl crate::consensus::encode::Encodable for Clsag {
    fn consensus_encode<S: io::Write>(&self, s: &mut S) -> Result<usize, io::Error> {
        let mut len = 0;
        // Encode the vector without prefix lenght
        len += encode_sized_vec!(self.s, s);
        len += self.c1.consensus_encode(s)?;
        len += self.D.consensus_encode(s)?;
        Ok(len)
    }
}

// ====================================================================
/// Range signature for range commitment.
#[derive(Debug, Clone)]
#[allow(non_snake_case)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(crate = "serde_crate"))]
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", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(crate = "serde_crate"))]
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);

// ====================================================================
/// BulletproofPlus format.
#[derive(Debug, Clone)]
#[allow(non_snake_case)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(crate = "serde_crate"))]
pub struct BulletproofPlus {
    /// A value.
    pub A: Key,
    /// S value.
    pub A1: Key,
    /// B value.
    pub B: Key,
    /// r1 value.
    pub r1: Key,
    /// s1 value.
    pub s1: Key,
    /// d1 value.
    pub d1: Key,
    /// L value.
    pub L: Vec<Key>,
    /// R value.
    pub R: Vec<Key>,
}

impl_consensus_encoding!(BulletproofPlus, A, A1, B, r1, s1, d1, L, R);
// ====================================================================
/// RingCt base signature format.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(crate = "serde_crate"))]
pub struct RctSigBase {
    /// The RingCt type of signatures.
    pub rct_type: RctType,
    /// Transaction fee.
    pub txn_fee: VarInt,
    /// 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 fmt::Display for RctSigBase {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        writeln!(fmt, "RCT type: {}", self.rct_type)?;
        writeln!(fmt, "Tx fee: {}", self.txn_fee)?;
        for out in &self.pseudo_outs {
            writeln!(fmt, "Pseudo out: {}", out)?;
        }
        for ecdh in &self.ecdh_info {
            writeln!(fmt, "Ecdh info: {}", ecdh)?;
        }
        for out in &self.out_pk {
            writeln!(fmt, "Out pk: {}", out)?;
        }
        Ok(())
    }
}

impl RctSigBase {
    /// Decode a RingCt base signature given the number of inputs and outputs of the transaction.
    pub fn consensus_decode<D: io::Read>(
        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(Some(RctSigBase {
                rct_type: RctType::Null,
                txn_fee: Default::default(),
                pseudo_outs: vec![],
                ecdh_info: vec![],
                out_pk: vec![],
            })),
            RctType::Full
            | RctType::Simple
            | RctType::FullBulletproof
            | RctType::SimpleBulletproof
            | RctType::Bulletproof
            | RctType::Bulletproof2
            | RctType::Clsag
            | RctType::BulletproofPlus => {
                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,
                }))
            }
        }
    }
}

#[sealed]
impl crate::consensus::encode::Encodable for RctSigBase {
    fn consensus_encode<S: io::Write>(&self, s: &mut S) -> Result<usize, io::Error> {
        let mut len = 0;
        len += self.rct_type.consensus_encode(s)?;
        match self.rct_type {
            RctType::Null => Ok(len),
            RctType::Full
            | RctType::Simple
            | RctType::FullBulletproof
            | RctType::SimpleBulletproof
            | RctType::Bulletproof
            | RctType::Bulletproof2
            | RctType::Clsag
            | RctType::BulletproofPlus => {
                len += self.txn_fee.consensus_encode(s)?;
                if self.rct_type == RctType::Simple {
                    len += encode_sized_vec!(self.pseudo_outs, s);
                }
                len += encode_sized_vec!(self.ecdh_info, s);
                len += encode_sized_vec!(self.out_pk, s);
                Ok(len)
            }
        }
    }
}

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

// ====================================================================
/// Types of Ring Confidential Transaction signatures.
#[derive(Debug, PartialEq, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(crate = "serde_crate"))]
pub enum RctType {
    /// Null type.
    Null,
    /// Full type.
    Full,
    /// Simple type.
    Simple,
    /// Full Bulletproof type,
    FullBulletproof,
    /// Simple Bulletproof type
    SimpleBulletproof,
    /// Normal Bulletproof type.
    Bulletproof,
    /// Bulletproof2 type.
    Bulletproof2,
    /// Clsag Ring signatures,
    Clsag,
    /// Bulletproof+ type, used in the current network.
    BulletproofPlus,
}

impl fmt::Display for RctType {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        let rct_type = match self {
            RctType::Null => "Null",
            RctType::Full => "Full",
            RctType::Simple => "Simple",
            RctType::FullBulletproof => "FullBulletproof",
            RctType::SimpleBulletproof => "SimpleBulletproof",
            RctType::Bulletproof => "Bulletproof",
            RctType::Bulletproof2 => "Bulletproof2",
            RctType::Clsag => "Clsag",
            RctType::BulletproofPlus => "Bulletproof+",
        };
        write!(fmt, "{}", rct_type)
    }
}

impl RctType {
    /// Return if the format use one of the bulletproof format.
    pub fn is_rct_bp(self) -> bool {
        matches!(
            self,
            RctType::FullBulletproof
                | RctType::SimpleBulletproof
                | RctType::Bulletproof
                | RctType::Bulletproof2
                | RctType::Clsag
        )
    }
    /// Return if the format use one of the bulletproofPlus format.
    pub fn is_rct_bp_plus(self) -> bool {
        matches!(self, RctType::BulletproofPlus)
    }
}

impl Decodable for RctType {
    fn consensus_decode<D: io::Read>(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::FullBulletproof),
            4 => Ok(RctType::SimpleBulletproof),
            5 => Ok(RctType::Bulletproof),
            6 => Ok(RctType::Bulletproof2),
            7 => Ok(RctType::Clsag),
            8 => Ok(RctType::BulletproofPlus),
            _ => Err(Error::UnknownRctType.into()),
        }
    }
}

#[sealed]
impl crate::consensus::encode::Encodable for RctType {
    fn consensus_encode<S: io::Write>(&self, s: &mut S) -> Result<usize, io::Error> {
        match self {
            RctType::Null => 0u8.consensus_encode(s),
            RctType::Full => 1u8.consensus_encode(s),
            RctType::Simple => 2u8.consensus_encode(s),
            RctType::FullBulletproof => 3u8.consensus_encode(s),
            RctType::SimpleBulletproof => 4u8.consensus_encode(s),
            RctType::Bulletproof => 5u8.consensus_encode(s),
            RctType::Bulletproof2 => 6u8.consensus_encode(s),
            RctType::Clsag => 7u8.consensus_encode(s),
            RctType::BulletproofPlus => 8u8.consensus_encode(s),
        }
    }
}

// ====================================================================
/// Prunable part of RingCt signature format.
#[derive(Debug, Clone)]
#[allow(non_snake_case)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(crate = "serde_crate"))]
pub struct RctSigPrunable {
    /// Range signatures.
    pub range_sigs: Vec<RangeSig>,
    /// Bulletproofs.
    pub bulletproofs: Vec<Bulletproof>,
    /// BulletproofPlus
    pub bulletproofplus: Vec<BulletproofPlus>,
    /// MSLAG signatures, simple rct has N, full has 1.
    pub MGs: Vec<MgSig>,
    /// CSLAG signatures.
    pub Clsags: Vec<Clsag>,
    /// 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: io::Read>(
        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::FullBulletproof
            | RctType::SimpleBulletproof
            | RctType::Bulletproof
            | RctType::Bulletproof2
            | RctType::Clsag
            | RctType::BulletproofPlus => {
                let mut bulletproofs: Vec<Bulletproof> = vec![];
                let mut bulletproofplus: Vec<BulletproofPlus> = vec![];
                let mut range_sigs: Vec<RangeSig> = vec![];
                if rct_type.is_rct_bp() {
                    match rct_type {
                        RctType::Bulletproof2 | RctType::Clsag | RctType::BulletproofPlus => {
                            bulletproofs = Decodable::consensus_decode(d)?;
                        }
                        RctType::FullBulletproof | RctType::SimpleBulletproof => {
                            let size: u32 = outputs as u32;
                            bulletproofs = decode_sized_vec!(size, d);
                        }
                        _ => {
                            let size: u32 = Decodable::consensus_decode(d)?;
                            bulletproofs = decode_sized_vec!(size, d);
                        }
                    }
                } else if rct_type.is_rct_bp_plus() {
                    let size: u8 = Decodable::consensus_decode(d)?;
                    bulletproofplus = decode_sized_vec!(size, d);
                } else {
                    range_sigs = decode_sized_vec!(outputs, d);
                }

                let mut Clsags: Vec<Clsag> = vec![];
                let mut MGs: Vec<MgSig> = vec![];

                match rct_type {
                    RctType::Clsag | RctType::BulletproofPlus => {
                        for _ in 0..inputs {
                            let mut s: Vec<Key> = vec![];
                            for _ in 0..=mixin {
                                let s_elems: Key = Decodable::consensus_decode(d)?;
                                s.push(s_elems);
                            }
                            let c1 = Decodable::consensus_decode(d)?;
                            let D = Decodable::consensus_decode(d)?;
                            Clsags.push(Clsag { s, c1, D });
                        }
                    }
                    _ => {
                        let is_full =
                            rct_type == RctType::Full || rct_type == RctType::FullBulletproof;
                        let mg_elements = if !is_full { inputs } else { 1 };
                        for _ in 0..mg_elements {
                            let mut ss: Vec<Vec<Key>> = vec![];
                            for _ in 0..=mixin {
                                let mg_ss2_elements = if !is_full { 2 } else { 1 + inputs };
                                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::SimpleBulletproof
                    | RctType::Bulletproof2
                    | RctType::Clsag
                    | RctType::BulletproofPlus => {
                        pseudo_outs = decode_sized_vec!(inputs, d);
                    }
                    _ => (),
                }

                Ok(Some(RctSigPrunable {
                    range_sigs,
                    bulletproofs,
                    bulletproofplus,
                    MGs,
                    Clsags,
                    pseudo_outs,
                }))
            }
        }
    }

    /// Encode the prunable RingCt signature part given the RingCt type of the transaction.
    pub fn consensus_encode<S: io::Write>(
        &self,
        s: &mut S,
        rct_type: RctType,
    ) -> Result<usize, io::Error> {
        match rct_type {
            RctType::Null => Ok(0),
            RctType::Full
            | RctType::Simple
            | RctType::FullBulletproof
            | RctType::SimpleBulletproof
            | RctType::Bulletproof
            | RctType::Bulletproof2
            | RctType::Clsag
            | RctType::BulletproofPlus => {
                let mut len = 0;
                if rct_type.is_rct_bp() {
                    match rct_type {
                        RctType::Bulletproof2 | RctType::Clsag => {
                            len += self.bulletproofs.consensus_encode(s)?;
                        }
                        RctType::FullBulletproof | RctType::SimpleBulletproof => {
                            len += encode_sized_vec!(self.bulletproofs, s);
                        }
                        _ => {
                            let size: u32 = self.bulletproofs.len() as u32;
                            len += size.consensus_encode(s)?;
                            len += encode_sized_vec!(self.bulletproofs, s);
                        }
                    }
                } else if rct_type.is_rct_bp_plus() {
                    let size: u8 = self.bulletproofplus.len() as u8;
                    len += size.consensus_encode(s)?;
                    len += encode_sized_vec!(self.bulletproofplus, s);
                } else {
                    len += encode_sized_vec!(self.range_sigs, s);
                }

                match rct_type {
                    RctType::Clsag | RctType::BulletproofPlus => {
                        len += encode_sized_vec!(self.Clsags, s)
                    }
                    _ => len += encode_sized_vec!(self.MGs, s),
                }

                match rct_type {
                    RctType::Bulletproof
                    | RctType::SimpleBulletproof
                    | RctType::Bulletproof2
                    | RctType::Clsag
                    | RctType::BulletproofPlus => {
                        len += encode_sized_vec!(self.pseudo_outs, s);
                    }
                    _ => (),
                }
                Ok(len)
            }
        }
    }
}

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

impl fmt::Display for RctSig {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        match &self.sig {
            Some(v) => writeln!(fmt, "Signature: {}", v)?,
            None => writeln!(fmt, "Signature: None")?,
        };
        Ok(())
    }
}

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

impl fmt::Display for Signature {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        writeln!(fmt, "C: {}", self.c)?;
        writeln!(fmt, "R: {}", self.r)
    }
}

impl_consensus_encoding!(Signature, c, r);