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
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
//! Copyright (c) 2022 MASSA LABS <info@massa.net>

//! Denunciation intro
//!
//! Currently, nothing prevents a user from producing multiple blocks (for the same Slot) or endorsing a block multiple times.
//! If an invalid Denunciation will just be ignored, a valid Denunciation will slash some locked rolls.
//! Note that this proposal aims at dissuading 'rational' users from causing damage but does help against 'byzantine' actors
//! that just want to disturb or break the blockclique (at any cost).
//!
//! Denunciation structure
//!
//! A denunciation embeds some information such as
//! Slot, the slot from the block header or the endorsements (+ index)
//! A public key: the public key of the secure share endorsement or secured header
//! 2 Hashes & 2 Signatures
//!
//! All of this constitutes a proof (and is verifiable) that a user produced multiple (at least 2) blocks or endorsements
//!
//! Denunciation creation
//!
//! Denunciations are created in a Denunciation pool, receiving new blocks & block headers & endorsements from various places.
//! The denunciation pool is also responsible of returning a list of denunciations to insert into a new block header.
//! After execution, the denunciation is kept for some time inside `executed_denunciations`
//! in order to prevent multiple executions. Note that this structure is part of the final state hash and thus is bootstrapped.
//!
//! Denunciation execution
//!
//! When a Denunciation is proven valid, we then need to ensure that the user has sufficient funds. If we cannot deduct the funds on node
//! balance or staked rolls, we will use 'locked' rolls` (or Deferred credits).
//! Selling a roll will lock it for some time (== 4 cycles). Note that it restricts the time,
//! a denunciation can be produced (A constant value will be defined for this).

#![allow(missing_docs)]

use std::cmp::Ordering;
use std::ops::Bound::{Excluded, Included};

use nom::{
    error::{context, ContextError, ParseError},
    sequence::tuple,
    IResult, Parser,
};
use num_enum::{IntoPrimitive, TryFromPrimitive};
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::block_header::{BlockHeaderDenunciationData, SecuredHeader};
use crate::endorsement::{EndorsementDenunciationData, SecureShareEndorsement};
use crate::slot::{Slot, SlotDeserializer, SlotSerializer};

use crate::secure_share::Id;
use massa_hash::{Hash, HashDeserializer, HashSerializer};
use massa_serialization::{
    Deserializer, SerializeError, Serializer, U32VarIntDeserializer, U32VarIntSerializer,
};
use massa_signature::{
    MassaSignatureError, PublicKey, PublicKeyDeserializer, Signature, SignatureDeserializer,
};
use variant_count::VariantCount;

/// A Variant of Denunciation enum for endorsement
#[allow(dead_code)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EndorsementDenunciation {
    public_key: PublicKey,
    slot: Slot,
    index: u32,
    hash_1: Hash,
    hash_2: Hash,
    signature_1: Signature,
    signature_2: Signature,
}

impl EndorsementDenunciation {
    /// Rebuild full hash of SecureShareEndorsement from given arguments
    fn compute_hash_for_sig_verif(
        public_key: &PublicKey,
        slot: &Slot,
        index: &u32,
        content_hash: &Hash,
    ) -> Hash {
        let mut hash_data = Vec::new();
        // Public key
        hash_data.extend(public_key.to_bytes());
        // Ser slot & index
        let denunciation_data = EndorsementDenunciationData::new(*slot, *index);
        hash_data.extend(&denunciation_data.to_bytes());
        // Add content hash
        hash_data.extend(content_hash.to_bytes());
        Hash::compute_from(&hash_data)
    }

    // Getters (for GRPC From)
    pub fn get_public_key(&self) -> &PublicKey {
        &self.public_key
    }
    pub fn get_slot(&self) -> &Slot {
        &self.slot
    }
    pub fn get_index(&self) -> &u32 {
        &self.index
    }
    pub fn get_hash_1(&self) -> &Hash {
        &self.hash_1
    }
    pub fn get_hash_2(&self) -> &Hash {
        &self.hash_2
    }
    pub fn get_signature_1(&self) -> &Signature {
        &self.signature_1
    }
    pub fn get_signature_2(&self) -> &Signature {
        &self.signature_2
    }
}

/// A Variant of Denunciation enum for block header
#[allow(dead_code)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BlockHeaderDenunciation {
    public_key: PublicKey,
    slot: Slot,
    hash_1: Hash,
    hash_2: Hash,
    signature_1: Signature,
    signature_2: Signature,
}

impl BlockHeaderDenunciation {
    /// Rebuild full hash of SecuredHeader from given arguments
    fn compute_hash_for_sig_verif(
        public_key: &PublicKey,
        slot: &Slot,
        content_hash: &Hash,
    ) -> Hash {
        let mut hash_data = Vec::new();
        // Public key
        hash_data.extend(public_key.to_bytes());
        // Ser slot
        let de_data = BlockHeaderDenunciationData::new(*slot);
        hash_data.extend(de_data.to_bytes());
        // Add content hash
        hash_data.extend(content_hash.to_bytes());
        Hash::compute_from(&hash_data)
    }

    // Getters (for GRPC From)
    pub fn get_public_key(&self) -> &PublicKey {
        &self.public_key
    }
    pub fn get_slot(&self) -> &Slot {
        &self.slot
    }
    pub fn get_hash_1(&self) -> &Hash {
        &self.hash_1
    }
    pub fn get_hash_2(&self) -> &Hash {
        &self.hash_2
    }
    pub fn get_signature_1(&self) -> &Signature {
        &self.signature_1
    }
    pub fn get_signature_2(&self) -> &Signature {
        &self.signature_2
    }
}

/// A denunciation enum
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[allow(missing_docs)]
pub enum Denunciation {
    Endorsement(EndorsementDenunciation),
    BlockHeader(BlockHeaderDenunciation),
}

#[allow(dead_code)]
impl Denunciation {
    /// Check if it is a Denunciation of several endorsements
    pub fn is_for_endorsement(&self) -> bool {
        matches!(self, Denunciation::Endorsement(_))
    }

    /// Check if it is a Denunciation of several block headers
    pub fn is_for_block_header(&self) -> bool {
        matches!(self, Denunciation::BlockHeader(_))
    }

    /// Check if it is a Denunciation for this endorsement
    pub fn is_also_for_endorsement(
        &self,
        s_endorsement: &SecureShareEndorsement,
    ) -> Result<bool, DenunciationError> {
        match self {
            Denunciation::BlockHeader(_) => Ok(false),
            Denunciation::Endorsement(endo_de) => {
                let content_hash = s_endorsement.id.get_hash();

                let hash = EndorsementDenunciation::compute_hash_for_sig_verif(
                    &endo_de.public_key,
                    &endo_de.slot,
                    &endo_de.index,
                    content_hash,
                );

                Ok(endo_de.slot == s_endorsement.content.slot
                    && endo_de.index == s_endorsement.content.index
                    && endo_de.public_key == s_endorsement.content_creator_pub_key
                    && endo_de.hash_1 != *content_hash
                    && endo_de.hash_2 != *content_hash
                    && endo_de
                        .public_key
                        .verify_signature(&hash, &s_endorsement.signature)
                        .is_ok())
            }
        }
    }

