1use std::{
6 collections::hash_map::DefaultHasher,
7 fmt::{Debug, Formatter},
8 hash::{Hash, Hasher},
9 sync::Arc,
10 time::{SystemTime, UNIX_EPOCH},
11};
12
13use byteorder::{BigEndian, ReadBytesExt};
14use fastcrypto::{error::FastCryptoResult, groups::bls12381, hash::HashFunction};
15use fastcrypto_threshold::dkg_v1;
16use iota_sdk_types::{
17 DenyRuleSet, Digest, MisbehaviorReportDigest, ObjectReference, SenderSignedTransaction,
18 TransactionDigest, crypto::IntentScope,
19};
20use once_cell::sync::OnceCell;
21use serde::{Deserialize, Serialize};
22use tracing::warn;
23
24use crate::{
25 attestation::{Attestation, AttestedTransaction},
26 base_types::{AuthorityName, ConciseableName},
27 crypto::{AuthoritySignature, DefaultHash, default_hash},
28 message_envelope::{Envelope, Message, VerifiedEnvelope},
29 messages_checkpoint::{CheckpointSequenceNumber, CheckpointSignatureMessage},
30 supported_protocol_versions::{
31 Chain, SupportedProtocolVersions, SupportedProtocolVersionsWithHashes,
32 },
33 transaction::{CertifiedTransaction, TransactionEnvelope},
34};
35
36#[derive(Serialize, Deserialize, Clone, Debug)]
37pub struct ConsensusTransaction {
38 pub tracking_id: [u8; 8],
42 pub kind: ConsensusTransactionKind,
43}
44
45#[derive(Serialize, Deserialize, Clone, Hash, PartialEq, Eq, Ord, PartialOrd)]
46pub enum ConsensusTransactionKey {
47 Certificate(TransactionDigest),
48 CheckpointSignature(AuthorityName, CheckpointSequenceNumber),
49 EndOfPublish(AuthorityName),
50 CapabilityNotification(AuthorityName, u64 ),
51 #[deprecated(note = "Authenticator state (JWK) is deprecated and was never enabled on IOTA")]
52 NewJWKFetchedDeprecated,
53 RandomnessDkgMessage(AuthorityName),
54 RandomnessDkgConfirmation(AuthorityName),
55 MisbehaviorReport(
56 AuthorityName,
57 MisbehaviorReportDigest,
58 CheckpointSequenceNumber,
59 ),
60 UserTransaction(TransactionDigest),
62 OverloadNotificationV1(AuthorityName, u64 ),
63 TransactionDenyRuleProposal(AuthorityName, u64 ),
64 }
67
68impl Debug for ConsensusTransactionKey {
69 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
70 match self {
71 Self::Certificate(digest) => write!(f, "Certificate({digest})"),
72 Self::CheckpointSignature(name, seq) => {
73 write!(f, "CheckpointSignature({:?}, {:?})", name.concise(), seq)
74 }
75 Self::EndOfPublish(name) => write!(f, "EndOfPublish({:?})", name.concise()),
76 Self::CapabilityNotification(name, generation) => write!(
77 f,
78 "CapabilityNotification({:?}, {:?})",
79 name.concise(),
80 generation
81 ),
82 #[allow(deprecated)]
83 Self::NewJWKFetchedDeprecated => {
84 write!(
85 f,
86 "NewJWKFetched(deprecated: Authenticator state (JWK) is deprecated and was never enabled on IOTA)"
87 )
88 }
89 Self::RandomnessDkgMessage(name) => {
90 write!(f, "RandomnessDkgMessage({:?})", name.concise())
91 }
92 Self::RandomnessDkgConfirmation(name) => {
93 write!(f, "RandomnessDkgConfirmation({:?})", name.concise())
94 }
95 Self::MisbehaviorReport(name, digest, checkpoint_seq) => {
96 write!(
97 f,
98 "MisbehaviorReport({:?}, {:?}, {:?})",
99 name.concise(),
100 digest,
101 checkpoint_seq
102 )
103 }
104 Self::UserTransaction(digest) => write!(f, "UserTransaction({digest:?})"),
105 Self::OverloadNotificationV1(name, generation) => {
106 write!(
107 f,
108 "OverloadNotificationV1({:?}, gen={generation:?})",
109 name.concise()
110 )
111 }
112 Self::TransactionDenyRuleProposal(name, generation) => {
113 write!(
114 f,
115 "TransactionDenyRuleProposal({:?}, gen={generation:?})",
116 name.concise()
117 )
118 }
119 }
120 }
121}
122
123pub type SignedAuthorityCapabilitiesV1 = Envelope<AuthorityCapabilitiesV1, AuthoritySignature>;
124
125pub type VerifiedAuthorityCapabilitiesV1 =
126 VerifiedEnvelope<AuthorityCapabilitiesV1, AuthoritySignature>;
127
128#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
129pub struct AuthorityCapabilitiesDigest(Digest);
130
131impl AuthorityCapabilitiesDigest {
132 pub const fn new(digest: [u8; 32]) -> Self {
133 Self(Digest::new(digest))
134 }
135}
136
137impl Debug for AuthorityCapabilitiesDigest {
138 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
139 f.debug_tuple("AuthorityCapabilitiesDigest")
140 .field(&self.0)
141 .finish()
142 }
143}
144
145#[derive(Serialize, Deserialize, Clone, Hash)]
148pub struct AuthorityCapabilitiesV1 {
149 pub authority: AuthorityName,
152 pub generation: u64,
159
160 pub supported_protocol_versions: SupportedProtocolVersionsWithHashes,
163
164 pub available_system_packages: Vec<ObjectReference>,
168}
169
170impl Message for AuthorityCapabilitiesV1 {
171 type DigestType = AuthorityCapabilitiesDigest;
172 const SCOPE: IntentScope = IntentScope::AuthorityCapabilities;
173
174 fn digest(&self) -> Self::DigestType {
175 let mut hasher = DefaultHash::new();
177 let serialized = bcs::to_bytes(&self).expect("BCS should not fail");
178 hasher.update(&serialized);
179 AuthorityCapabilitiesDigest::new(<[u8; 32]>::from(hasher.finalize()))
180 }
181}
182
183impl Debug for AuthorityCapabilitiesV1 {
184 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
185 f.debug_struct("AuthorityCapabilities")
186 .field("authority", &self.authority.concise())
187 .field("generation", &self.generation)
188 .field(
189 "supported_protocol_versions",
190 &self.supported_protocol_versions,
191 )
192 .field("available_system_packages", &self.available_system_packages)
193 .finish()
194 }
195}
196
197impl AuthorityCapabilitiesV1 {
198 pub fn new(
199 authority: AuthorityName,
200 chain: Chain,
201 supported_protocol_versions: SupportedProtocolVersions,
202 available_system_packages: Vec<ObjectReference>,
203 ) -> Self {
204 let generation = SystemTime::now()
205 .duration_since(UNIX_EPOCH)
206 .expect("IOTA did not exist prior to 1970")
207 .as_millis()
208 .try_into()
209 .expect("This build of iota is not supported in the year 500,000,000");
210 Self {
211 authority,
212 generation,
213 supported_protocol_versions:
214 SupportedProtocolVersionsWithHashes::from_supported_versions(
215 supported_protocol_versions,
216 chain,
217 ),
218 available_system_packages,
219 }
220 }
221}
222
223impl SignedAuthorityCapabilitiesV1 {
224 pub fn cache_digest(&self, epoch: u64) -> AuthorityCapabilitiesDigest {
228 let signed_data_with_epoch = (self.data(), self.auth_sig(), epoch);
229
230 let mut hasher = DefaultHash::new();
232 let serialized = bcs::to_bytes(&signed_data_with_epoch).expect("BCS should not fail");
233 hasher.update(&serialized);
234 AuthorityCapabilitiesDigest::new(<[u8; 32]>::from(hasher.finalize()))
235 }
236}
237
238#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
245pub struct TransactionDenyRuleProposal {
246 pub authority: AuthorityName,
248 pub generation: u64,
251 pub proposed_rules: DenyRuleSet,
253}
254
255impl TransactionDenyRuleProposal {
256 pub fn new(
261 authority: AuthorityName,
262 proposed_rules: DenyRuleSet,
263 last_generation: Option<u64>,
264 ) -> Self {
265 let now: u64 = SystemTime::now()
266 .duration_since(UNIX_EPOCH)
267 .expect("IOTA did not exist prior to 1970")
268 .as_millis()
269 .try_into()
270 .expect("This build of iota is not supported in the year 500,000,000");
271 Self {
272 authority,
273 generation: now.max(last_generation.map_or(0, |g| g.saturating_add(1))),
274 proposed_rules,
275 }
276 }
277}
278
279#[derive(Serialize, Deserialize, Clone, Debug)]
280pub enum ConsensusTransactionKind {
281 CertifiedTransaction(Box<CertifiedTransaction>),
282 CheckpointSignature(Box<CheckpointSignatureMessage>),
283 EndOfPublish(AuthorityName),
284
285 CapabilityNotificationV1(AuthorityCapabilitiesV1),
286 SignedCapabilityNotificationV1(SignedAuthorityCapabilitiesV1),
287
288 #[deprecated(note = "Authenticator state (JWK) is deprecated and was never enabled on IOTA")]
289 NewJWKFetchedDeprecated,
290
291 RandomnessDkgMessage(AuthorityName, Vec<u8>),
295 RandomnessDkgConfirmation(AuthorityName, Vec<u8>),
299 MisbehaviorReport(VersionedMisbehaviorReport),
300 UserTransactionV1(Box<AttestedTransaction>),
304 OverloadNotificationV1(
305 AuthorityName,
306 u64, u8, ),
309 TransactionDenyRuleProposal(TransactionDenyRuleProposal),
313 }
316
317impl ConsensusTransactionKind {
318 fn map_cert_or_raw_user_tx<'a, R>(
325 &'a self,
326 certified: impl FnOnce(&'a CertifiedTransaction) -> R,
327 raw: impl FnOnce(&'a TransactionEnvelope) -> R,
328 ) -> Option<R> {
329 match self {
330 Self::CertifiedTransaction(c) => Some(certified(c)),
331 Self::UserTransactionV1(t) => Some(raw(&t.transaction)),
332 Self::CheckpointSignature(_)
333 | Self::EndOfPublish(_)
334 | Self::CapabilityNotificationV1(_)
335 | Self::SignedCapabilityNotificationV1(_)
336 | Self::RandomnessDkgMessage(..)
337 | Self::RandomnessDkgConfirmation(..)
338 | Self::MisbehaviorReport(_)
339 | Self::OverloadNotificationV1(..)
340 | Self::TransactionDenyRuleProposal(_) => None,
341 #[allow(deprecated)]
342 Self::NewJWKFetchedDeprecated => None,
343 }
344 }
345
346 pub fn as_sender_signed_transaction(&self) -> Option<&SenderSignedTransaction> {
349 self.map_cert_or_raw_user_tx(|c| c.data(), |t| t.data())
350 }
351
352 pub fn transaction_digest(&self) -> Option<TransactionDigest> {
355 self.map_cert_or_raw_user_tx(|c| *c.digest(), |t| *t.digest())
356 }
357
358 pub fn as_user_transaction_with_attestation(
362 &self,
363 ) -> Option<(&TransactionEnvelope, Option<&Attestation>)> {
364 match self {
365 Self::UserTransactionV1(t) => Some((&t.transaction, t.attestation.as_ref())),
366 Self::CertifiedTransaction(_)
367 | Self::CheckpointSignature(_)
368 | Self::EndOfPublish(_)
369 | Self::CapabilityNotificationV1(_)
370 | Self::SignedCapabilityNotificationV1(_)
371 | Self::RandomnessDkgMessage(..)
372 | Self::RandomnessDkgConfirmation(..)
373 | Self::MisbehaviorReport(_)
374 | Self::OverloadNotificationV1(..)
375 | Self::TransactionDenyRuleProposal(_) => None,
376 #[allow(deprecated)]
377 Self::NewJWKFetchedDeprecated => None,
378 }
379 }
380
381 pub fn as_user_transaction(&self) -> Option<&TransactionEnvelope> {
385 self.as_user_transaction_with_attestation().map(|(t, _)| t)
386 }
387
388 pub fn is_user_transaction(&self) -> bool {
392 self.as_user_transaction().is_some()
393 }
394
395 pub fn is_dkg(&self) -> bool {
398 match self {
399 Self::RandomnessDkgMessage(_, _) | Self::RandomnessDkgConfirmation(_, _) => true,
400 Self::UserTransactionV1(_)
401 | Self::CertifiedTransaction(_)
402 | Self::CheckpointSignature(_)
403 | Self::EndOfPublish(_)
404 | Self::CapabilityNotificationV1(_)
405 | Self::SignedCapabilityNotificationV1(_)
406 | Self::MisbehaviorReport(_)
407 | Self::OverloadNotificationV1(..)
408 | Self::TransactionDenyRuleProposal(_) => false,
409 #[allow(deprecated)]
410 Self::NewJWKFetchedDeprecated => false,
411 }
412 }
413}
414
415#[derive(Debug, Clone, Serialize, Deserialize)]
425pub struct VersionedMisbehaviorReport {
426 pub authority: AuthorityName,
429 pub payload: MisbehaviorObservations,
431 pub generation: u64,
435 #[serde(skip)]
436 digest: OnceCell<MisbehaviorReportDigest>,
437}
438
439#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
445pub enum MisbehaviorObservations {
446 V1(MisbehaviorObservationsV1),
447 V2(MisbehaviorObservationsV2),
448}
449
450impl MisbehaviorObservations {
451 pub fn verify(&self, committee_size: usize) -> bool {
453 match self {
454 Self::V1(payload) => payload.verify(committee_size),
455 Self::V2(payload) => payload.verify(committee_size),
456 }
457 }
458}
459
460impl VersionedMisbehaviorReport {
461 pub fn new_v1(
462 authority: AuthorityName,
463 generation: u64,
464 observations: MisbehaviorObservationsV1,
465 ) -> Self {
466 Self {
467 authority,
468 payload: MisbehaviorObservations::V1(observations),
469 generation,
470 digest: OnceCell::new(),
471 }
472 }
473
474 pub fn new_v2(
475 authority: AuthorityName,
476 generation: u64,
477 observations: MisbehaviorObservationsV2,
478 ) -> Self {
479 Self {
480 authority,
481 payload: MisbehaviorObservations::V2(observations),
482 generation,
483 digest: OnceCell::new(),
484 }
485 }
486
487 pub fn digest(&self) -> &MisbehaviorReportDigest {
490 self.digest
491 .get_or_init(|| MisbehaviorReportDigest::new(default_hash(self)))
492 }
493
494 pub fn summary(&self) -> u64 {
497 let summary = match &self.payload {
498 MisbehaviorObservations::V1(report) => [
499 &report.faulty_blocks_provable,
500 &report.faulty_blocks_unprovable,
501 &report.missing_proposals,
502 &report.equivocations,
503 ]
504 .into_iter()
505 .flatten()
506 .fold(0u64, |acc, metric| acc.saturating_add(*metric)),
507 MisbehaviorObservations::V2(report) => [
508 &report.faulty_blocks_provable,
509 &report.faulty_blocks_unprovable,
510 &report.missing_proposals,
511 &report.equivocations,
512 &report.invalid_bundle_parts,
513 ]
514 .into_iter()
515 .flatten()
516 .fold(0u64, |acc, metric| acc.saturating_add(*metric)),
517 };
518 if summary == u64::MAX {
519 warn!("MisbehaviorReport summary reached its maximum value.");
520 }
521 summary
522 }
523}
524
525#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
531pub struct MisbehaviorObservationsV1 {
532 pub faulty_blocks_provable: Vec<u64>,
533 pub faulty_blocks_unprovable: Vec<u64>,
534 pub missing_proposals: Vec<u64>,
535 pub equivocations: Vec<u64>,
538}
539
540impl MisbehaviorObservationsV1 {
541 pub fn verify(&self, committee_size: usize) -> bool {
542 self.faulty_blocks_provable.len() == committee_size
550 && self.faulty_blocks_unprovable.len() == committee_size
551 && self.equivocations.len() == committee_size
552 && self.missing_proposals.len() == committee_size
553 }
554}
555
556#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
561pub struct MisbehaviorObservationsV2 {
562 pub faulty_blocks_provable: Vec<u64>,
563 pub faulty_blocks_unprovable: Vec<u64>,
564 pub missing_proposals: Vec<u64>,
565 pub equivocations: Vec<u64>,
568 pub invalid_bundle_parts: Vec<u64>,
569}
570
571impl MisbehaviorObservationsV2 {
572 pub fn verify(&self, committee_size: usize) -> bool {
573 self.faulty_blocks_provable.len() == committee_size
574 && self.faulty_blocks_unprovable.len() == committee_size
575 && self.missing_proposals.len() == committee_size
576 && self.equivocations.len() == committee_size
577 && self.invalid_bundle_parts.len() == committee_size
578 }
579}
580
581#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
582pub enum VersionedDkgMessage {
583 V1(dkg_v1::Message<bls12381::G2Element, bls12381::G2Element>),
584}
585
586#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
587pub enum VersionedDkgConfirmation {
588 V1(dkg_v1::Confirmation<bls12381::G2Element>),
589}
590
591impl Debug for VersionedDkgMessage {
592 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
593 match self {
594 VersionedDkgMessage::V1(msg) => write!(
595 f,
596 "DKG V1 Message with sender={}, vss_pk.degree={}, encrypted_shares.len()={}",
597 msg.sender,
598 msg.vss_pk.degree(),
599 msg.encrypted_shares.len(),
600 ),
601 }
602 }
603}
604
605impl VersionedDkgMessage {
606 pub fn sender(&self) -> u16 {
607 match self {
608 VersionedDkgMessage::V1(msg) => msg.sender,
609 }
610 }
611
612 pub fn create(
613 dkg_version: u64,
614 party: Arc<dkg_v1::Party<bls12381::G2Element, bls12381::G2Element>>,
615 ) -> FastCryptoResult<VersionedDkgMessage> {
616 assert_eq!(dkg_version, 1, "BUG: invalid DKG version");
617 let msg = party.create_message(&mut rand08::thread_rng())?;
618 Ok(VersionedDkgMessage::V1(msg))
619 }
620
621 pub fn unwrap_v1(self) -> dkg_v1::Message<bls12381::G2Element, bls12381::G2Element> {
622 match self {
623 VersionedDkgMessage::V1(msg) => msg,
624 }
625 }
626
627 pub fn is_valid_version(&self, dkg_version: u64) -> bool {
628 matches!((self, dkg_version), (VersionedDkgMessage::V1(_), 1))
629 }
630}
631
632impl VersionedDkgConfirmation {
633 pub fn sender(&self) -> u16 {
634 match self {
635 VersionedDkgConfirmation::V1(msg) => msg.sender,
636 }
637 }
638
639 pub fn num_of_complaints(&self) -> usize {
640 match self {
641 VersionedDkgConfirmation::V1(msg) => msg.complaints.len(),
642 }
643 }
644
645 pub fn unwrap_v1(&self) -> &dkg_v1::Confirmation<bls12381::G2Element> {
646 match self {
647 VersionedDkgConfirmation::V1(msg) => msg,
648 }
649 }
650
651 pub fn is_valid_version(&self, dkg_version: u64) -> bool {
652 matches!((self, dkg_version), (VersionedDkgConfirmation::V1(_), 1))
653 }
654}
655
656impl ConsensusTransaction {
657 pub fn new_certificate_message(
658 authority: &AuthorityName,
659 certificate: CertifiedTransaction,
660 ) -> Self {
661 let mut hasher = DefaultHasher::new();
662 let tx_digest = certificate.digest();
663 tx_digest.hash(&mut hasher);
664 authority.hash(&mut hasher);
665 let tracking_id = hasher.finish().to_le_bytes();
666 Self {
667 tracking_id,
668 kind: ConsensusTransactionKind::CertifiedTransaction(Box::new(certificate)),
669 }
670 }
671
672 pub fn new_checkpoint_signature_message(data: CheckpointSignatureMessage) -> Self {
673 let mut hasher = DefaultHasher::new();
674 data.summary.auth_sig().signature.hash(&mut hasher);
675 let tracking_id = hasher.finish().to_le_bytes();
676 Self {
677 tracking_id,
678 kind: ConsensusTransactionKind::CheckpointSignature(Box::new(data)),
679 }
680 }
681
682 pub fn new_end_of_publish(authority: AuthorityName) -> Self {
683 let mut hasher = DefaultHasher::new();
684 authority.hash(&mut hasher);
685 let tracking_id = hasher.finish().to_le_bytes();
686 Self {
687 tracking_id,
688 kind: ConsensusTransactionKind::EndOfPublish(authority),
689 }
690 }
691
692 pub fn new_capability_notification_v1(capabilities: AuthorityCapabilitiesV1) -> Self {
693 let mut hasher = DefaultHasher::new();
694 capabilities.hash(&mut hasher);
695 let tracking_id = hasher.finish().to_le_bytes();
696 Self {
697 tracking_id,
698 kind: ConsensusTransactionKind::CapabilityNotificationV1(capabilities),
699 }
700 }
701
702 pub fn new_signed_capability_notification_v1(
703 signed_capabilities: SignedAuthorityCapabilitiesV1,
704 ) -> Self {
705 let mut hasher = DefaultHasher::new();
706 signed_capabilities.data().hash(&mut hasher);
707 signed_capabilities.auth_sig().hash(&mut hasher);
708 let tracking_id = hasher.finish().to_le_bytes();
709 Self {
710 tracking_id,
711 kind: ConsensusTransactionKind::SignedCapabilityNotificationV1(signed_capabilities),
712 }
713 }
714
715 pub fn new_randomness_dkg_message(
716 authority: AuthorityName,
717 versioned_message: &VersionedDkgMessage,
718 ) -> Self {
719 let message =
720 bcs::to_bytes(versioned_message).expect("message serialization should not fail");
721 let mut hasher = DefaultHasher::new();
722 message.hash(&mut hasher);
723 let tracking_id = hasher.finish().to_le_bytes();
724 Self {
725 tracking_id,
726 kind: ConsensusTransactionKind::RandomnessDkgMessage(authority, message),
727 }
728 }
729 pub fn new_randomness_dkg_confirmation(
730 authority: AuthorityName,
731 versioned_confirmation: &VersionedDkgConfirmation,
732 ) -> Self {
733 let confirmation =
734 bcs::to_bytes(versioned_confirmation).expect("message serialization should not fail");
735 let mut hasher = DefaultHasher::new();
736 confirmation.hash(&mut hasher);
737 let tracking_id = hasher.finish().to_le_bytes();
738 Self {
739 tracking_id,
740 kind: ConsensusTransactionKind::RandomnessDkgConfirmation(authority, confirmation),
741 }
742 }
743
744 pub fn new_misbehavior_report(report: VersionedMisbehaviorReport) -> Self {
745 let serialized_report =
746 bcs::to_bytes(&report).expect("report serialization should not fail");
747 let mut hasher = DefaultHasher::new();
748 serialized_report.hash(&mut hasher);
749 let tracking_id = hasher.finish().to_le_bytes();
750 Self {
751 tracking_id,
752 kind: ConsensusTransactionKind::MisbehaviorReport(report),
753 }
754 }
755
756 pub fn new_user_transaction(transaction: TransactionEnvelope) -> Self {
757 let mut hasher = DefaultHasher::new();
758 let tx_digest = transaction.digest();
759 tx_digest.hash(&mut hasher);
760 let tracking_id = hasher.finish().to_le_bytes();
761 Self {
762 tracking_id,
763 kind: ConsensusTransactionKind::UserTransactionV1(Box::new(AttestedTransaction::new(
764 transaction,
765 None,
766 ))),
767 }
768 }
769
770 pub fn new_overload_notification_v1(
771 authority: AuthorityName,
772 load_shedding_percentage: u8,
773 ) -> Self {
774 let generation: u64 = SystemTime::now()
781 .duration_since(UNIX_EPOCH)
782 .expect("IOTA did not exist prior to 1970")
783 .as_millis()
784 .try_into()
785 .expect("This build of iota is not supported in the year 500,000,000");
786 let mut hasher = DefaultHasher::new();
787 authority.hash(&mut hasher);
788 generation.hash(&mut hasher);
789 load_shedding_percentage.hash(&mut hasher);
790 let tracking_id = hasher.finish().to_le_bytes();
791 Self {
792 tracking_id,
793 kind: ConsensusTransactionKind::OverloadNotificationV1(
794 authority,
795 generation,
796 load_shedding_percentage,
797 ),
798 }
799 }
800
801 pub fn new_transaction_deny_rule_proposal(proposal: TransactionDenyRuleProposal) -> Self {
802 let mut hasher = DefaultHasher::new();
803 proposal.hash(&mut hasher);
804 let tracking_id = hasher.finish().to_le_bytes();
805 Self {
806 tracking_id,
807 kind: ConsensusTransactionKind::TransactionDenyRuleProposal(proposal),
808 }
809 }
810
811 pub fn new_attested_user_transaction(attested_tx: AttestedTransaction) -> Self {
812 let mut hasher = DefaultHasher::new();
813 attested_tx.digest().hash(&mut hasher);
814 let tracking_id = hasher.finish().to_le_bytes();
815 Self {
816 tracking_id,
817 kind: ConsensusTransactionKind::UserTransactionV1(Box::new(attested_tx)),
818 }
819 }
820
821 pub fn get_tracking_id(&self) -> u64 {
822 (&self.tracking_id[..])
823 .read_u64::<BigEndian>()
824 .unwrap_or_default()
825 }
826
827 pub fn key(&self) -> ConsensusTransactionKey {
828 match &self.kind {
829 ConsensusTransactionKind::CertifiedTransaction(cert) => {
830 ConsensusTransactionKey::Certificate(*cert.digest())
831 }
832 ConsensusTransactionKind::CheckpointSignature(data) => {
833 ConsensusTransactionKey::CheckpointSignature(
834 data.summary.auth_sig().authority,
835 data.summary.sequence_number,
836 )
837 }
838 ConsensusTransactionKind::EndOfPublish(authority) => {
839 ConsensusTransactionKey::EndOfPublish(*authority)
840 }
841 ConsensusTransactionKind::CapabilityNotificationV1(cap) => {
842 ConsensusTransactionKey::CapabilityNotification(cap.authority, cap.generation)
843 }
844 ConsensusTransactionKind::SignedCapabilityNotificationV1(signed_cap) => {
845 ConsensusTransactionKey::CapabilityNotification(
846 signed_cap.authority,
847 signed_cap.generation,
848 )
849 }
850
851 #[allow(deprecated)]
852 ConsensusTransactionKind::NewJWKFetchedDeprecated => {
853 ConsensusTransactionKey::NewJWKFetchedDeprecated
854 }
855 ConsensusTransactionKind::RandomnessDkgMessage(authority, _) => {
856 ConsensusTransactionKey::RandomnessDkgMessage(*authority)
857 }
858 ConsensusTransactionKind::RandomnessDkgConfirmation(authority, _) => {
859 ConsensusTransactionKey::RandomnessDkgConfirmation(*authority)
860 }
861 ConsensusTransactionKind::MisbehaviorReport(report) => {
862 ConsensusTransactionKey::MisbehaviorReport(
863 report.authority,
864 *report.digest(),
865 report.generation,
866 )
867 }
868 ConsensusTransactionKind::UserTransactionV1(tx) => {
869 ConsensusTransactionKey::UserTransaction(*tx.digest())
870 }
871 ConsensusTransactionKind::OverloadNotificationV1(authority, generation, _) => {
872 ConsensusTransactionKey::OverloadNotificationV1(*authority, *generation)
873 }
874 ConsensusTransactionKind::TransactionDenyRuleProposal(proposal) => {
875 ConsensusTransactionKey::TransactionDenyRuleProposal(
876 proposal.authority,
877 proposal.generation,
878 )
879 }
880 }
881 }
882
883 pub fn is_user_certificate(&self) -> bool {
884 matches!(self.kind, ConsensusTransactionKind::CertifiedTransaction(_))
885 }
886
887 pub fn is_end_of_publish(&self) -> bool {
888 matches!(self.kind, ConsensusTransactionKind::EndOfPublish(_))
889 }
890}
891
892#[cfg(test)]
893mod tests {
894 use super::*;
895
896 #[derive(Serialize)]
900 struct LegacyVersionedMisbehaviorReport<'a> {
901 payload: &'a MisbehaviorObservations,
902 }
903
904 fn sample_payload() -> MisbehaviorObservations {
905 MisbehaviorObservations::V1(MisbehaviorObservationsV1 {
906 faulty_blocks_provable: vec![1, 2, 3],
907 faulty_blocks_unprovable: vec![4, 5, 6],
908 missing_proposals: vec![7, 8, 9],
909 equivocations: vec![10, 11, 12],
910 })
911 }
912
913 #[test]
921 fn misbehavior_report_wire_format_unchanged() {
922 let authority = AuthorityName::default();
923 let generation: u64 = 42;
924 let payload = sample_payload();
925
926 let legacy_bytes = bcs::to_bytes(&(
927 authority,
928 LegacyVersionedMisbehaviorReport { payload: &payload },
929 generation,
930 ))
931 .unwrap();
932
933 let new = VersionedMisbehaviorReport {
934 authority,
935 payload,
936 generation,
937 digest: OnceCell::new(),
938 };
939 let new_bytes = bcs::to_bytes(&new).unwrap();
940
941 assert_eq!(
942 legacy_bytes, new_bytes,
943 "VersionedMisbehaviorReport wire format must not change — testnet is live"
944 );
945 }
946
947 #[test]
951 fn misbehavior_observations_v2_wire_format() {
952 let payload = MisbehaviorObservations::V2(MisbehaviorObservationsV2 {
953 faulty_blocks_provable: vec![1, 2, 3],
954 faulty_blocks_unprovable: vec![4, 5, 6],
955 missing_proposals: vec![7, 8, 9],
956 equivocations: vec![10, 11, 12],
957 invalid_bundle_parts: vec![13, 14, 15],
958 });
959
960 let mut expected = vec![1u8];
961 expected.extend(
962 bcs::to_bytes(&(
963 vec![1u64, 2, 3],
964 vec![4u64, 5, 6],
965 vec![7u64, 8, 9],
966 vec![10u64, 11, 12],
967 vec![13u64, 14, 15],
968 ))
969 .unwrap(),
970 );
971
972 assert_eq!(
973 bcs::to_bytes(&payload).unwrap(),
974 expected,
975 "MisbehaviorObservations::V2 wire format must not change"
976 );
977 }
978
979 #[test]
986 fn misbehavior_report_consensus_kind_wire_format_unchanged() {
987 let authority = AuthorityName::default();
988 let generation: u64 = 7;
989 let payload = sample_payload();
990
991 let new_kind = ConsensusTransactionKind::MisbehaviorReport(VersionedMisbehaviorReport {
992 authority,
993 payload: payload.clone(),
994 generation,
995 digest: OnceCell::new(),
996 });
997 let new_bytes = bcs::to_bytes(&new_kind).unwrap();
998
999 let mut legacy_bytes = vec![8u8];
1002 legacy_bytes.extend(
1003 bcs::to_bytes(&(
1004 authority,
1005 LegacyVersionedMisbehaviorReport { payload: &payload },
1006 generation,
1007 ))
1008 .unwrap(),
1009 );
1010
1011 assert_eq!(
1012 legacy_bytes, new_bytes,
1013 "ConsensusTransactionKind::MisbehaviorReport wire format must not change — testnet is live"
1014 );
1015 }
1016
1017 #[test]
1022 fn deny_rule_proposal_consensus_kind_wire_format_unchanged() {
1023 use iota_sdk_types::{Address, DenyRuleSet, ObjectId};
1024
1025 let authority = AuthorityName::default();
1026 let address = Address::new([7u8; 32]);
1027 let object = ObjectId::new([8u8; 32]);
1028 let package = ObjectId::new([9u8; 32]);
1029
1030 for hot in 0..6usize {
1034 let switch = |i: usize| i == hot;
1035 let proposal = TransactionDenyRuleProposal {
1036 authority,
1037 generation: 42,
1038 proposed_rules: DenyRuleSet {
1039 denied_addresses: [address].into(),
1040 denied_objects: [object].into(),
1041 denied_packages: [package].into(),
1042 package_publish_disabled: switch(0),
1043 package_upgrade_disabled: switch(1),
1044 shared_object_disabled: switch(2),
1045 user_transaction_disabled: switch(3),
1046 receiving_objects_disabled: switch(4),
1047 move_authenticator_disabled: switch(5),
1048 },
1049 };
1050 let new_bytes = bcs::to_bytes(&ConsensusTransactionKind::TransactionDenyRuleProposal(
1051 proposal,
1052 ))
1053 .unwrap();
1054
1055 let mut legacy_bytes = vec![11u8];
1056 legacy_bytes.extend(
1057 bcs::to_bytes(&(
1058 authority,
1059 42u64,
1060 (
1061 vec![address],
1062 vec![object],
1063 vec![package],
1064 switch(0), switch(1), switch(2), switch(3), switch(4), switch(5), ),
1071 ))
1072 .unwrap(),
1073 );
1074
1075 assert_eq!(
1076 legacy_bytes, new_bytes,
1077 "ConsensusTransactionKind::TransactionDenyRuleProposal wire format must not \
1078 change (switch {hot})"
1079 );
1080 }
1081 }
1082
1083 #[test]
1085 fn deny_rule_proposal_bcs_round_trip() {
1086 use iota_sdk_types::{Address, DenyRuleSet, ObjectId};
1087
1088 let proposal = TransactionDenyRuleProposal {
1089 authority: AuthorityName::default(),
1090 generation: 42,
1091 proposed_rules: DenyRuleSet {
1092 denied_addresses: [Address::new([1u8; 32])].into(),
1093 denied_objects: [ObjectId::new([2u8; 32])].into(),
1094 denied_packages: [ObjectId::new([3u8; 32])].into(),
1095 package_publish_disabled: true,
1096 shared_object_disabled: true,
1097 receiving_objects_disabled: true,
1098 ..Default::default()
1099 },
1100 };
1101 let bytes = bcs::to_bytes(&proposal).unwrap();
1102 assert_eq!(proposal, bcs::from_bytes(&bytes).unwrap());
1103 }
1104
1105 #[test]
1108 fn proposal_generation_supersedes_last_generation() {
1109 use iota_sdk_types::DenyRuleSet;
1110
1111 let authority = AuthorityName::default();
1112 let fresh = TransactionDenyRuleProposal::new(authority, DenyRuleSet::default(), None);
1113 assert!(fresh.generation > 0);
1114
1115 let far_future = fresh.generation + 1_000_000_000;
1116 let successor =
1117 TransactionDenyRuleProposal::new(authority, DenyRuleSet::default(), Some(far_future));
1118 assert_eq!(successor.generation, far_future + 1);
1119 }
1120}