1#![allow(missing_docs)]
43
44use std::cmp::Ordering;
45use std::ops::Bound::{Excluded, Included};
46
47use nom::{
48 error::{context, ContextError, ParseError},
49 sequence::tuple,
50 IResult, Parser,
51};
52use num_enum::{IntoPrimitive, TryFromPrimitive};
53use serde::{Deserialize, Serialize};
54use thiserror::Error;
55
56use crate::block_header::{BlockHeaderDenunciationData, SecuredHeader};
57use crate::endorsement::{EndorsementDenunciationData, SecureShareEndorsement};
58use crate::slot::{Slot, SlotDeserializer, SlotSerializer};
59
60use crate::secure_share::Id;
61use massa_hash::{Hash, HashDeserializer, HashSerializer};
62use massa_serialization::{
63 Deserializer, SerializeError, Serializer, U32VarIntDeserializer, U32VarIntSerializer,
64};
65use massa_signature::{
66 MassaSignatureError, PublicKey, PublicKeyDeserializer, Signature, SignatureDeserializer,
67};
68use variant_count::VariantCount;
69
70#[allow(dead_code)]
72#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
73pub struct EndorsementDenunciation {
74 public_key: PublicKey,
75 slot: Slot,
76 index: u32,
77 hash_1: Hash,
78 hash_2: Hash,
79 signature_1: Signature,
80 signature_2: Signature,
81}
82
83impl EndorsementDenunciation {
84 fn compute_hash_for_sig_verif(
88 public_key: &PublicKey,
89 slot: &Slot,
90 index: &u32,
91 content_hash: &Hash,
92 chain_id: u64,
93 ) -> Hash {
94 let mut hash_data = Vec::new();
95 hash_data.extend(public_key.to_bytes());
97 let denunciation_data = EndorsementDenunciationData::new(*slot, *index, chain_id);
99 hash_data.extend(&denunciation_data.to_bytes());
100 hash_data.extend(content_hash.to_bytes());
102 Hash::compute_from(&hash_data)
103 }
104
105 pub fn get_public_key(&self) -> &PublicKey {
107 &self.public_key
108 }
109 pub fn get_slot(&self) -> &Slot {
110 &self.slot
111 }
112 pub fn get_index(&self) -> &u32 {
113 &self.index
114 }
115 pub fn get_hash_1(&self) -> &Hash {
116 &self.hash_1
117 }
118 pub fn get_hash_2(&self) -> &Hash {
119 &self.hash_2
120 }
121 pub fn get_signature_1(&self) -> &Signature {
122 &self.signature_1
123 }
124 pub fn get_signature_2(&self) -> &Signature {
125 &self.signature_2
126 }
127}
128
129#[allow(dead_code)]
131#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
132pub struct BlockHeaderDenunciation {
133 public_key: PublicKey,
134 slot: Slot,
135 hash_1: Hash,
136 hash_2: Hash,
137 signature_1: Signature,
138 signature_2: Signature,
139}
140
141impl BlockHeaderDenunciation {
142 fn compute_hash_for_sig_verif(
146 public_key: &PublicKey,
147 slot: &Slot,
148 content_hash: &Hash,
149 chain_id: u64,
150 ) -> Hash {
151 let mut hash_data = Vec::new();
152 hash_data.extend(public_key.to_bytes());
154 let de_data = BlockHeaderDenunciationData::new(*slot, chain_id);
156 hash_data.extend(de_data.to_bytes());
157 hash_data.extend(content_hash.to_bytes());
159 Hash::compute_from(&hash_data)
160 }
161
162 pub fn get_public_key(&self) -> &PublicKey {
164 &self.public_key
165 }
166 pub fn get_slot(&self) -> &Slot {
167 &self.slot
168 }
169 pub fn get_hash_1(&self) -> &Hash {
170 &self.hash_1
171 }
172 pub fn get_hash_2(&self) -> &Hash {
173 &self.hash_2
174 }
175 pub fn get_signature_1(&self) -> &Signature {
176 &self.signature_1
177 }
178 pub fn get_signature_2(&self) -> &Signature {
179 &self.signature_2
180 }
181}
182
183#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
185#[allow(missing_docs)]
186pub enum Denunciation {
187 Endorsement(EndorsementDenunciation),
188 BlockHeader(BlockHeaderDenunciation),
189}
190
191#[allow(dead_code)]
192impl Denunciation {
193 pub fn is_for_endorsement(&self) -> bool {
195 matches!(self, Denunciation::Endorsement(_))
196 }
197
198 pub fn is_for_block_header(&self) -> bool {
200 matches!(self, Denunciation::BlockHeader(_))
201 }
202
203 pub fn is_also_for_endorsement(
207 &self,
208 s_endorsement: &SecureShareEndorsement,
209 chain_id: u64,
210 ) -> Result<bool, DenunciationError> {
211 match self {
212 Denunciation::BlockHeader(_) => Ok(false),
213 Denunciation::Endorsement(endo_de) => {
214 let content_hash = s_endorsement.id.get_hash();
215
216 let hash = EndorsementDenunciation::compute_hash_for_sig_verif(
217 &endo_de.public_key,
218 &endo_de.slot,
219 &endo_de.index,
220 content_hash,
221 chain_id,
222 );
223
224 Ok(endo_de.slot == s_endorsement.content.slot
225 && endo_de.index == s_endorsement.content.index
226 && endo_de.public_key == s_endorsement.content_creator_pub_key
227 && endo_de.hash_1 != *content_hash
228 && endo_de.hash_2 != *content_hash
229 && endo_de
230 .public_key
231 .verify_signature(&hash, &s_endorsement.signature)
232 .is_ok())
233 }
234 }
235 }
236
237 pub fn is_also_for_block_header(
241 &self,
242 s_block_header: &SecuredHeader,
243 chain_id: u64,
244 ) -> Result<bool, DenunciationError> {
245 match self {
246 Denunciation::Endorsement(_) => Ok(false),
247 Denunciation::BlockHeader(endo_bh) => {
248 let content_hash = s_block_header.id.get_hash();
249
250 let hash = BlockHeaderDenunciation::compute_hash_for_sig_verif(
251 &endo_bh.public_key,
252 &endo_bh.slot,
253 content_hash,
254 chain_id,
255 );
256
257 Ok(endo_bh.slot == s_block_header.content.slot
258 && endo_bh.public_key == s_block_header.content_creator_pub_key
259 && endo_bh.hash_1 != *content_hash
260 && endo_bh.hash_2 != *content_hash
261 && endo_bh
262 .public_key
263 .verify_signature(&hash, &s_block_header.signature)
264 .is_ok())
265 }
266 }
267 }
268
269 pub fn is_valid_with_chain(&self, chain_id: u64) -> bool {
275 let (signature_1, signature_2, hash_1, hash_2, public_key) = match self {
276 Denunciation::Endorsement(de) => {
277 let hash_1 = EndorsementDenunciation::compute_hash_for_sig_verif(
278 &de.public_key,
279 &de.slot,
280 &de.index,
281 &de.hash_1,
282 chain_id,
283 );
284 let hash_2 = EndorsementDenunciation::compute_hash_for_sig_verif(
285 &de.public_key,
286 &de.slot,
287 &de.index,
288 &de.hash_2,
289 chain_id,
290 );
291
292 (
293 de.signature_1,
294 de.signature_2,
295 hash_1,
296 hash_2,
297 de.public_key,
298 )
299 }
300 Denunciation::BlockHeader(de) => {
301 let hash_1 = BlockHeaderDenunciation::compute_hash_for_sig_verif(
302 &de.public_key,
303 &de.slot,
304 &de.hash_1,
305 chain_id,
306 );
307 let hash_2 = BlockHeaderDenunciation::compute_hash_for_sig_verif(
308 &de.public_key,
309 &de.slot,
310 &de.hash_2,
311 chain_id,
312 );
313
314 (
315 de.signature_1,
316 de.signature_2,
317 hash_1,
318 hash_2,
319 de.public_key,
320 )
321 }
322 };
323
324 hash_1 != hash_2
325 && public_key.verify_signature(&hash_1, &signature_1).is_ok()
326 && public_key.verify_signature(&hash_2, &signature_2).is_ok()
327 }
328
329 pub fn get_slot(&self) -> &Slot {
331 match self {
332 Denunciation::Endorsement(de) => &de.slot,
333 Denunciation::BlockHeader(de) => &de.slot,
334 }
335 }
336
337 pub fn get_index(&self) -> Option<&u32> {
339 match self {
340 Denunciation::BlockHeader(_) => None,
341 Denunciation::Endorsement(de) => Some(&de.index),
342 }
343 }
344
345 pub fn get_public_key(&self) -> &PublicKey {
347 match self {
348 Denunciation::Endorsement(de) => &de.public_key,
349 Denunciation::BlockHeader(de) => &de.public_key,
350 }
351 }
352
353 pub fn is_expired(
358 denunciation_slot_period: &u64,
359 slot_period: &u64,
360 denunciation_expire_periods: &u64,
361 ) -> bool {
362 slot_period.checked_sub(*denunciation_slot_period) > Some(*denunciation_expire_periods)
363 }
364}
365
366impl TryFrom<(&SecureShareEndorsement, &SecureShareEndorsement, u64)> for Denunciation {
368 type Error = DenunciationError;
369
370 fn try_from(
371 (s_e1, s_e2, chain_id): (&SecureShareEndorsement, &SecureShareEndorsement, u64),
372 ) -> Result<Self, Self::Error> {
373 if s_e1.content.slot != s_e2.content.slot
376 || s_e1.content.index != s_e2.content.index
377 || s_e1.content_creator_pub_key != s_e2.content_creator_pub_key
378 || s_e1.id == s_e2.id
379 {
380 return Err(DenunciationError::InvalidInput(format!(
381 "Not the same slot, index or public key or same hash for {:?} & {:?}",
382 s_e1, s_e2
383 )));
384 }
385
386 let s_e1_hash_content = s_e1.id.get_hash();
388 let s_e1_hash = EndorsementDenunciation::compute_hash_for_sig_verif(
389 &s_e1.content_creator_pub_key,
390 &s_e1.content.slot,
391 &s_e1.content.index,
392 s_e1_hash_content,
393 chain_id,
394 );
395 let s_e2_hash_content = s_e2.id.get_hash();
397 let s_e2_hash = EndorsementDenunciation::compute_hash_for_sig_verif(
398 &s_e1.content_creator_pub_key,
399 &s_e1.content.slot,
400 &s_e1.content.index,
401 s_e2_hash_content,
402 chain_id,
403 );
404
405 s_e1.content_creator_pub_key
406 .verify_signature(&s_e1_hash, &s_e1.signature)?;
407 s_e1.content_creator_pub_key
408 .verify_signature(&s_e2_hash, &s_e2.signature)?;
409
410 Ok(Denunciation::Endorsement(EndorsementDenunciation {
411 public_key: s_e1.content_creator_pub_key,
412 slot: s_e1.content.slot,
413 index: s_e1.content.index,
414 signature_1: s_e1.signature,
415 signature_2: s_e2.signature,
416 hash_1: *s_e1_hash_content,
417 hash_2: *s_e2_hash_content,
418 }))
419 }
420}
421
422impl TryFrom<(&SecuredHeader, &SecuredHeader, u64)> for Denunciation {
424 type Error = DenunciationError;
425
426 fn try_from(
427 (s_bh1, s_bh2, chain_id): (&SecuredHeader, &SecuredHeader, u64),
428 ) -> Result<Self, Self::Error> {
429 if s_bh1.content.slot != s_bh2.content.slot
432 || s_bh1.content_creator_pub_key != s_bh2.content_creator_pub_key
433 || s_bh1.id == s_bh2.id
434 {
435 return Err(DenunciationError::InvalidInput(format!(
436 "Not the same slot or public key or same hash for {:?} & {:?}",
437 s_bh1, s_bh2
438 )));
439 }
440
441 let s_bh1_hash_content = s_bh1.id.get_hash();
443 let s_bh1_hash = BlockHeaderDenunciation::compute_hash_for_sig_verif(
444 &s_bh1.content_creator_pub_key,
445 &s_bh1.content.slot,
446 s_bh1_hash_content,
447 chain_id,
448 );
449 let s_bh2_hash_content = s_bh2.id.get_hash();
450 let s_bh2_hash = BlockHeaderDenunciation::compute_hash_for_sig_verif(
451 &s_bh1.content_creator_pub_key,
452 &s_bh1.content.slot,
453 s_bh2_hash_content,
454 chain_id,
455 );
456
457 s_bh1
458 .content_creator_pub_key
459 .verify_signature(&s_bh1_hash, &s_bh1.signature)?;
460 s_bh1
461 .content_creator_pub_key
462 .verify_signature(&s_bh2_hash, &s_bh2.signature)?;
463
464 Ok(Denunciation::BlockHeader(BlockHeaderDenunciation {
465 public_key: s_bh1.content_creator_pub_key,
466 slot: s_bh1.content.slot,
467 signature_1: s_bh1.signature,
468 signature_2: s_bh2.signature,
469 hash_1: *s_bh1_hash_content,
470 hash_2: *s_bh2_hash_content,
471 }))
472 }
473}
474
475#[allow(missing_docs)]
476#[derive(IntoPrimitive, Debug, TryFromPrimitive, VariantCount)]
477#[repr(u32)]
478pub enum DenunciationTypeId {
479 BlockHeader = 0,
480 Endorsement = 1,
481}
482
483impl From<&Denunciation> for DenunciationTypeId {
484 fn from(value: &Denunciation) -> Self {
485 match value {
486 Denunciation::Endorsement(_) => DenunciationTypeId::Endorsement,
487 Denunciation::BlockHeader(_) => DenunciationTypeId::BlockHeader,
488 }
489 }
490}
491
492#[allow(missing_docs)]
494#[derive(Error, Debug)]
495pub enum DenunciationError {
496 #[error("Invalid endorsements or block headers, cannot create denunciation: {0}")]
497 InvalidInput(String),
498 #[error("signature error: {0}")]
499 Signature(#[from] MassaSignatureError),
500 #[error("serialization error: {0}")]
501 Serialization(#[from] SerializeError),
502}
503
504struct EndorsementDenunciationSerializer {
508 slot_serializer: SlotSerializer,
509 u32_serializer: U32VarIntSerializer,
510 hash_serializer: HashSerializer,
511}
512
513impl EndorsementDenunciationSerializer {
514 const fn new() -> Self {
516 Self {
517 slot_serializer: SlotSerializer::new(),
518 u32_serializer: U32VarIntSerializer::new(),
519 hash_serializer: HashSerializer::new(),
520 }
521 }
522}
523
524impl Default for EndorsementDenunciationSerializer {
525 fn default() -> Self {
526 Self::new()
527 }
528}
529
530impl Serializer<EndorsementDenunciation> for EndorsementDenunciationSerializer {
531 fn serialize(
532 &self,
533 value: &EndorsementDenunciation,
534 buffer: &mut Vec<u8>,
535 ) -> Result<(), SerializeError> {
536 buffer.extend(value.public_key.to_bytes());
537 self.slot_serializer.serialize(&value.slot, buffer)?;
538 self.u32_serializer.serialize(&value.index, buffer)?;
539 self.hash_serializer.serialize(&value.hash_1, buffer)?;
540 self.hash_serializer.serialize(&value.hash_2, buffer)?;
541 buffer.extend(value.signature_1.to_bytes());
542 buffer.extend(value.signature_2.to_bytes());
543 Ok(())
544 }
545}
546
547struct EndorsementDenunciationDeserializer {
549 slot_deserializer: SlotDeserializer,
550 index_deserializer: U32VarIntDeserializer,
551 hash_deserializer: HashDeserializer,
552 pubkey_deserializer: PublicKeyDeserializer,
553 signature_deserializer: SignatureDeserializer,
554}
555
556impl EndorsementDenunciationDeserializer {
557 const fn new(thread_count: u8, endorsement_count: u32) -> Self {
559 EndorsementDenunciationDeserializer {
560 slot_deserializer: SlotDeserializer::new(
561 (Included(0), Included(u64::MAX)),
562 (Included(0), Excluded(thread_count)),
563 ),
564 index_deserializer: U32VarIntDeserializer::new(
565 Included(0),
566 Excluded(endorsement_count),
567 ),
568 hash_deserializer: HashDeserializer::new(),
569 pubkey_deserializer: PublicKeyDeserializer::new(),
570 signature_deserializer: SignatureDeserializer::new(),
571 }
572 }
573}
574
575impl Deserializer<EndorsementDenunciation> for EndorsementDenunciationDeserializer {
576 fn deserialize<'a, E: ParseError<&'a [u8]> + ContextError<&'a [u8]>>(
577 &self,
578 buffer: &'a [u8],
579 ) -> IResult<&'a [u8], EndorsementDenunciation, E> {
580 context(
581 "Failed Endorsement Denunciation deserialization",
582 tuple((
583 context("Failed public key deserialization", |input| {
584 self.pubkey_deserializer.deserialize(input)
585 }),
586 context("Failed slot deserialization", |input| {
587 self.slot_deserializer.deserialize(input)
588 }),
589 context("Failed slot deserialization", |input| {
590 self.index_deserializer.deserialize(input)
591 }),
592 context("Failed hash 1 deserialization", |input| {
593 self.hash_deserializer.deserialize(input)
594 }),
595 context("Failed hash 2 deserialization", |input| {
596 self.hash_deserializer.deserialize(input)
597 }),
598 context("Failed signature 1 deserialization", |input| {
599 self.signature_deserializer.deserialize(input)
600 }),
601 context("Failed signature 2 deserialization", |input| {
602 self.signature_deserializer.deserialize(input)
603 }),
604 )),
605 )
606 .map(
607 |(public_key, slot, index, hash_1, hash_2, signature_1, signature_2)| {
608 EndorsementDenunciation {
609 public_key,
610 slot,
611 index,
612 hash_1,
613 hash_2,
614 signature_1,
615 signature_2,
616 }
617 },
618 )
619 .parse(buffer)
620 }
621}
622
623struct BlockHeaderDenunciationSerializer {
625 slot_serializer: SlotSerializer,
626 hash_serializer: HashSerializer,
627}
628
629impl BlockHeaderDenunciationSerializer {
630 const fn new() -> Self {
632 Self {
633 slot_serializer: SlotSerializer::new(),
634 hash_serializer: HashSerializer::new(),
635 }
636 }
637}
638
639impl Default for BlockHeaderDenunciationSerializer {
640 fn default() -> Self {
641 Self::new()
642 }
643}
644
645impl Serializer<BlockHeaderDenunciation> for BlockHeaderDenunciationSerializer {
646 fn serialize(
647 &self,
648 value: &BlockHeaderDenunciation,
649 buffer: &mut Vec<u8>,
650 ) -> Result<(), SerializeError> {
651 buffer.extend(value.public_key.to_bytes());
652 self.slot_serializer.serialize(&value.slot, buffer)?;
653 self.hash_serializer.serialize(&value.hash_1, buffer)?;
654 self.hash_serializer.serialize(&value.hash_2, buffer)?;
655 buffer.extend(value.signature_1.to_bytes());
656 buffer.extend(value.signature_2.to_bytes());
657 Ok(())
658 }
659}
660
661struct BlockHeaderDenunciationDeserializer {
663 slot_deserializer: SlotDeserializer,
664 hash_deserializer: HashDeserializer,
665 pubkey_deserializer: PublicKeyDeserializer,
666 signature_deserializer: SignatureDeserializer,
667}
668
669impl BlockHeaderDenunciationDeserializer {
670 pub const fn new(thread_count: u8) -> Self {
672 Self {
673 slot_deserializer: SlotDeserializer::new(
674 (Included(0), Included(u64::MAX)),
675 (Included(0), Excluded(thread_count)),
676 ),
677 hash_deserializer: HashDeserializer::new(),
678 pubkey_deserializer: PublicKeyDeserializer::new(),
679 signature_deserializer: SignatureDeserializer::new(),
680 }
681 }
682}
683
684impl Deserializer<BlockHeaderDenunciation> for BlockHeaderDenunciationDeserializer {
685 fn deserialize<'a, E: ParseError<&'a [u8]> + ContextError<&'a [u8]>>(
686 &self,
687 buffer: &'a [u8],
688 ) -> IResult<&'a [u8], BlockHeaderDenunciation, E> {
689 context(
690 "Failed BlockHeader Denunciation deserialization",
691 tuple((
692 context("Failed public key deserialization", |input| {
693 self.pubkey_deserializer.deserialize(input)
694 }),
695 context("Failed slot deserialization", |input| {
696 self.slot_deserializer.deserialize(input)
697 }),
698 context("Failed hash 1 deserialization", |input| {
699 self.hash_deserializer.deserialize(input)
700 }),
701 context("Failed hash 2 deserialization", |input| {
702 self.hash_deserializer.deserialize(input)
703 }),
704 context("Failed signature 1 deserialization", |input| {
705 self.signature_deserializer.deserialize(input)
706 }),
707 context("Failed signature 2 deserialization", |input| {
708 self.signature_deserializer.deserialize(input)
709 }),
710 )),
711 )
712 .map(
713 |(public_key, slot, hash_1, hash_2, signature_1, signature_2)| {
714 BlockHeaderDenunciation {
715 public_key,
716 slot,
717 hash_1,
718 hash_2,
719 signature_1,
720 signature_2,
721 }
722 },
723 )
724 .parse(buffer)
725 }
726}
727
728pub struct DenunciationSerializer {
730 endo_de_serializer: EndorsementDenunciationSerializer,
731 blkh_de_serializer: BlockHeaderDenunciationSerializer,
732 type_id_serializer: U32VarIntSerializer,
733}
734
735impl DenunciationSerializer {
736 pub const fn new() -> Self {
738 Self {
739 endo_de_serializer: EndorsementDenunciationSerializer::new(),
740 blkh_de_serializer: BlockHeaderDenunciationSerializer::new(),
741 type_id_serializer: U32VarIntSerializer::new(),
742 }
743 }
744}
745
746impl Default for DenunciationSerializer {
747 fn default() -> Self {
748 Self::new()
749 }
750}
751
752impl Serializer<Denunciation> for DenunciationSerializer {
753 fn serialize(&self, value: &Denunciation, buffer: &mut Vec<u8>) -> Result<(), SerializeError> {
754 let de_type_id = DenunciationTypeId::from(value);
755 self.type_id_serializer
756 .serialize(&u32::from(de_type_id), buffer)?;
757 match value {
758 Denunciation::Endorsement(de) => {
759 self.endo_de_serializer.serialize(de, buffer)?;
760 }
761 Denunciation::BlockHeader(de) => {
762 self.blkh_de_serializer.serialize(de, buffer)?;
763 }
764 }
765 Ok(())
766 }
767}
768
769pub struct DenunciationDeserializer {
771 endo_de_deserializer: EndorsementDenunciationDeserializer,
772 blkh_de_deserializer: BlockHeaderDenunciationDeserializer,
773 type_id_deserializer: U32VarIntDeserializer,
774}
775
776impl DenunciationDeserializer {
777 pub const fn new(thread_count: u8, endorsement_count: u32) -> Self {
779 Self {
780 endo_de_deserializer: EndorsementDenunciationDeserializer::new(
781 thread_count,
782 endorsement_count,
783 ),
784 blkh_de_deserializer: BlockHeaderDenunciationDeserializer::new(thread_count),
785 type_id_deserializer: U32VarIntDeserializer::new(
786 Included(0),
787 Excluded(DenunciationTypeId::VARIANT_COUNT as u32),
788 ),
789 }
790 }
791}
792
793impl Deserializer<Denunciation> for DenunciationDeserializer {
794 fn deserialize<'a, E: ParseError<&'a [u8]> + ContextError<&'a [u8]>>(
795 &self,
796 buffer: &'a [u8],
797 ) -> IResult<&'a [u8], Denunciation, E> {
798 let (rem, de_type_id_) = context("Failed Denunciation type id deserialization", |input| {
799 self.type_id_deserializer.deserialize(input)
800 })
801 .parse(buffer)?;
802
803 let de_type_id = DenunciationTypeId::try_from(de_type_id_).map_err(|_| {
804 nom::Err::Error(ParseError::from_error_kind(
805 buffer,
806 nom::error::ErrorKind::Fail,
807 ))
808 })?;
809
810 match de_type_id {
811 DenunciationTypeId::Endorsement => {
812 let (rem2, endo_de) = self.endo_de_deserializer.deserialize(rem)?;
813 IResult::Ok((rem2, Denunciation::Endorsement(endo_de)))
814 }
815 DenunciationTypeId::BlockHeader => {
816 let (rem2, blkh_de) = self.blkh_de_deserializer.deserialize(rem)?;
817 IResult::Ok((rem2, Denunciation::BlockHeader(blkh_de)))
818 }
819 }
820 }
821}
822
823#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)]
828pub enum DenunciationIndex {
830 BlockHeader {
832 slot: Slot,
834 },
835 Endorsement {
837 slot: Slot,
839 index: u32,
841 },
842}
843
844impl DenunciationIndex {
845 pub fn get_slot(&self) -> &Slot {
847 match self {
848 DenunciationIndex::BlockHeader { slot } => slot,
849 DenunciationIndex::Endorsement { slot, .. } => slot,
850 }
851 }
852
853 pub fn get_index(&self) -> Option<&u32> {
855 match self {
856 DenunciationIndex::BlockHeader { .. } => None,
857 DenunciationIndex::Endorsement { slot: _, index } => Some(index),
858 }
859 }
860
861 pub fn get_hash(&self) -> Hash {
863 let mut buffer = u32::from(DenunciationIndexTypeId::from(self))
864 .to_le_bytes()
865 .to_vec();
866 match self {
867 DenunciationIndex::BlockHeader { slot } => buffer.extend(slot.to_bytes_key()),
868 DenunciationIndex::Endorsement { slot, index } => {
869 buffer.extend(slot.to_bytes_key());
870 buffer.extend(index.to_le_bytes());
871 }
872 }
873 Hash::compute_from(&buffer)
874 }
875}
876
877impl From<&Denunciation> for DenunciationIndex {
879 fn from(value: &Denunciation) -> Self {
880 match value {
881 Denunciation::Endorsement(endo_de) => DenunciationIndex::Endorsement {
882 slot: endo_de.slot,
883 index: endo_de.index,
884 },
885 Denunciation::BlockHeader(blkh_de) => {
886 DenunciationIndex::BlockHeader { slot: blkh_de.slot }
887 }
888 }
889 }
890}
891
892impl From<&DenunciationPrecursor> for DenunciationIndex {
894 fn from(value: &DenunciationPrecursor) -> Self {
895 match value {
896 DenunciationPrecursor::Endorsement(de_p) => DenunciationIndex::Endorsement {
897 slot: de_p.slot,
898 index: de_p.index,
899 },
900 DenunciationPrecursor::BlockHeader(de_p) => {
901 DenunciationIndex::BlockHeader { slot: de_p.slot }
902 }
903 }
904 }
905}
906
907impl Ord for DenunciationIndex {
908 fn cmp(&self, other: &Self) -> Ordering {
909 let self_key = (
912 self.get_slot(),
913 self.get_index().unwrap_or(&0),
914 u32::from(DenunciationIndexTypeId::from(self)),
915 );
916 let other_key = (
917 other.get_slot(),
918 other.get_index().unwrap_or(&0),
919 u32::from(DenunciationIndexTypeId::from(other)),
920 );
921 self_key.cmp(&other_key)
922 }
923}
924
925impl PartialOrd for DenunciationIndex {
926 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
927 Some(self.cmp(other))
928 }
929}
930
931#[derive(IntoPrimitive, Debug, Eq, PartialEq, TryFromPrimitive)]
936#[repr(u32)]
937enum DenunciationIndexTypeId {
938 BlockHeader = 0,
939 Endorsement = 1,
940}
941
942impl From<&DenunciationIndex> for DenunciationIndexTypeId {
943 fn from(value: &DenunciationIndex) -> Self {
944 match value {
945 DenunciationIndex::BlockHeader { .. } => DenunciationIndexTypeId::BlockHeader,
946 DenunciationIndex::Endorsement { .. } => DenunciationIndexTypeId::Endorsement,
947 }
948 }
949}
950
951#[derive(Clone)]
952pub struct DenunciationIndexSerializer {
954 u32_serializer: U32VarIntSerializer,
955 slot_serializer: SlotSerializer,
956 index_serializer: U32VarIntSerializer,
957}
958
959impl DenunciationIndexSerializer {
960 pub const fn new() -> Self {
962 Self {
963 u32_serializer: U32VarIntSerializer::new(),
964 slot_serializer: SlotSerializer::new(),
965 index_serializer: U32VarIntSerializer::new(),
966 }
967 }
968}
969
970impl Default for DenunciationIndexSerializer {
971 fn default() -> Self {
972 Self::new()
973 }
974}
975
976impl Serializer<DenunciationIndex> for DenunciationIndexSerializer {
977 fn serialize(
978 &self,
979 value: &DenunciationIndex,
980 buffer: &mut Vec<u8>,
981 ) -> Result<(), SerializeError> {
982 match value {
983 DenunciationIndex::BlockHeader { slot } => {
984 self.u32_serializer
985 .serialize(&u32::from(DenunciationIndexTypeId::BlockHeader), buffer)?;
986 self.slot_serializer.serialize(slot, buffer)?;
987 }
988 DenunciationIndex::Endorsement { slot, index } => {
989 self.u32_serializer
990 .serialize(&u32::from(DenunciationIndexTypeId::Endorsement), buffer)?;
991 self.slot_serializer.serialize(slot, buffer)?;
992 self.index_serializer.serialize(index, buffer)?;
993 }
994 }
995 Ok(())
996 }
997}
998
999#[derive(Clone)]
1000pub struct DenunciationIndexDeserializer {
1002 id_deserializer: U32VarIntDeserializer,
1003 slot_deserializer: SlotDeserializer,
1004 index_deserializer: U32VarIntDeserializer,
1005}
1006
1007impl DenunciationIndexDeserializer {
1008 pub const fn new(thread_count: u8, endorsement_count: u32) -> Self {
1010 Self {
1011 id_deserializer: U32VarIntDeserializer::new(Included(0), Included(u32::MAX)),
1012 slot_deserializer: SlotDeserializer::new(
1013 (Included(0), Included(u64::MAX)),
1014 (Included(0), Excluded(thread_count)),
1015 ),
1016 index_deserializer: U32VarIntDeserializer::new(
1017 Included(0),
1018 Included(endorsement_count),
1019 ),
1020 }
1021 }
1022}
1023
1024impl Deserializer<DenunciationIndex> for DenunciationIndexDeserializer {
1025 fn deserialize<'a, E: ParseError<&'a [u8]> + ContextError<&'a [u8]>>(
1026 &self,
1027 buffer: &'a [u8],
1028 ) -> IResult<&'a [u8], DenunciationIndex, E> {
1029 let (input, id) = self.id_deserializer.deserialize(buffer)?;
1030 let id = DenunciationIndexTypeId::try_from(id).map_err(|_| {
1031 nom::Err::Error(ParseError::from_error_kind(
1032 buffer,
1033 nom::error::ErrorKind::Eof,
1034 ))
1035 })?;
1036
1037 match id {
1038 DenunciationIndexTypeId::BlockHeader => {
1039 context("Failed slot deserialization", |input| {
1040 self.slot_deserializer.deserialize(input)
1041 })
1042 .map(|slot| DenunciationIndex::BlockHeader { slot })
1043 .parse(input)
1045 }
1046 DenunciationIndexTypeId::Endorsement => context(
1047 "Failed Endorsement denunciation index",
1048 tuple((
1049 context("Failed slot deserialization", |input| {
1050 self.slot_deserializer.deserialize(input)
1051 }),
1052 context("Failed index deserialization", |input| {
1053 self.index_deserializer.deserialize(input)
1054 }),
1055 )),
1056 )
1057 .map(|(slot, index)| DenunciationIndex::Endorsement { slot, index })
1058 .parse(input),
1059 }
1060 }
1061}
1062
1063#[derive(Debug, Clone, PartialEq)]
1069pub struct EndorsementDenunciationPrecursor {
1070 pub public_key: PublicKey,
1072 pub slot: Slot,
1074 pub index: u32,
1076 hash: Hash,
1078 signature: Signature,
1080}
1081
1082#[derive(Debug, Clone, PartialEq)]
1084pub struct BlockHeaderDenunciationPrecursor {
1085 pub public_key: PublicKey,
1087 pub slot: Slot,
1089 hash: Hash,
1091 signature: Signature,
1093}
1094
1095#[derive(Debug, Clone, PartialEq)]
1098pub enum DenunciationPrecursor {
1099 Endorsement(EndorsementDenunciationPrecursor),
1101 BlockHeader(BlockHeaderDenunciationPrecursor),
1103}
1104
1105impl DenunciationPrecursor {
1106 pub fn get_slot(&self) -> &Slot {
1108 match self {
1109 DenunciationPrecursor::Endorsement(endo_de_p) => &endo_de_p.slot,
1110 DenunciationPrecursor::BlockHeader(blkh_de_p) => &blkh_de_p.slot,
1111 }
1112 }
1113
1114 pub fn get_public_key(&self) -> &PublicKey {
1116 match self {
1117 DenunciationPrecursor::Endorsement(endo_de_p) => &endo_de_p.public_key,
1118 DenunciationPrecursor::BlockHeader(blkh_de_p) => &blkh_de_p.public_key,
1119 }
1120 }
1121}
1122
1123impl From<&SecureShareEndorsement> for DenunciationPrecursor {
1124 fn from(value: &SecureShareEndorsement) -> Self {
1125 DenunciationPrecursor::Endorsement(EndorsementDenunciationPrecursor {
1126 public_key: value.content_creator_pub_key,
1127 slot: value.content.slot,
1128 index: value.content.index,
1129 hash: *value.id.get_hash(),
1130 signature: value.signature,
1131 })
1132 }
1133}
1134
1135impl From<&SecuredHeader> for DenunciationPrecursor {
1136 fn from(value: &SecuredHeader) -> Self {
1137 DenunciationPrecursor::BlockHeader(BlockHeaderDenunciationPrecursor {
1138 public_key: value.content_creator_pub_key,
1139 slot: value.content.slot,
1140 hash: *value.id.get_hash(),
1141 signature: value.signature,
1142 })
1143 }
1144}
1145
1146impl TryFrom<(&DenunciationPrecursor, &DenunciationPrecursor, u64)> for Denunciation {
1148 type Error = DenunciationError;
1149
1150 fn try_from(
1151 (de_p_1, de_p_2, chain_id): (&DenunciationPrecursor, &DenunciationPrecursor, u64),
1152 ) -> Result<Self, Self::Error> {
1153 match (de_p_1, de_p_2) {
1154 (
1155 DenunciationPrecursor::BlockHeader(de_p_blkh_1),
1156 DenunciationPrecursor::BlockHeader(de_p_blkh_2),
1157 ) => {
1158 if de_p_blkh_1.slot != de_p_blkh_2.slot
1160 || de_p_blkh_1.public_key != de_p_blkh_2.public_key
1161 || de_p_blkh_1.hash == de_p_blkh_2.hash
1162 {
1163 return Err(DenunciationError::InvalidInput(
1164 format!("Not the same slot or public key or same hash for de precursor: {:?} & {:?}", de_p_blkh_1, de_p_blkh_2)
1165 ));
1166 }
1167
1168 let de_p_blkh_1_hash = BlockHeaderDenunciation::compute_hash_for_sig_verif(
1170 &de_p_blkh_1.public_key,
1171 &de_p_blkh_1.slot,
1172 &de_p_blkh_1.hash,
1173 chain_id,
1174 );
1175 let de_p_blkh_2_hash = BlockHeaderDenunciation::compute_hash_for_sig_verif(
1176 &de_p_blkh_2.public_key,
1177 &de_p_blkh_2.slot,
1178 &de_p_blkh_2.hash,
1179 chain_id,
1180 );
1181
1182 de_p_blkh_1
1183 .public_key
1184 .verify_signature(&de_p_blkh_1_hash, &de_p_blkh_1.signature)?;
1185 de_p_blkh_1
1186 .public_key
1187 .verify_signature(&de_p_blkh_2_hash, &de_p_blkh_2.signature)?;
1188
1189 Ok(Denunciation::BlockHeader(BlockHeaderDenunciation {
1190 public_key: de_p_blkh_1.public_key,
1191 slot: de_p_blkh_1.slot,
1192 signature_1: de_p_blkh_1.signature,
1193 signature_2: de_p_blkh_2.signature,
1194 hash_1: de_p_blkh_1.hash,
1195 hash_2: de_p_blkh_2.hash,
1196 }))
1197 }
1198 (
1199 DenunciationPrecursor::Endorsement(de_p_endo_1),
1200 DenunciationPrecursor::Endorsement(de_p_endo_2),
1201 ) => {
1202 if de_p_endo_1.slot != de_p_endo_2.slot
1204 || de_p_endo_1.index != de_p_endo_2.index
1205 || de_p_endo_1.public_key != de_p_endo_2.public_key
1206 || de_p_endo_1.hash == de_p_endo_2.hash
1207 {
1208 return Err(DenunciationError::InvalidInput(
1209 format!("Not the same slot, index or public key or same hash for de precursor: {:?} & {:?}", de_p_endo_1, de_p_endo_2)
1210 ));
1211 }
1212
1213 let de_p_endo_1_hash = EndorsementDenunciation::compute_hash_for_sig_verif(
1215 &de_p_endo_1.public_key,
1216 &de_p_endo_1.slot,
1217 &de_p_endo_1.index,
1218 &de_p_endo_1.hash,
1219 chain_id,
1220 );
1221 let de_p_endo_2_hash = EndorsementDenunciation::compute_hash_for_sig_verif(
1222 &de_p_endo_2.public_key,
1223 &de_p_endo_2.slot,
1224 &de_p_endo_2.index,
1225 &de_p_endo_2.hash,
1226 chain_id,
1227 );
1228
1229 de_p_endo_1
1230 .public_key
1231 .verify_signature(&de_p_endo_1_hash, &de_p_endo_1.signature)?;
1232 de_p_endo_1
1233 .public_key
1234 .verify_signature(&de_p_endo_2_hash, &de_p_endo_2.signature)?;
1235
1236 Ok(Denunciation::Endorsement(EndorsementDenunciation {
1237 public_key: de_p_endo_1.public_key,
1238 slot: de_p_endo_1.slot,
1239 index: de_p_endo_1.index,
1240 signature_1: de_p_endo_1.signature,
1241 signature_2: de_p_endo_2.signature,
1242 hash_1: de_p_endo_1.hash,
1243 hash_2: de_p_endo_2.hash,
1244 }))
1245 }
1246 _ => {
1247 Err(DenunciationError::InvalidInput(
1249 "Mixed endorsement and block header denunciation precursors".to_string(),
1250 ))
1251 }
1252 }
1253 }
1254}
1255
1256#[cfg(any(test, feature = "test-exports"))]
1261impl Denunciation {
1262 pub fn check_invariants(&self) -> Result<(), Box<dyn std::error::Error>> {
1264 if !self.is_valid_with_chain(*crate::config::CHAINID) {
1265 return Err(format!("Denunciation is invalid: {:?}", self).into());
1266 }
1267 Ok(())
1268 }
1269}
1270
1271#[cfg(test)]
1274mod tests {
1275 use super::*;
1276
1277 use massa_hash::Hash;
1278 use massa_serialization::DeserializeError;
1279 use massa_signature::KeyPair;
1280
1281 use crate::block_id::BlockId;
1282 use crate::config::{CHAINID, ENDORSEMENT_COUNT, THREAD_COUNT};
1283 use crate::endorsement::{Endorsement, EndorsementSerializer, SecureShareEndorsement};
1284 use crate::secure_share::{Id, SecureShareContent};
1285
1286 use crate::test_exports::{
1287 gen_block_headers_for_denunciation, gen_endorsements_for_denunciation,
1288 };
1289
1290 #[test]
1291 fn test_endorsement_denunciation() {
1292 let (_slot, _keypair, s_endorsement_1, s_endorsement_2, _s_endorsement_3) =
1294 gen_endorsements_for_denunciation(None, None);
1295 let denunciation: Denunciation = (&s_endorsement_1, &s_endorsement_2, *CHAINID)
1296 .try_into()
1297 .unwrap();
1298
1299 assert!(denunciation.is_for_endorsement());
1300 assert!(denunciation.is_valid_with_chain(*CHAINID));
1301 }
1302
1303 #[test]
1304 fn test_endorsement_denunciation_invalid_1() {
1305 let (slot, keypair, s_endorsement_1, _s_endorsement_2, _s_endorsement_3) =
1306 gen_endorsements_for_denunciation(None, None);
1307
1308 let endorsement_4 = Endorsement {
1310 slot,
1311 index: 9,
1312 endorsed_block: BlockId::generate_from_hash(Hash::compute_from("foo".as_bytes())),
1313 };
1314 let s_endorsement_4 = Endorsement::new_verifiable(
1315 endorsement_4,
1316 EndorsementSerializer::new(),
1317 &keypair,
1318 *CHAINID,
1319 )
1320 .unwrap();
1321
1322 let denunciation = Denunciation::try_from((&s_endorsement_1, &s_endorsement_4, *CHAINID));
1323
1324 assert!(matches!(
1325 denunciation,
1326 Err(DenunciationError::InvalidInput(..))
1327 ));
1328
1329 let denunciation = Denunciation::try_from((&s_endorsement_1, &s_endorsement_1, *CHAINID));
1331
1332 assert!(matches!(
1333 denunciation,
1334 Err(DenunciationError::InvalidInput(..))
1335 ));
1336 }
1337
1338 #[test]
1339 fn test_endorsement_denunciation_is_for() {
1340 let (slot, keypair, s_endorsement_1, s_endorsement_2, s_endorsement_3) =
1341 gen_endorsements_for_denunciation(None, None);
1342
1343 let denunciation: Denunciation = (&s_endorsement_1, &s_endorsement_2, *CHAINID)
1344 .try_into()
1345 .unwrap();
1346
1347 assert!(denunciation.is_for_endorsement());
1348 assert!(denunciation.is_valid_with_chain(*CHAINID));
1349
1350 let endorsement_4 = Endorsement {
1352 slot,
1353 index: 9,
1354 endorsed_block: BlockId::generate_from_hash(Hash::compute_from("foo".as_bytes())),
1355 };
1356 let s_endorsement_4 = Endorsement::new_verifiable(
1357 endorsement_4,
1358 EndorsementSerializer::new(),
1359 &keypair,
1360 *CHAINID,
1361 )
1362 .unwrap();
1363
1364 assert!(!denunciation
1365 .is_also_for_endorsement(&s_endorsement_4, *CHAINID)
1366 .unwrap());
1367 assert!(denunciation
1368 .is_also_for_endorsement(&s_endorsement_3, *CHAINID)
1369 .unwrap());
1370 assert!(denunciation.is_valid_with_chain(*CHAINID));
1371 }
1372
1373 #[test]
1374 fn test_block_header_denunciation() {
1375 let (_slot, _keypair, s_block_header_1, s_block_header_2, s_block_header_3) =
1377 gen_block_headers_for_denunciation(None, None);
1378 let denunciation: Denunciation = (&s_block_header_1, &s_block_header_2, *CHAINID)
1379 .try_into()
1380 .unwrap();
1381
1382 assert!(denunciation.is_for_block_header());
1383 assert!(denunciation.is_valid_with_chain(*CHAINID));
1384 assert!(denunciation
1385 .is_also_for_block_header(&s_block_header_3, *CHAINID)
1386 .unwrap());
1387 }
1388
1389 #[test]
1390 fn test_forge_invalid_denunciation() {
1391 let keypair = KeyPair::generate(0).unwrap();
1392 let slot_1 = Slot::new(4, 2);
1393 let slot_2 = Slot::new(3, 7);
1394
1395 let endorsement_1 = Endorsement {
1396 slot: slot_1,
1397 index: 0,
1398 endorsed_block: BlockId::generate_from_hash(Hash::compute_from("blk1".as_bytes())),
1399 };
1400
1401 let s_endorsement_1: SecureShareEndorsement = Endorsement::new_verifiable(
1402 endorsement_1,
1403 EndorsementSerializer::new(),
1404 &keypair,
1405 *CHAINID,
1406 )
1407 .unwrap();
1408
1409 let endorsement_2 = Endorsement {
1410 slot: slot_2,
1411 index: 0,
1412 endorsed_block: BlockId::generate_from_hash(Hash::compute_from("blk2".as_bytes())),
1413 };
1414
1415 let s_endorsement_2: SecureShareEndorsement = Endorsement::new_verifiable(
1416 endorsement_2,
1417 EndorsementSerializer::new(),
1418 &keypair,
1419 *CHAINID,
1420 )
1421 .unwrap();
1422
1423 let de_forged_1 = Denunciation::Endorsement(EndorsementDenunciation {
1425 public_key: keypair.get_public_key(),
1426 slot: slot_1,
1427 index: 0,
1428 hash_1: *s_endorsement_1.id.get_hash(), hash_2: *s_endorsement_1.id.get_hash(),
1430 signature_1: s_endorsement_1.signature,
1431 signature_2: s_endorsement_1.signature,
1432 });
1433
1434 assert!(!de_forged_1.is_valid_with_chain(*CHAINID));
1436
1437 let de_forged_2 = Denunciation::Endorsement(EndorsementDenunciation {
1439 public_key: keypair.get_public_key(),
1440 slot: slot_2,
1441 index: 0,
1442 hash_1: *s_endorsement_1.id.get_hash(),
1443 hash_2: *s_endorsement_2.id.get_hash(),
1444 signature_1: s_endorsement_1.signature,
1445 signature_2: s_endorsement_2.signature,
1446 });
1447
1448 assert!(!de_forged_2.is_valid_with_chain(*CHAINID));
1451 }
1452
1453 #[test]
1455 fn test_endorsement_denunciation_ser_der() {
1456 let (_, _, s_endorsement_1, s_endorsement_2, _) =
1457 gen_endorsements_for_denunciation(None, None);
1458
1459 let denunciation =
1460 Denunciation::try_from((&s_endorsement_1, &s_endorsement_2, *CHAINID)).unwrap();
1461
1462 let mut buffer = Vec::new();
1463 let de_ser = EndorsementDenunciationSerializer::new();
1464
1465 match denunciation {
1466 Denunciation::Endorsement(de) => {
1467 de_ser.serialize(&de, &mut buffer).unwrap();
1468 let de_der =
1469 EndorsementDenunciationDeserializer::new(THREAD_COUNT, ENDORSEMENT_COUNT);
1470
1471 let (rem, de_der_res) = de_der.deserialize::<DeserializeError>(&buffer).unwrap();
1472
1473 assert!(rem.is_empty());
1474 assert_eq!(de, de_der_res);
1475 }
1476 Denunciation::BlockHeader(_) => {
1477 unimplemented!()
1478 }
1479 }
1480 }
1481
1482 #[test]
1483 fn test_block_header_denunciation_ser_der() {
1484 let (_, _, s_block_header_1, s_block_header_2, _) =
1485 gen_block_headers_for_denunciation(None, None);
1486 let denunciation: Denunciation = (&s_block_header_1, &s_block_header_2, *CHAINID)
1487 .try_into()
1488 .unwrap();
1489
1490 let mut buffer = Vec::new();
1491 let de_ser = BlockHeaderDenunciationSerializer::new();
1492
1493 match denunciation {
1494 Denunciation::Endorsement(_) => {
1495 unimplemented!()
1496 }
1497 Denunciation::BlockHeader(de) => {
1498 de_ser.serialize(&de, &mut buffer).unwrap();
1499 let de_der = BlockHeaderDenunciationDeserializer::new(THREAD_COUNT);
1500
1501 let (rem, de_der_res) = de_der.deserialize::<DeserializeError>(&buffer).unwrap();
1502
1503 assert!(rem.is_empty());
1504 assert_eq!(de, de_der_res);
1505 }
1506 }
1507 }
1508
1509 #[test]
1510 fn test_denunciation_ser_der() {
1511 let (_, _, s_block_header_1, s_block_header_2, _) =
1512 gen_block_headers_for_denunciation(None, None);
1513 let denunciation: Denunciation = (&s_block_header_1, &s_block_header_2, *CHAINID)
1514 .try_into()
1515 .unwrap();
1516
1517 let mut buffer = Vec::new();
1518 let de_ser = DenunciationSerializer::new();
1519
1520 de_ser.serialize(&denunciation, &mut buffer).unwrap();
1521 let de_der = DenunciationDeserializer::new(THREAD_COUNT, ENDORSEMENT_COUNT);
1522
1523 let (rem, de_der_res) = de_der.deserialize::<DeserializeError>(&buffer).unwrap();
1524
1525 assert!(rem.is_empty());
1526 assert_eq!(denunciation, de_der_res);
1527
1528 let (_, _, s_endorsement_1, s_endorsement_2, _) =
1529 gen_endorsements_for_denunciation(None, None);
1530 let denunciation =
1531 Denunciation::try_from((&s_endorsement_1, &s_endorsement_2, *CHAINID)).unwrap();
1532 buffer.clear();
1533
1534 de_ser.serialize(&denunciation, &mut buffer).unwrap();
1535 let (rem, de_der_res) = de_der.deserialize::<DeserializeError>(&buffer).unwrap();
1536 assert!(rem.is_empty());
1537 assert_eq!(denunciation, de_der_res);
1538 }
1539
1540 #[test]
1541 fn test_denunciation_precursor() {
1542 let (_, _, s_block_header_1, s_block_header_2, _) =
1543 gen_block_headers_for_denunciation(None, None);
1544 let denunciation: Denunciation = (&s_block_header_1, &s_block_header_2, *CHAINID)
1545 .try_into()
1546 .unwrap();
1547
1548 let de_p_1 = DenunciationPrecursor::from(&s_block_header_1);
1549 let de_p_2 = DenunciationPrecursor::from(&s_block_header_2);
1550 let denunciation_2: Denunciation = (&de_p_1, &de_p_2, *CHAINID).try_into().unwrap();
1551
1552 assert_eq!(denunciation, denunciation_2);
1553
1554 let (_, _, s_endorsement_1, s_endorsement_2, _) =
1555 gen_endorsements_for_denunciation(None, None);
1556 let denunciation_3 =
1557 Denunciation::try_from((&s_endorsement_1, &s_endorsement_2, *CHAINID)).unwrap();
1558
1559 let de_p_3 = DenunciationPrecursor::from(&s_endorsement_1);
1560 let de_p_4 = DenunciationPrecursor::from(&s_endorsement_2);
1561 let denunciation_4: Denunciation = (&de_p_3, &de_p_4, *CHAINID).try_into().unwrap();
1562
1563 assert_eq!(denunciation_3, denunciation_4);
1564 }
1565
1566 #[test]
1567 fn test_denunciation_index_ser_der() {
1568 let (_, _, s_block_header_1, s_block_header_2, _) =
1569 gen_block_headers_for_denunciation(None, None);
1570 let denunciation_1: Denunciation = (&s_block_header_1, &s_block_header_2, *CHAINID)
1571 .try_into()
1572 .unwrap();
1573 let denunciation_index_1 = DenunciationIndex::from(&denunciation_1);
1574
1575 let (_, _, s_endorsement_1, s_endorsement_2, _) =
1576 gen_endorsements_for_denunciation(None, None);
1577 let denunciation_2 =
1578 Denunciation::try_from((&s_endorsement_1, &s_endorsement_2, *CHAINID)).unwrap();
1579 let denunciation_index_2 = DenunciationIndex::from(&denunciation_2);
1580
1581 let mut buffer = Vec::new();
1582 let de_idx_ser = DenunciationIndexSerializer::new();
1583 de_idx_ser
1584 .serialize(&denunciation_index_1, &mut buffer)
1585 .unwrap();
1586 let de_idx_der = DenunciationIndexDeserializer::new(THREAD_COUNT, ENDORSEMENT_COUNT);
1587 let (rem, de_idx_der_res) = de_idx_der.deserialize::<DeserializeError>(&buffer).unwrap();
1588
1589 assert!(rem.is_empty());
1590 assert_eq!(denunciation_index_1, de_idx_der_res);
1591
1592 let mut buffer = Vec::new();
1593 let de_idx_ser = DenunciationIndexSerializer::new();
1594 de_idx_ser
1595 .serialize(&denunciation_index_2, &mut buffer)
1596 .unwrap();
1597 let de_idx_der = DenunciationIndexDeserializer::new(THREAD_COUNT, ENDORSEMENT_COUNT);
1598 let (rem, de_idx_der_res) = de_idx_der.deserialize::<DeserializeError>(&buffer).unwrap();
1599
1600 assert!(rem.is_empty());
1601 assert_eq!(denunciation_index_2, de_idx_der_res);
1602 }
1603
1604 fn make_endorsement(
1613 keypair: &KeyPair,
1614 slot: Slot,
1615 endorsed_block: &str,
1616 chain_id: u64,
1617 ) -> SecureShareEndorsement {
1618 Endorsement::new_verifiable(
1619 Endorsement {
1620 slot,
1621 index: 0,
1622 endorsed_block: BlockId::generate_from_hash(Hash::compute_from(
1623 endorsed_block.as_bytes(),
1624 )),
1625 },
1626 EndorsementSerializer::new(),
1627 keypair,
1628 chain_id,
1629 )
1630 .unwrap()
1631 }
1632
1633 #[test]
1634 fn test_endorsement_denunciation_cross_chain_rejected() {
1635 let keypair = KeyPair::generate(0).unwrap();
1636 let slot = Slot::new(3, 7);
1637 let chain_a: u64 = 77658377; let chain_b: u64 = 77658376; let e_a1 = make_endorsement(&keypair, slot, "blk_a1", chain_a);
1642 let e_a2 = make_endorsement(&keypair, slot, "blk_a2", chain_a);
1643
1644 let de_same =
1646 Denunciation::try_from((&e_a1, &e_a2, chain_a)).expect("same-chain denunciation");
1647 assert!(de_same.is_valid_with_chain(chain_a));
1648 assert!(!de_same.is_valid_with_chain(chain_b));
1650
1651 let e_b2 = make_endorsement(&keypair, slot, "blk_b2", chain_b);
1653
1654 let de_cross = Denunciation::try_from((&e_a1, &e_b2, chain_a));
1657 assert!(de_cross.is_err(), "cross-chain denunciation must not build");
1658 }
1659
1660 fn make_header(
1661 keypair: &KeyPair,
1662 slot: Slot,
1663 merkle: &str,
1664 chain_id: u64,
1665 ) -> crate::block_header::SecuredHeader {
1666 crate::block_header::BlockHeader::new_verifiable(
1667 crate::block_header::BlockHeader {
1668 current_version: 0,
1669 announced_version: None,
1670 slot,
1671 parents: Vec::new(),
1672 operation_merkle_root: Hash::compute_from(merkle.as_bytes()),
1673 endorsements: Vec::new(),
1674 denunciations: Vec::new(),
1675 },
1676 crate::block_header::BlockHeaderSerializer::new(),
1677 keypair,
1678 chain_id,
1679 )
1680 .unwrap()
1681 }
1682
1683 #[test]
1684 fn test_block_header_denunciation_cross_chain_rejected() {
1685 let keypair = KeyPair::generate(0).unwrap();
1686 let slot = Slot::new(3, 7);
1687 let chain_a: u64 = 77658377;
1688 let chain_b: u64 = 77658376;
1689
1690 let h_a1 = make_header(&keypair, slot, "hdr_a1", chain_a);
1691 let h_a2 = make_header(&keypair, slot, "hdr_a2", chain_a);
1692 let de_same =
1693 Denunciation::try_from((&h_a1, &h_a2, chain_a)).expect("same-chain header de");
1694 assert!(de_same.is_valid_with_chain(chain_a));
1695 assert!(!de_same.is_valid_with_chain(chain_b));
1697
1698 let h_b2 = make_header(&keypair, slot, "hdr_b2", chain_b);
1699 assert!(
1700 Denunciation::try_from((&h_a1, &h_b2, chain_a)).is_err(),
1701 "cross-chain header denunciation must not build"
1702 );
1703 }
1704}