    /// Check if it is a Denunciation for this block header
    pub fn is_also_for_block_header(
        &self,
        s_block_header: &SecuredHeader,
    ) -> Result<bool, DenunciationError> {
        match self {
            Denunciation::Endorsement(_) => Ok(false),
            Denunciation::BlockHeader(endo_bh) => {
                let content_hash = s_block_header.id.get_hash();

                let hash = BlockHeaderDenunciation::compute_hash_for_sig_verif(
                    &endo_bh.public_key,
                    &endo_bh.slot,
                    content_hash,
                );

                Ok(endo_bh.slot == s_block_header.content.slot
                    && endo_bh.public_key == s_block_header.content_creator_pub_key
                    && endo_bh.hash_1 != *content_hash
                    && endo_bh.hash_2 != *content_hash
                    && endo_bh
                        .public_key
                        .verify_signature(&hash, &s_block_header.signature)
                        .is_ok())
            }
        }
    }

    /// Check if Denunciation is valid
    /// Should be used if received from the network (prevent against invalid or attacker crafted denunciation)
    pub fn is_valid(&self) -> bool {
        let (signature_1, signature_2, hash_1, hash_2, public_key) = match self {
            Denunciation::Endorsement(de) => {
                let hash_1 = EndorsementDenunciation::compute_hash_for_sig_verif(
                    &de.public_key,
                    &de.slot,
                    &de.index,
                    &de.hash_1,
                );
                let hash_2 = EndorsementDenunciation::compute_hash_for_sig_verif(
                    &de.public_key,
                    &de.slot,
                    &de.index,
                    &de.hash_2,
                );

                (
                    de.signature_1,
                    de.signature_2,
                    hash_1,
                    hash_2,
                    de.public_key,
                )
            }
            Denunciation::BlockHeader(de) => {
                let hash_1 = BlockHeaderDenunciation::compute_hash_for_sig_verif(
                    &de.public_key,
                    &de.slot,
                    &de.hash_1,
                );
                let hash_2 = BlockHeaderDenunciation::compute_hash_for_sig_verif(
                    &de.public_key,
                    &de.slot,
                    &de.hash_2,
                );

                (
                    de.signature_1,
                    de.signature_2,
                    hash_1,
                    hash_2,
                    de.public_key,
                )
            }
        };

        hash_1 != hash_2
            && public_key.verify_signature(&hash_1, &signature_1).is_ok()
            && public_key.verify_signature(&hash_2, &signature_2).is_ok()
    }

    /// Get Denunciation slot ref
    pub fn get_slot(&self) -> &Slot {
        match self {
            Denunciation::Endorsement(de) => &de.slot,
            Denunciation::BlockHeader(de) => &de.slot,
        }
    }

    /// Get field: index (return None for a block header denunciation)
    pub fn get_index(&self) -> Option<&u32> {
        match self {
            Denunciation::BlockHeader(_) => None,
            Denunciation::Endorsement(de) => Some(&de.index),
        }
    }

    /// Get Denunciation public key ref
    pub fn get_public_key(&self) -> &PublicKey {
        match self {
            Denunciation::Endorsement(de) => &de.public_key,
            Denunciation::BlockHeader(de) => &de.public_key,
        }
    }

    /// Check if denunciation has expired given a slot period
    /// Note that slot_period can be:
    /// * A final slot period (for example in order to cleanup denunciation pool caches)
    /// * A block slot period (in execution (execute_denunciation(...)))
    pub fn is_expired(
        denunciation_slot_period: &u64,
        slot_period: &u64,
        denunciation_expire_periods: &u64,
    ) -> bool {
        slot_period.checked_sub(*denunciation_slot_period) > Some(*denunciation_expire_periods)
    }
}

/// Create a new Denunciation from 2 SecureShareEndorsement
impl TryFrom<(&SecureShareEndorsement, &SecureShareEndorsement)> for Denunciation {
    type Error = DenunciationError;

    fn try_from(
        (s_e1, s_e2): (&SecureShareEndorsement, &SecureShareEndorsement),
    ) -> Result<Self, Self::Error> {
        // In order to create a Denunciation, there should be the same
        // slot, index & public key
        if s_e1.content.slot != s_e2.content.slot
            || s_e1.content.index != s_e2.content.index
            || s_e1.content_creator_pub_key != s_e2.content_creator_pub_key
            || s_e1.id == s_e2.id
        {
            return Err(DenunciationError::InvalidInput(format!(
                "Not the same slot, index or public key or same hash for {:?} & {:?}",
                s_e1, s_e2
            )));
        }

        // Check sig of s_e1 with s_e1.public_key, s_e1.slot, s_e1.index
        let s_e1_hash_content = s_e1.id.get_hash();
        let s_e1_hash = EndorsementDenunciation::compute_hash_for_sig_verif(
            &s_e1.content_creator_pub_key,
            &s_e1.content.slot,
            &s_e1.content.index,
            s_e1_hash_content,
        );
        // Check sig of s_e2 but with s_e1.public_key, s_e1.slot, s_e1.index
        let s_e2_hash_content = s_e2.id.get_hash();
        let s_e2_hash = EndorsementDenunciation::compute_hash_for_sig_verif(
            &s_e1.content_creator_pub_key,
            &s_e1.content.slot,
            &s_e1.content.index,
            s_e2_hash_content,
        );

        s_e1.content_creator_pub_key
            .verify_signature(&s_e1_hash, &s_e1.signature)?;
        s_e1.content_creator_pub_key
            .verify_signature(&s_e2_hash, &s_e2.signature)?;

        Ok(Denunciation::Endorsement(EndorsementDenunciation {
            public_key: s_e1.content_creator_pub_key,
            slot: s_e1.content.slot,
            index: s_e1.content.index,
            signature_1: s_e1.signature,
            signature_2: s_e2.signature,
            hash_1: *s_e1_hash_content,
            hash_2: *s_e2_hash_content,
        }))
    }
}

/// Create a new Denunciation from 2 SecureHeader
impl TryFrom<(&SecuredHeader, &SecuredHeader)> for Denunciation {
    type Error = DenunciationError;

