Skip to main content

iota_types/
messages_consensus.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5use 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    /// Encodes an u64 unique tracking id to allow us trace a message between
39    /// IOTA and consensus. Use an byte array instead of u64 to ensure stable
40    /// serialization.
41    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 /* generation */),
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    /// P-COOL user transaction key (by transaction digest).
61    UserTransaction(TransactionDigest),
62    OverloadNotificationV1(AuthorityName, u64 /* generation */),
63    TransactionDenyRuleProposal(AuthorityName, u64 /* generation */),
64    // New entries should be added at the end to preserve serialization compatibility. DO NOT
65    // CHANGE THE ORDER OF EXISTING ENTRIES!
66}
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/// Used to advertise capabilities of each authority via consensus. This allows
146/// validators to negotiate the creation of the ChangeEpoch transaction.
147#[derive(Serialize, Deserialize, Clone, Hash)]
148pub struct AuthorityCapabilitiesV1 {
149    /// Originating authority - must match transaction source authority from
150    /// consensus or the signature of a non-committee active validator.
151    pub authority: AuthorityName,
152    /// Generation number set by sending authority. Used to determine which of
153    /// multiple AuthorityCapabilities messages from the same authority is
154    /// the most recent.
155    ///
156    /// (Currently, we just set this to the current time in milliseconds since
157    /// the epoch, but this should not be interpreted as a timestamp.)
158    pub generation: u64,
159
160    /// ProtocolVersions that the authority supports, including the hash of the
161    /// serialized ProtocolConfig of that authority per version.
162    pub supported_protocol_versions: SupportedProtocolVersionsWithHashes,
163
164    /// The ObjectRefs of all versions of system packages that the validator
165    /// possesses. Used to determine whether to do a framework/movestdlib
166    /// upgrade.
167    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        // Ensure deterministic serialization for digest
176        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    /// Key under which a successful signature verification of this message is
225    /// cached. Covers the signature, so a cache hit never vouches for a
226    /// signature that was not itself verified.
227    pub fn cache_digest(&self, epoch: u64) -> AuthorityCapabilitiesDigest {
228        let signed_data_with_epoch = (self.data(), self.auth_sig(), epoch);
229
230        // Ensure deterministic serialization for digest
231        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/// A validator's full-state proposal for the network transaction deny rules,
239/// announced through consensus.
240///
241/// Each proposal carries the authority's complete proposed rule set; the latest
242/// generation per authority supersedes earlier ones. The active rule set the
243/// network enforces is the stake-weighted aggregate of all current proposals.
244#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
245pub struct TransactionDenyRuleProposal {
246    /// The authority announcing this proposal.
247    pub authority: AuthorityName,
248    /// Per-authority counter used to deduplicate proposals; a higher generation
249    /// supersedes earlier proposals from the same authority.
250    pub generation: u64,
251    /// The complete set of rules this authority proposes.
252    pub proposed_rules: DenyRuleSet,
253}
254
255impl TransactionDenyRuleProposal {
256    /// Creates a proposal with a wall-clock generation, so a resubmission
257    /// supersedes this authority's earlier proposals. Pass the generation of
258    /// this authority's currently recorded proposal (if any) so the new one
259    /// stays newer even after a backward wall-clock step.
260    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    // DKG is used to generate keys for use in the random beacon protocol.
292    // `RandomnessDkgMessage` is sent out at start-of-epoch to initiate the process.
293    // Contents are a serialized `fastcrypto_threshold::dkg::Message`.
294    RandomnessDkgMessage(AuthorityName, Vec<u8>),
295    // `RandomnessDkgConfirmation` is the second DKG message, sent as soon as a threshold amount
296    // of `RandomnessDkgMessages` have been received locally, to complete the key generation
297    // process. Contents are a serialized `fastcrypto_threshold::dkg::Confirmation`.
298    RandomnessDkgConfirmation(AuthorityName, Vec<u8>),
299    MisbehaviorReport(VersionedMisbehaviorReport),
300    /// P-COOL user transaction. Raw, uncertified transaction submitted
301    /// directly to consensus without pre-consensus object locking.
302    /// Conflicts are resolved post-consensus.
303    UserTransactionV1(Box<AttestedTransaction>),
304    OverloadNotificationV1(
305        AuthorityName,
306        u64, // generation
307        u8,  // percentage
308    ),
309    /// A validator's full-state deny rule proposal. Unsigned: the sender is
310    /// authenticated as the consensus block author and must match
311    /// `TransactionDenyRuleProposal::authority`.
312    TransactionDenyRuleProposal(TransactionDenyRuleProposal),
313    // New entries should be added at the end to preserve serialization compatibility. DO NOT
314    // CHANGE THE ORDER OF EXISTING ENTRIES!
315}
316
317impl ConsensusTransactionKind {
318    // NOTE: Keep every match in this impl exhaustive (no `_` arm) so a new
319    // `ConsensusTransactionKind` variant must be classified here rather
320    // than being silently mishandled.
321
322    /// Helper that applies the matching projection to the underlying certified
323    /// or raw user transaction, or `None` for internal consensus messages.
324    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    /// The signed transaction of the underlying certified or raw user
347    /// transaction, or `None` for internal consensus messages.
348    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    /// The (cached) transaction digest of the underlying certified or raw
353    /// user transaction, or `None` for internal consensus messages.
354    pub fn transaction_digest(&self) -> Option<TransactionDigest> {
355        self.map_cert_or_raw_user_tx(|c| *c.digest(), |t| *t.digest())
356    }
357
358    /// Returns the raw, uncertified user transaction together with its
359    /// attestation (`Some` when it was attested), or `None` for any other
360    /// kind. Certified user transactions are not included here.
361    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    /// Returns the raw, uncertified user transaction (`UserTransactionV1`)
382    /// submitted directly to consensus, or `None` for any other kind.
383    /// Certified user transactions are not included here.
384    pub fn as_user_transaction(&self) -> Option<&TransactionEnvelope> {
385        self.as_user_transaction_with_attestation().map(|(t, _)| t)
386    }
387
388    /// Returns `true` only for a raw, uncertified user transaction
389    /// (`UserTransactionV1`) submitted directly to consensus. Certified user
390    /// transactions are not included here.
391    pub fn is_user_transaction(&self) -> bool {
392        self.as_user_transaction().is_some()
393    }
394
395    /// Returns `true` for the randomness DKG messages
396    /// (`RandomnessDkgMessage` and `RandomnessDkgConfirmation`).
397    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/// A misbehavior report carrying a versioned payload plus a memoized digest.
416///
417/// Wire format is BCS over the `Serialize`-derived fields in declaration order:
418/// `authority || payload || generation`. This exactly matches the pre-refactor
419/// `ConsensusTransactionKind::MisbehaviorReport(AuthorityName,
420/// VersionedMisbehaviorReport { payload }, CheckpointSequenceNumber)` 3-tuple
421/// — see `tests::misbehavior_report_wire_format_unchanged` which pins the
422/// equivalence. Reordering or inserting any non-`skip` field here would change
423/// the consensus wire format and halt a running testnet.
424#[derive(Debug, Clone, Serialize, Deserialize)]
425pub struct VersionedMisbehaviorReport {
426    /// Originating authority — must match the transaction source authority
427    /// from consensus. Verified at the consensus boundary.
428    pub authority: AuthorityName,
429    /// Versioned payload of the misbehavior report.
430    pub payload: MisbehaviorObservations,
431    /// Generation number set by the sending authority. Used to identify the
432    /// most recent report from each authority. Currently set to the
433    /// checkpoint sequence number at which the report was generated.
434    pub generation: u64,
435    #[serde(skip)]
436    digest: OnceCell<MisbehaviorReportDigest>,
437}
438
439/// Versioned per-authority misbehavior observations. New variants get their
440/// own named-field payload type (`MisbehaviorObservationsV2`,
441/// `MisbehaviorObservationsV3`, ...) so the wire schema stays compile-time
442/// checked. Also serves as the in-memory representation in
443/// `MisbehaviorMonitor` / `ReportAggregator`.
444#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
445pub enum MisbehaviorObservations {
446    V1(MisbehaviorObservationsV1),
447    V2(MisbehaviorObservationsV2),
448}
449
450impl MisbehaviorObservations {
451    /// Verifies the payload shape against the committee size.
452    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    /// Returns the digest of the misbehavior report, caching it if it has not
488    /// been computed yet.
489    pub fn digest(&self) -> &MisbehaviorReportDigest {
490        self.digest
491            .get_or_init(|| MisbehaviorReportDigest::new(default_hash(self)))
492    }
493
494    /// Returns the summary of the misbehavior report, defined as the sum of all
495    /// metrics for all authorities.
496    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/// V1 misbehavior observations: per-authority counts for each tracked
526/// misbehavior category (faulty blocks, equivocations, missing proposals).
527/// Field order is part of the wire format — BCS serializes named struct
528/// fields in declaration order. This first version does not include any
529/// type of proof.
530#[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    /// Per-authority count of rounds in which the authority signed more than
536    /// one block header, however many extra headers each round held.
537    pub equivocations: Vec<u64>,
538}
539
540impl MisbehaviorObservationsV1 {
541    pub fn verify(&self, committee_size: usize) -> bool {
542        // This version of reports are valid as long as they contain the counts for all
543        // authorities. Future versions may contain proofs that need verification.
544        // However, since the validity of a proof is deeply coupled with the protocol
545        // version and the consensus mechanism being used, we cannot verify it here. In
546        // the future, reports should be unwrapped (or translated) to a type verifiable
547        // by the starfish crate, which means that the verification logic will probably
548        // move out of this crate.
549        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/// V2 misbehavior observations: the V1 categories plus a dedicated
557/// per-authority count of invalid bundle parts (counted under
558/// `faulty_blocks_unprovable` in the V1 format). Field order is part of the
559/// wire format — BCS serializes named struct fields in declaration order.
560#[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    /// Per-authority count of rounds in which the authority signed more than
566    /// one block header, however many extra headers each round held.
567    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        // Wall-clock millis-since-epoch is used purely as a unique-per-submission
775        // disambiguator in the consensus transaction key, mirroring
776        // `AuthorityCapabilitiesV1::new`, because `consensus_message_processed`
777        // dedups by key for the full epoch.
778        // The receive side uses the percentage value directly; the generation is only
779        // for key uniqueness, not for ordering (consensus already orders deliveries).
780        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    /// Pre-refactor wire shape of `VersionedMisbehaviorReport` — only `payload`
897    /// crossed the wire (the digest cache was `#[serde(skip)]`). Used to pin
898    /// post-refactor bytes against the legacy encoding.
899    #[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    /// Pins the BCS encoding of `VersionedMisbehaviorReport` against the
914    /// pre-refactor 3-tuple layout `(AuthorityName, { payload }, u64)`. Testnet
915    /// is running the legacy format; if the bytes ever drift, validators on
916    /// the new build will reject reports from validators on the old build (or
917    /// vice versa) and consensus halts. Reordering struct fields, adding a
918    /// non-`skip` field, or renaming a field's serde tag will all trip this
919    /// test.
920    #[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    /// Pins the BCS encoding of the `MisbehaviorObservations::V2` payload:
948    /// variant tag 1 (ULEB128 of the declaration index) followed by the five
949    /// per-authority vectors in declaration order.
950    #[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    /// `ConsensusTransactionKind::MisbehaviorReport`'s variant tag is its
980    /// position in the enum (BCS encodes enum variants as ULEB128 of the
981    /// declaration index). Reordering variants — even if the new wrapping
982    /// layout is byte-identical otherwise — would shift the tag and break
983    /// every node still on the old build. This test catches that and also
984    /// confirms the post-tag bytes equal the legacy 3-tuple encoding.
985    #[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        // Legacy encoding: variant tag (8 = position of MisbehaviorReport in
1000        // the enum, ULEB128 single byte) followed by the 3-tuple body.
1001        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    /// Pins `ConsensusTransactionKind::TransactionDenyRuleProposal`'s variant
1018    /// tag (11) and body layout: `(authority, generation, DenyRuleSet)`
1019    /// with the rule set's fields in declaration order. Reordering enum
1020    /// variants or `DenyRuleSet` fields breaks nodes on the old build.
1021    #[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        // Six one-hot switch patterns: a single sample can't pin the order of
1031        // equal-valued booleans, so pin each switch position separately. The
1032        // deny lists get distinct contents for the same reason.
1033        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), // package_publish_disabled
1065                        switch(1), // package_upgrade_disabled
1066                        switch(2), // shared_object_disabled
1067                        switch(3), // user_transaction_disabled
1068                        switch(4), // receiving_objects_disabled
1069                        switch(5), // move_authenticator_disabled
1070                    ),
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    /// The proposal round-trips through BCS unchanged.
1084    #[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    /// The generation is wall-clock time, but never regresses below a
1106    /// recorded proposal's generation even if the clock stepped backward.
1107    #[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}