    fn try_from((s_bh1, s_bh2): (&SecuredHeader, &SecuredHeader)) -> Result<Self, Self::Error> {
        // Cannot use the same block header twice
        // In order to create a Denunciation, there should be the same slot & public key
        if s_bh1.content.slot != s_bh2.content.slot
            || s_bh1.content_creator_pub_key != s_bh2.content_creator_pub_key
            || s_bh1.id == s_bh2.id
        {
            return Err(DenunciationError::InvalidInput(format!(
                "Not the same slot or public key or same hash for {:?} & {:?}",
                s_bh1, s_bh2
            )));
        }

        // Check sig of s_bh2 but with s_bh1.public_key, s_bh1.slot, s_bh1.index
        let s_bh1_hash_content = s_bh1.id.get_hash();
        let s_bh1_hash = BlockHeaderDenunciation::compute_hash_for_sig_verif(
            &s_bh1.content_creator_pub_key,
            &s_bh1.content.slot,
            s_bh1_hash_content,
        );
        let s_bh2_hash_content = s_bh2.id.get_hash();
        let s_bh2_hash = BlockHeaderDenunciation::compute_hash_for_sig_verif(
            &s_bh1.content_creator_pub_key,
            &s_bh1.content.slot,
            s_bh2_hash_content,
        );

        s_bh1
            .content_creator_pub_key
            .verify_signature(&s_bh1_hash, &s_bh1.signature)?;
        s_bh1
            .content_creator_pub_key
            .verify_signature(&s_bh2_hash, &s_bh2.signature)?;

        Ok(Denunciation::BlockHeader(BlockHeaderDenunciation {
            public_key: s_bh1.content_creator_pub_key,
            slot: s_bh1.content.slot,
            signature_1: s_bh1.signature,
            signature_2: s_bh2.signature,
            hash_1: *s_bh1_hash_content,
            hash_2: *s_bh2_hash_content,
        }))
    }
}

#[allow(missing_docs)]
#[derive(IntoPrimitive, Debug, TryFromPrimitive, VariantCount)]
#[repr(u32)]
pub enum DenunciationTypeId {
    BlockHeader = 0,
    Endorsement = 1,
}

impl From<&Denunciation> for DenunciationTypeId {
    fn from(value: &Denunciation) -> Self {
        match value {
            Denunciation::Endorsement(_) => DenunciationTypeId::Endorsement,
            Denunciation::BlockHeader(_) => DenunciationTypeId::BlockHeader,
        }
    }
}

/// Denunciation error
#[allow(missing_docs)]
#[derive(Error, Debug)]
pub enum DenunciationError {
    #[error("Invalid endorsements or block headers, cannot create denunciation: {0}")]
    InvalidInput(String),
    #[error("signature error: {0}")]
    Signature(#[from] MassaSignatureError),
    #[error("serialization error: {0}")]
    Serialization(#[from] SerializeError),
}

// Serialization / Deserialization

/// Serializer for `EndorsementDenunciation`
struct EndorsementDenunciationSerializer {
    slot_serializer: SlotSerializer,
    u32_serializer: U32VarIntSerializer,
    hash_serializer: HashSerializer,
}

impl EndorsementDenunciationSerializer {
    /// Creates a new `EndorsementDenunciationSerializer`
    const fn new() -> Self {
        Self {
            slot_serializer: SlotSerializer::new(),
            u32_serializer: U32VarIntSerializer::new(),
            hash_serializer: HashSerializer::new(),
        }
    }
}

impl Default for EndorsementDenunciationSerializer {
    fn default() -> Self {
        Self::new()
    }
}

impl Serializer<EndorsementDenunciation> for EndorsementDenunciationSerializer {
    fn serialize(
        &self,
        value: &EndorsementDenunciation,
        buffer: &mut Vec<u8>,
    ) -> Result<(), SerializeError> {
        buffer.extend(value.public_key.to_bytes());
        self.slot_serializer.serialize(&value.slot, buffer)?;
        self.u32_serializer.serialize(&value.index, buffer)?;
        self.hash_serializer.serialize(&value.hash_1, buffer)?;
        self.hash_serializer.serialize(&value.hash_2, buffer)?;
        buffer.extend(value.signature_1.to_bytes());
        buffer.extend(value.signature_2.to_bytes());
        Ok(())
    }
}

/// Deserializer for `EndorsementDenunciation`
struct EndorsementDenunciationDeserializer {
    slot_deserializer: SlotDeserializer,
    index_deserializer: U32VarIntDeserializer,
    hash_deserializer: HashDeserializer,
    pubkey_deserializer: PublicKeyDeserializer,
    signature_deserializer: SignatureDeserializer,
}

impl EndorsementDenunciationDeserializer {
    /// Creates a new `EndorsementDeserializer`
    const fn new(thread_count: u8, endorsement_count: u32) -> Self {
        EndorsementDenunciationDeserializer {
            slot_deserializer: SlotDeserializer::new(
                (Included(0), Included(u64::MAX)),
                (Included(0), Excluded(thread_count)),
            ),
            index_deserializer: U32VarIntDeserializer::new(
                Included(0),
                Excluded(endorsement_count),
            ),
            hash_deserializer: HashDeserializer::new(),
            pubkey_deserializer: PublicKeyDeserializer::new(),
            signature_deserializer: SignatureDeserializer::new(),
        }
    }
}

impl Deserializer<EndorsementDenunciation> for EndorsementDenunciationDeserializer {
    fn deserialize<'a, E: ParseError<&'a [u8]> + ContextError<&'a [u8]>>(
        &self,
        buffer: &'a [u8],
    ) -> IResult<&'a [u8], EndorsementDenunciation, E> {
        context(
            "Failed Endorsement Denunciation deserialization",
            tuple((
                context("Failed public key deserialization", |input| {
                    self.pubkey_deserializer.deserialize(input)
                }),
                context("Failed slot deserialization", |input| {
                    self.slot_deserializer.deserialize(input)
                }),
                context("Failed slot deserialization", |input| {
                    self.index_deserializer.deserialize(input)
                }),
                context("Failed hash 1 deserialization", |input| {
                    self.hash_deserializer.deserialize(input)
                }),
                context("Failed hash 2 deserialization", |input| {
                    self.hash_deserializer.deserialize(input)
                }),
                context("Failed signature 1 deserialization", |input| {
                    self.signature_deserializer.deserialize(input)
                }),
                context("Failed signature 2 deserialization", |input| {
                    self.signature_deserializer.deserialize(input)
                }),
            )),
        )
        .map(
            |(public_key, slot, index, hash_1, hash_2, signature_1, signature_2)| {
                EndorsementDenunciation {
                    public_key,
                    slot,
                    index,
                    hash_1,
                    hash_2,
                    signature_1,
                    signature_2,
                }
            },
        )
        .parse(buffer)
    }
}

/// Serializer for `BlockHeaderDenunciation`
struct BlockHeaderDenunciationSerializer {
    slot_serializer: SlotSerializer,
    hash_serializer: HashSerializer,
}

impl BlockHeaderDenunciationSerializer {
    /// Creates a new `BlockHeaderDenunciationSerializer`
    const fn new() -> Self {
        Self {
            slot_serializer: SlotSerializer::new(),
            hash_serializer: HashSerializer::new(),
        }
    }
}

impl Default for BlockHeaderDenunciationSerializer {
    fn default() -> Self {
        Self::new()
    }
}

impl Serializer<BlockHeaderDenunciation> for BlockHeaderDenunciationSerializer {
    fn serialize(
        &self,
        value: &BlockHeaderDenunciation,
        buffer: &mut Vec<u8>,
    ) -> Result<(), SerializeError> {
        buffer.extend(value.public_key.to_bytes());
        self.slot_serializer.serialize(&value.slot, buffer)?;
        self.hash_serializer.serialize(&value.hash_1, buffer)?;
        self.hash_serializer.serialize(&value.hash_2, buffer)?;
        buffer.extend(value.signature_1.to_bytes());
        buffer.extend(value.signature_2.to_bytes());
        Ok(())
    }
}

/// Deserializer for `BlockHeaderDenunciation`
struct BlockHeaderDenunciationDeserializer {
    slot_deserializer: SlotDeserializer,
    hash_deserializer: HashDeserializer,
    pubkey_deserializer: PublicKeyDeserializer,
    signature_deserializer: SignatureDeserializer,
}

impl BlockHeaderDenunciationDeserializer {
    /// Creates a new `BlockHeaderDenunciationDeserializer`
    pub const fn new(thread_count: u8) -> Self {
        Self {
            slot_deserializer: SlotDeserializer::new(
                (Included(0), Included(u64::MAX)),
                (Included(0), Excluded(thread_count)),
            ),
            hash_deserializer: HashDeserializer::new(),
            pubkey_deserializer: PublicKeyDeserializer::new(),
            signature_deserializer: SignatureDeserializer::new(),
        }
    }
}

impl Deserializer<BlockHeaderDenunciation> for BlockHeaderDenunciationDeserializer {
    fn deserialize<'a, E: ParseError<&'a [u8]> + ContextError<&'a [u8]>>(
        &self,
        buffer: &'a [u8],
    ) -> IResult<&'a [u8], BlockHeaderDenunciation, E> {
        context(
            "Failed BlockHeader Denunciation deserialization",
            tuple((
                context("Failed public key deserialization", |input| {
                    self.pubkey_deserializer.deserialize(input)
                }),
                context("Failed slot deserialization", |input| {
                    self.slot_deserializer.deserialize(input)
                }),
                context("Failed hash 1 deserialization", |input| {
                    self.hash_deserializer.deserialize(input)
                }),
                context("Failed hash 2 deserialization", |input| {
                    self.hash_deserializer.deserialize(input)
                }),
                context("Failed signature 1 deserialization", |input| {
                    self.signature_deserializer.deserialize(input)
                }),
                context("Failed signature 2 deserialization", |input| {
                    self.signature_deserializer.deserialize(input)
                }),
            )),
        )
        .map(
            |(public_key, slot, hash_1, hash_2, signature_1, signature_2)| {
                BlockHeaderDenunciation {
                    public_key,
                    slot,
                    hash_1,
                    hash_2,
                    signature_1,
                    signature_2,
                }
            },
        )
        .parse(buffer)
    }
}

/// Serializer for `Denunciation`
pub struct DenunciationSerializer {
    endo_de_serializer: EndorsementDenunciationSerializer,
    blkh_de_serializer: BlockHeaderDenunciationSerializer,
    type_id_serializer: U32VarIntSerializer,
}

impl DenunciationSerializer {
    /// Creates a new `BlockHeaderDenunciationSerializer`
    pub const fn new() -> Self {
        Self {
            endo_de_serializer: EndorsementDenunciationSerializer::new(),
            blkh_de_serializer: BlockHeaderDenunciationSerializer::new(),
            type_id_serializer: U32VarIntSerializer::new(),
        }
    }
}

impl Default for DenunciationSerializer {
    fn default() -> Self {
        Self::new()
    }
}

impl Serializer<Denunciation> for DenunciationSerializer {
    fn serialize(&self, value: &Denunciation, buffer: &mut Vec<u8>) -> Result<(), SerializeError> {
        let de_type_id = DenunciationTypeId::from(value);
        self.type_id_serializer
            .serialize(&u32::from(de_type_id), buffer)?;
        match value {
            Denunciation::Endorsement(de) => {
                self.endo_de_serializer.serialize(de, buffer)?;
            }
            Denunciation::BlockHeader(de) => {
                self.blkh_de_serializer.serialize(de, buffer)?;
            }
        }
        Ok(())
    }
}

/// Deserializer for `Denunciation`
pub struct DenunciationDeserializer {
    endo_de_deserializer: EndorsementDenunciationDeserializer,
    blkh_de_deserializer: BlockHeaderDenunciationDeserializer,
    type_id_deserializer: U32VarIntDeserializer,
}

impl DenunciationDeserializer {
    /// Creates a new `DenunciationDeserializer`
    pub const fn new(thread_count: u8, endorsement_count: u32) -> Self {
        Self {
            endo_de_deserializer: EndorsementDenunciationDeserializer::new(
                thread_count,
                endorsement_count,
            ),
            blkh_de_deserializer: BlockHeaderDenunciationDeserializer::new(thread_count),
            type_id_deserializer: U32VarIntDeserializer::new(
                Included(0),
                Excluded(DenunciationTypeId::VARIANT_COUNT as u32),
            ),
        }
    }
}

impl Deserializer<Denunciation> for DenunciationDeserializer {
    fn deserialize<'a, E: ParseError<&'a [u8]> + ContextError<&'a [u8]>>(
        &self,
        buffer: &'a [u8],
    ) -> IResult<&'a [u8], Denunciation, E> {
        let (rem, de_type_id_) = context("Failed Denunciation type id deserialization", |input| {
            self.type_id_deserializer.deserialize(input)
        })
        .parse(buffer)?;

        let de_type_id = DenunciationTypeId::try_from(de_type_id_).map_err(|_| {
            nom::Err::Error(ParseError::from_error_kind(
                buffer,
                nom::error::ErrorKind::Fail,
            ))
        })?;

        match de_type_id {
            DenunciationTypeId::Endorsement => {
                let (rem2, endo_de) = self.endo_de_deserializer.deserialize(rem)?;
                IResult::Ok((rem2, Denunciation::Endorsement(endo_de)))
            }
            DenunciationTypeId::BlockHeader => {
                let (rem2, blkh_de) = self.blkh_de_deserializer.deserialize(rem)?;
                IResult::Ok((rem2, Denunciation::BlockHeader(blkh_de)))
            }
        }
    }
}

// End Ser / Der

// Denunciation Index

#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)]
/// Index for Denunciations in collections (e.g. like a HashMap...)
pub enum DenunciationIndex {
    /// Variant for Block header denunciation index
    BlockHeader {
        /// de slot
        slot: Slot,
    },
    /// Variant for Endorsement denunciation index
    Endorsement {
        /// de slot
        slot: Slot,
        /// de index
        index: u32,
    },
}

impl DenunciationIndex {
    /// Get field: slot
    pub fn get_slot(&self) -> &Slot {
        match self {
            DenunciationIndex::BlockHeader { slot } => slot,
            DenunciationIndex::Endorsement { slot, .. } => slot,
        }
    }

    /// Get field: index (return None for a block header denunciation index)
    pub fn get_index(&self) -> Option<&u32> {
        match self {
            DenunciationIndex::BlockHeader { .. } => None,
            DenunciationIndex::Endorsement { slot: _, index } => Some(index),
        }
    }

    /// Compute the hash
    pub fn get_hash(&self) -> Hash {
        let mut buffer = u32::from(DenunciationIndexTypeId::from(self))
            .to_le_bytes()
            .to_vec();
        match self {
            DenunciationIndex::BlockHeader { slot } => buffer.extend(slot.to_bytes_key()),
            DenunciationIndex::Endorsement { slot, index } => {
                buffer.extend(slot.to_bytes_key());
                buffer.extend(index.to_le_bytes());
            }
        }
        Hash::compute_from(&buffer)
    }
}

/// Create a `DenunciationIndex` from a `Denunciation`
impl From<&Denunciation> for DenunciationIndex {
    fn from(value: &Denunciation) -> Self {
        match value {
            Denunciation::Endorsement(endo_de) => DenunciationIndex::Endorsement {
                slot: endo_de.slot,
                index: endo_de.index,
            },
            Denunciation::BlockHeader(blkh_de) => {
                DenunciationIndex::BlockHeader { slot: blkh_de.slot }
            }
        }
    }
}

/// Create a `DenunciationIndex` from a `DenunciationPrecursor`
impl From<&DenunciationPrecursor> for DenunciationIndex {
    fn from(value: &DenunciationPrecursor) -> Self {
        match value {
            DenunciationPrecursor::Endorsement(de_p) => DenunciationIndex::Endorsement {
                slot: de_p.slot,
                index: de_p.index,
            },
            DenunciationPrecursor::BlockHeader(de_p) => {
                DenunciationIndex::BlockHeader { slot: de_p.slot }
            }
        }
    }
}

impl Ord for DenunciationIndex {
    fn cmp(&self, other: &Self) -> Ordering {
        // key ends with type id so that we avoid prioritizing one type over the other
        // when filling block headers (comparison of tuples is from left to right).
        let self_key = (
            self.get_slot(),
            self.get_index().unwrap_or(&0),
            u32::from(DenunciationIndexTypeId::from(self)),
        );
        let other_key = (
            other.get_slot(),
            other.get_index().unwrap_or(&0),
            u32::from(DenunciationIndexTypeId::from(other)),
        );
        self_key.cmp(&other_key)
    }
}

impl PartialOrd for DenunciationIndex {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

// End Denunciation Index

// Denunciation Index ser der

#[derive(IntoPrimitive, Debug, Eq, PartialEq, TryFromPrimitive)]
#[repr(u32)]
enum DenunciationIndexTypeId {
    BlockHeader = 0,
    Endorsement = 1,
}

impl From<&DenunciationIndex> for DenunciationIndexTypeId {
    fn from(value: &DenunciationIndex) -> Self {
        match value {
            DenunciationIndex::BlockHeader { .. } => DenunciationIndexTypeId::BlockHeader,
            DenunciationIndex::Endorsement { .. } => DenunciationIndexTypeId::Endorsement,
        }
    }
}

#[derive(Clone)]
/// Serializer for `DenunciationIndex`
pub struct DenunciationIndexSerializer {
    u32_serializer: U32VarIntSerializer,
    slot_serializer: SlotSerializer,
    index_serializer: U32VarIntSerializer,
}

impl DenunciationIndexSerializer {
    /// Creates a new `DenunciationIndexSerializer`
    pub const fn new() -> Self {
        Self {
            u32_serializer: U32VarIntSerializer::new(),
            slot_serializer: SlotSerializer::new(),
            index_serializer: U32VarIntSerializer::new(),
        }
    }
}

impl Default for DenunciationIndexSerializer {
    fn default() -> Self {
        Self::new()
    }
}

impl Serializer<DenunciationIndex> for DenunciationIndexSerializer {
    fn serialize(
        &self,
        value: &DenunciationIndex,
        buffer: &mut Vec<u8>,
    ) -> Result<(), SerializeError> {
        match value {
            DenunciationIndex::BlockHeader { slot } => {
                self.u32_serializer
                    .serialize(&u32::from(DenunciationIndexTypeId::BlockHeader), buffer)?;
                self.slot_serializer.serialize(slot, buffer)?;
            }
            DenunciationIndex::Endorsement { slot, index } => {
                self.u32_serializer
                    .serialize(&u32::from(DenunciationIndexTypeId::Endorsement), buffer)?;
                self.slot_serializer.serialize(slot, buffer)?;
                self.index_serializer.serialize(index, buffer)?;
            }
        }
        Ok(())
    }
}

#[derive(Clone)]
/// Deserializer for `DenunciationIndex`
pub struct DenunciationIndexDeserializer {
    id_deserializer: U32VarIntDeserializer,
    slot_deserializer: SlotDeserializer,
    index_deserializer: U32VarIntDeserializer,
}

impl DenunciationIndexDeserializer {
    /// Creates a new `DenunciationIndexDeserializer`
    pub const fn new(thread_count: u8, endorsement_count: u32) -> Self {
        Self {
            id_deserializer: U32VarIntDeserializer::new(Included(0), Included(u32::MAX)),
            slot_deserializer: SlotDeserializer::new(
                (Included(0), Included(u64::MAX)),
                (Included(0), Excluded(thread_count)),
            ),
            index_deserializer: U32VarIntDeserializer::new(
                Included(0),
                Included(endorsement_count),
            ),
        }
    }
}

impl Deserializer<DenunciationIndex> for DenunciationIndexDeserializer {
    fn deserialize<'a, E: ParseError<&'a [u8]> + ContextError<&'a [u8]>>(
        &self,
        buffer: &'a [u8],
    ) -> IResult<&'a [u8], DenunciationIndex, E> {
        let (input, id) = self.id_deserializer.deserialize(buffer)?;
        let id = DenunciationIndexTypeId::try_from(id).map_err(|_| {
            nom::Err::Error(ParseError::from_error_kind(
                buffer,
                nom::error::ErrorKind::Eof,
            ))
        })?;

        match id {
            DenunciationIndexTypeId::BlockHeader => {
                context("Failed slot deserialization", |input| {
                    self.slot_deserializer.deserialize(input)
                })
                .map(|slot| DenunciationIndex::BlockHeader { slot })
                // .parse(&buffer[1..])
                .parse(input)
            }
            DenunciationIndexTypeId::Endorsement => context(
                "Failed Endorsement denunciation index",
                tuple((
                    context("Failed slot deserialization", |input| {
                        self.slot_deserializer.deserialize(input)
                    }),
                    context("Failed index deserialization", |input| {
                        self.index_deserializer.deserialize(input)
                    }),
                )),
            )
            .map(|(slot, index)| DenunciationIndex::Endorsement { slot, index })
            .parse(input),
        }
    }
}

// End Denunciation Index ser der

// Denunciation interest

/// DenunciationPrecursor variant for endorsement
#[derive(Debug, Clone, PartialEq)]
pub struct EndorsementDenunciationPrecursor {
    /// secure share endorsement public key
    pub public_key: PublicKey,
    /// endorsement slot
    pub slot: Slot,
    /// endorsement index
    pub index: u32,
    /// secured header partial hash
    hash: Hash,
    /// secured header signature
    signature: Signature,
}

/// DenunciationPrecursor variant for block header
#[derive(Debug, Clone, PartialEq)]
pub struct BlockHeaderDenunciationPrecursor {
    /// secured header public key
    pub public_key: PublicKey,
    /// block header slot
    pub slot: Slot,
    /// secured header partial hash
    hash: Hash,
    /// secured header signature
    signature: Signature,
}

/// Lightweight data for Denunciation creation
/// (avoid storing heavyweight secured header or secure share endorsement, see denunciation pool)
#[derive(Debug, Clone, PartialEq)]
pub enum DenunciationPrecursor {
    /// Endorsement variant
    Endorsement(EndorsementDenunciationPrecursor),
    /// Block header variant
    BlockHeader(BlockHeaderDenunciationPrecursor),
}

impl DenunciationPrecursor {
    /// Get field: slot
    pub fn get_slot(&self) -> &Slot {
        match self {
            DenunciationPrecursor::Endorsement(endo_de_p) => &endo_de_p.slot,
            DenunciationPrecursor::BlockHeader(blkh_de_p) => &blkh_de_p.slot,
        }
    }

    /// Get field: pub key
    pub fn get_public_key(&self) -> &PublicKey {
        match self {
            DenunciationPrecursor::Endorsement(endo_de_p) => &endo_de_p.public_key,
            DenunciationPrecursor::BlockHeader(blkh_de_p) => &blkh_de_p.public_key,
        }
    }
}

impl From<&SecureShareEndorsement> for DenunciationPrecursor {
    fn from(value: &SecureShareEndorsement) -> Self {
        DenunciationPrecursor::Endorsement(EndorsementDenunciationPrecursor {
            public_key: value.content_creator_pub_key,
            slot: value.content.slot,
            index: value.content.index,
            hash: *value.id.get_hash(),
            signature: value.signature,
        })
    }
}

impl From<&SecuredHeader> for DenunciationPrecursor {
    fn from(value: &SecuredHeader) -> Self {
        DenunciationPrecursor::BlockHeader(BlockHeaderDenunciationPrecursor {
            public_key: value.content_creator_pub_key,
            slot: value.content.slot,
            hash: *value.id.get_hash(),
            signature: value.signature,
        })
    }
}

/// Create a new Denunciation from 2 SecureHeader
impl TryFrom<(&DenunciationPrecursor, &DenunciationPrecursor)> for Denunciation {
    type Error = DenunciationError;

    fn try_from(
        (de_p_1, de_p_2): (&DenunciationPrecursor, &DenunciationPrecursor),
    ) -> Result<Self, Self::Error> {
        match (de_p_1, de_p_2) {
            (
                DenunciationPrecursor::BlockHeader(de_p_blkh_1),
                DenunciationPrecursor::BlockHeader(de_p_blkh_2),
            ) => {
                // Cannot use the same block header (here: block header denunciation precursor) twice
                if de_p_blkh_1.slot != de_p_blkh_2.slot
                    || de_p_blkh_1.public_key != de_p_blkh_2.public_key
                    || de_p_blkh_1.hash == de_p_blkh_2.hash
                {
                    return Err(DenunciationError::InvalidInput(
                        format!("Not the same slot or public key or same hash for de precursor: {:?} & {:?}", de_p_blkh_1, de_p_blkh_2)
                    ));
                }

                // Check sig
                let de_p_blkh_1_hash = BlockHeaderDenunciation::compute_hash_for_sig_verif(
                    &de_p_blkh_1.public_key,
                    &de_p_blkh_1.slot,
                    &de_p_blkh_1.hash,
                );
                let de_p_blkh_2_hash = BlockHeaderDenunciation::compute_hash_for_sig_verif(
                    &de_p_blkh_2.public_key,
                    &de_p_blkh_2.slot,
                    &de_p_blkh_2.hash,
                );

                de_p_blkh_1
                    .public_key
                    .verify_signature(&de_p_blkh_1_hash, &de_p_blkh_1.signature)?;
                de_p_blkh_1
                    .public_key
                    .verify_signature(&de_p_blkh_2_hash, &de_p_blkh_2.signature)?;

                Ok(Denunciation::BlockHeader(BlockHeaderDenunciation {
                    public_key: de_p_blkh_1.public_key,
                    slot: de_p_blkh_1.slot,
                    signature_1: de_p_blkh_1.signature,
                    signature_2: de_p_blkh_2.signature,
                    hash_1: de_p_blkh_1.hash,
                    hash_2: de_p_blkh_2.hash,
                }))
            }
            (
                DenunciationPrecursor::Endorsement(de_p_endo_1),
                DenunciationPrecursor::Endorsement(de_p_endo_2),
            ) => {
                // Cannot use the same endorsement (here: endorsement denunciation) twice
                if de_p_endo_1.slot != de_p_endo_2.slot
                    || de_p_endo_1.index != de_p_endo_2.index
                    || de_p_endo_1.public_key != de_p_endo_2.public_key
                    || de_p_endo_1.hash == de_p_endo_2.hash
                {
                    return Err(DenunciationError::InvalidInput(
                        format!("Not the same slot, index or public key or same hash for de precursor: {:?} & {:?}", de_p_endo_1, de_p_endo_2)
                    ));
                }

                // Check sig
                let de_p_endo_1_hash = EndorsementDenunciation::compute_hash_for_sig_verif(
                    &de_p_endo_1.public_key,
                    &de_p_endo_1.slot,
                    &de_p_endo_1.index,
                    &de_p_endo_1.hash,
                );
                let de_p_endo_2_hash = EndorsementDenunciation::compute_hash_for_sig_verif(
                    &de_p_endo_2.public_key,
                    &de_p_endo_2.slot,
                    &de_p_endo_2.index,
                    &de_p_endo_2.hash,
                );

                de_p_endo_1
                    .public_key
                    .verify_signature(&de_p_endo_1_hash, &de_p_endo_1.signature)?;
                de_p_endo_1
                    .public_key
                    .verify_signature(&de_p_endo_2_hash, &de_p_endo_2.signature)?;

                Ok(Denunciation::Endorsement(EndorsementDenunciation {
                    public_key: de_p_endo_1.public_key,
                    slot: de_p_endo_1.slot,
                    index: de_p_endo_1.index,
                    signature_1: de_p_endo_1.signature,
                    signature_2: de_p_endo_2.signature,
                    hash_1: de_p_endo_1.hash,
                    hash_2: de_p_endo_2.hash,
                }))
            }
            _ => {
                // Different enum variants - this is invalid
                Err(DenunciationError::InvalidInput(
                    "Mixed endorsement and block header denunciation precursors".to_string(),
                ))
            }
        }
    }
}

// End Denunciation interest

// test-exports

#[cfg(any(test, feature = "test-exports"))]
impl Denunciation {
    /// Used under testing conditions to validate an instance of Self
    pub fn check_invariants(&self) -> Result<(), Box<dyn std::error::Error>> {
        if !self.is_valid() {
            return Err(format!("Denunciation is invalid: {:?}", self).into());
        }
        Ok(())
    }
}

// end test-exports

#[cfg(test)]
mod tests {
    use super::*;

    use massa_serialization::DeserializeError;
    use massa_signature::KeyPair;

    use crate::block_id::BlockId;
    use crate::config::{CHAINID, ENDORSEMENT_COUNT, THREAD_COUNT};
    use crate::endorsement::{Endorsement, EndorsementSerializer, SecureShareEndorsement};
    use crate::secure_share::{Id, SecureShareContent};

    use crate::test_exports::{
        gen_block_headers_for_denunciation, gen_endorsements_for_denunciation,
    };

    #[test]
    fn test_endorsement_denunciation() {
        // Create an endorsement denunciation and check if it is valid
        let (_slot, _keypair, s_endorsement_1, s_endorsement_2, _s_endorsement_3) =
            gen_endorsements_for_denunciation(None, None);
        let denunciation: Denunciation = (&s_endorsement_1, &s_endorsement_2).try_into().unwrap();

        assert!(denunciation.is_for_endorsement());
        assert!(denunciation.is_valid());
    }

    #[test]
    fn test_endorsement_denunciation_invalid_1() {
        let (slot, keypair, s_endorsement_1, _s_endorsement_2, _s_endorsement_3) =
            gen_endorsements_for_denunciation(None, None);

        // Try to create a denunciation from 2 endorsements @ != index
        let endorsement_4 = Endorsement {
            slot,
            index: 9,
            endorsed_block: BlockId::generate_from_hash(Hash::compute_from("foo".as_bytes())),
        };
        let s_endorsement_4 = Endorsement::new_verifiable(
            endorsement_4,
            EndorsementSerializer::new(),
            &keypair,
            *CHAINID,
        )
        .unwrap();

        let denunciation = Denunciation::try_from((&s_endorsement_1, &s_endorsement_4));

        assert!(matches!(
            denunciation,
            Err(DenunciationError::InvalidInput(..))
        ));

        // Try to create a denunciation from only 1 endorsement
        let denunciation = Denunciation::try_from((&s_endorsement_1, &s_endorsement_1));

        assert!(matches!(
            denunciation,
            Err(DenunciationError::InvalidInput(..))
        ));
    }

    #[test]
    fn test_endorsement_denunciation_is_for() {
        let (slot, keypair, s_endorsement_1, s_endorsement_2, s_endorsement_3) =
            gen_endorsements_for_denunciation(None, None);

        let denunciation: Denunciation = (&s_endorsement_1, &s_endorsement_2).try_into().unwrap();

        assert!(denunciation.is_for_endorsement());
        assert!(denunciation.is_valid());

        // Try to create a denunciation from 2 endorsements @ != index
        let endorsement_4 = Endorsement {
            slot,
            index: 9,
            endorsed_block: BlockId::generate_from_hash(Hash::compute_from("foo".as_bytes())),
        };
        let s_endorsement_4 = Endorsement::new_verifiable(
            endorsement_4,
            EndorsementSerializer::new(),
            &keypair,
            *CHAINID,
        )
        .unwrap();

        assert!(!denunciation
            .is_also_for_endorsement(&s_endorsement_4)
            .unwrap());
        assert!(denunciation
            .is_also_for_endorsement(&s_endorsement_3)
            .unwrap());
        assert!(denunciation.is_valid());
    }

    #[test]
    fn test_block_header_denunciation() {
        // Create an block header denunciation and check if it is valid
        let (_slot, _keypair, s_block_header_1, s_block_header_2, s_block_header_3) =
            gen_block_headers_for_denunciation(None, None);
        let denunciation: Denunciation = (&s_block_header_1, &s_block_header_2).try_into().unwrap();

        assert!(denunciation.is_for_block_header());
        assert!(denunciation.is_valid());
        assert!(denunciation
            .is_also_for_block_header(&s_block_header_3)
            .unwrap());
    }

    #[test]
    fn test_forge_invalid_denunciation() {
        let keypair = KeyPair::generate(0).unwrap();
        let slot_1 = Slot::new(4, 2);
        let slot_2 = Slot::new(3, 7);

        let endorsement_1 = Endorsement {
            slot: slot_1,
            index: 0,
            endorsed_block: BlockId::generate_from_hash(Hash::compute_from("blk1".as_bytes())),
        };

        let s_endorsement_1: SecureShareEndorsement = Endorsement::new_verifiable(
            endorsement_1,
            EndorsementSerializer::new(),
            &keypair,
            *CHAINID,
        )
        .unwrap();

        let endorsement_2 = Endorsement {
            slot: slot_2,
            index: 0,
            endorsed_block: BlockId::generate_from_hash(Hash::compute_from("blk2".as_bytes())),
        };

        let s_endorsement_2: SecureShareEndorsement = Endorsement::new_verifiable(
            endorsement_2,
            EndorsementSerializer::new(),
            &keypair,
            *CHAINID,
        )
        .unwrap();

        // from an attacker - building manually a Denunciation object
        let de_forged_1 = Denunciation::Endorsement(EndorsementDenunciation {
            public_key: keypair.get_public_key(),
            slot: slot_1,
            index: 0,
            hash_1: *s_endorsement_1.id.get_hash(), // use only data from s_endorsement_1
            hash_2: *s_endorsement_1.id.get_hash(),
            signature_1: s_endorsement_1.signature,
            signature_2: s_endorsement_1.signature,
        });

        // hash_1 == hash_2 -> this is invalid
        assert!(!de_forged_1.is_valid());

        // from an attacker - building manually a Denunciation object
        let de_forged_2 = Denunciation::Endorsement(EndorsementDenunciation {
            public_key: keypair.get_public_key(),
            slot: slot_2,
            index: 0,
            hash_1: *s_endorsement_1.id.get_hash(),
            hash_2: *s_endorsement_2.id.get_hash(),
            signature_1: s_endorsement_1.signature,
            signature_2: s_endorsement_2.signature,
        });

        // An attacker uses an old s_endorsement_1 to forge a Denunciation object @ slot_2
        // This has to be detected if Denunciation are send via the network
        assert!(!de_forged_2.is_valid());
    }

    // SER / DER
    #[test]
    fn test_endorsement_denunciation_ser_der() {
        let (_, _, s_endorsement_1, s_endorsement_2, _) =
            gen_endorsements_for_denunciation(None, None);

        let denunciation = Denunciation::try_from((&s_endorsement_1, &s_endorsement_2)).unwrap();

        let mut buffer = Vec::new();
        let de_ser = EndorsementDenunciationSerializer::new();

        match denunciation {
            Denunciation::Endorsement(de) => {
                de_ser.serialize(&de, &mut buffer).unwrap();
                let de_der =
                    EndorsementDenunciationDeserializer::new(THREAD_COUNT, ENDORSEMENT_COUNT);

                let (rem, de_der_res) = de_der.deserialize::<DeserializeError>(&buffer).unwrap();

                assert!(rem.is_empty());
                assert_eq!(de, de_der_res);
            }
            Denunciation::BlockHeader(_) => {
                unimplemented!()
            }
        }
    }

    #[test]
    fn test_block_header_denunciation_ser_der() {
        let (_, _, s_block_header_1, s_block_header_2, _) =
            gen_block_headers_for_denunciation(None, None);
        let denunciation: Denunciation = (&s_block_header_1, &s_block_header_2).try_into().unwrap();

        let mut buffer = Vec::new();
        let de_ser = BlockHeaderDenunciationSerializer::new();

        match denunciation {
            Denunciation::Endorsement(_) => {
                unimplemented!()
            }
            Denunciation::BlockHeader(de) => {
                de_ser.serialize(&de, &mut buffer).unwrap();
                let de_der = BlockHeaderDenunciationDeserializer::new(THREAD_COUNT);

                let (rem, de_der_res) = de_der.deserialize::<DeserializeError>(&buffer).unwrap();

                assert!(rem.is_empty());
                assert_eq!(de, de_der_res);
            }
        }
    }

    #[test]
    fn test_denunciation_ser_der() {
        let (_, _, s_block_header_1, s_block_header_2, _) =
            gen_block_headers_for_denunciation(None, None);
        let denunciation: Denunciation = (&s_block_header_1, &s_block_header_2).try_into().unwrap();

        let mut buffer = Vec::new();
        let de_ser = DenunciationSerializer::new();

        de_ser.serialize(&denunciation, &mut buffer).unwrap();
        let de_der = DenunciationDeserializer::new(THREAD_COUNT, ENDORSEMENT_COUNT);

        let (rem, de_der_res) = de_der.deserialize::<DeserializeError>(&buffer).unwrap();

        assert!(rem.is_empty());
        assert_eq!(denunciation, de_der_res);

        let (_, _, s_endorsement_1, s_endorsement_2, _) =
            gen_endorsements_for_denunciation(None, None);
        let denunciation = Denunciation::try_from((&s_endorsement_1, &s_endorsement_2)).unwrap();
        buffer.clear();

        de_ser.serialize(&denunciation, &mut buffer).unwrap();
        let (rem, de_der_res) = de_der.deserialize::<DeserializeError>(&buffer).unwrap();
        assert!(rem.is_empty());
        assert_eq!(denunciation, de_der_res);
    }

    #[test]
    fn test_denunciation_precursor() {
        let (_, _, s_block_header_1, s_block_header_2, _) =
            gen_block_headers_for_denunciation(None, None);
        let denunciation: Denunciation = (&s_block_header_1, &s_block_header_2).try_into().unwrap();

        let de_p_1 = DenunciationPrecursor::from(&s_block_header_1);
        let de_p_2 = DenunciationPrecursor::from(&s_block_header_2);
        let denunciation_2: Denunciation = (&de_p_1, &de_p_2).try_into().unwrap();

        assert_eq!(denunciation, denunciation_2);

        let (_, _, s_endorsement_1, s_endorsement_2, _) =
            gen_endorsements_for_denunciation(None, None);
        let denunciation_3 = Denunciation::try_from((&s_endorsement_1, &s_endorsement_2)).unwrap();

        let de_p_3 = DenunciationPrecursor::from(&s_endorsement_1);
        let de_p_4 = DenunciationPrecursor::from(&s_endorsement_2);
        let denunciation_4: Denunciation = (&de_p_3, &de_p_4).try_into().unwrap();

        assert_eq!(denunciation_3, denunciation_4);
    }

    #[test]
    fn test_denunciation_index_ser_der() {
        let (_, _, s_block_header_1, s_block_header_2, _) =
            gen_block_headers_for_denunciation(None, None);
        let denunciation_1: Denunciation =
            (&s_block_header_1, &s_block_header_2).try_into().unwrap();
        let denunciation_index_1 = DenunciationIndex::from(&denunciation_1);

        let (_, _, s_endorsement_1, s_endorsement_2, _) =
            gen_endorsements_for_denunciation(None, None);
        let denunciation_2 = Denunciation::try_from((&s_endorsement_1, &s_endorsement_2)).unwrap();
        let denunciation_index_2 = DenunciationIndex::from(&denunciation_2);

        let mut buffer = Vec::new();
        let de_idx_ser = DenunciationIndexSerializer::new();
        de_idx_ser
            .serialize(&denunciation_index_1, &mut buffer)
            .unwrap();
        let de_idx_der = DenunciationIndexDeserializer::new(THREAD_COUNT, ENDORSEMENT_COUNT);
        let (rem, de_idx_der_res) = de_idx_der.deserialize::<DeserializeError>(&buffer).unwrap();

        assert!(rem.is_empty());
        assert_eq!(denunciation_index_1, de_idx_der_res);

        let mut buffer = Vec::new();
        let de_idx_ser = DenunciationIndexSerializer::new();
        de_idx_ser
            .serialize(&denunciation_index_2, &mut buffer)
            .unwrap();
        let de_idx_der = DenunciationIndexDeserializer::new(THREAD_COUNT, ENDORSEMENT_COUNT);
        let (rem, de_idx_der_res) = de_idx_der.deserialize::<DeserializeError>(&buffer).unwrap();

        assert!(rem.is_empty());
        assert_eq!(denunciation_index_2, de_idx_der_res);
    }
}