Skip to main content

tendermint_consensus/
message.rs

1use core::{iter::Flatten, fmt};
2
3use crate::{
4  BlockNumber, RoundNumber, Validator, ValidatorSet, Signature, AggregateSignature,
5  SignatureScheme, Signer, BlockHash, Block, Commit, Blockchain, Evidence, SlashReason,
6};
7
8/// A valid round.
9///
10/// This is not just the specification of the valid round but also the evidence needed to convince
11/// other validators this round was valid. This allows each validator to only store their view of
12/// the valid round, with a bounded amount of memory, yet to recognize the proposer's argument for
13/// the valid round without issue.
14///
15/// This does increase the amount communicated by the proposer, but maintains the same `O(n^2)`
16/// communication complexity for each round as here we have the single proposer sending a message
17/// of size `n` to `n` other participants, while the following rounds have `n` participants sending
18/// messages of size `1` to `n` other participants. This assumes the aggregate signature is of size
19/// linear to the individual signatures, such as by a naïve concatenation into a list, though with
20/// threshold signatures or similar, this could be of equal complexity to the traditional concept
21/// of a proposal message.
22///
23/// In order for this to be valid, the signature MUST be valid and aggregated from signatures by
24/// validators whose weight is sufficient for the threshold. Deserialization or instantiation alone
25/// DOES NOT signify validity.
26#[derive(Clone)]
27#[cfg_attr(feature = "alloc", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
28pub(crate) struct ValidRound<A: AggregateSignature> {
29  pub(crate) round_number: RoundNumber,
30  pub(crate) aggregate_signature: A,
31}
32
33impl<A: AggregateSignature> PartialEq for ValidRound<A> {
34  /// This equality is semantic and does not consider if any present signatures are equal. This
35  /// ensures even for signature schemes with malleable signatures, multiple signatures over the
36  /// same messages are not semantically treated as distinct signatures. However, this also means a
37  /// value with an invalid signature will be considered equal to a message with a valid signature.
38  fn eq(&self, other: &Self) -> bool {
39    let Self { round_number, aggregate_signature: _ } = self;
40    (*round_number) == other.round_number
41  }
42}
43impl<A: AggregateSignature> Eq for ValidRound<A> {}
44
45impl<A: AggregateSignature> fmt::Debug for ValidRound<A> {
46  fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
47    let Self { round_number, aggregate_signature: _ } = self;
48    formatter.debug_struct("ValidRound").field("round_number", round_number).finish()
49  }
50}
51
52/// The data within a message.
53#[derive(Clone)]
54#[cfg_attr(feature = "alloc", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
55pub(crate) enum Data<S: Signature, A: AggregateSignature, B: Block> {
56  Proposal {
57    valid_round: Option<ValidRound<A>>,
58    proposal: B,
59  },
60  Prevote {
61    #[cfg_attr(
62      feature = "alloc",
63      borsh(bound(
64        serialize = "B::Hash: borsh::BorshSerialize",
65        deserialize = "B::Hash: borsh::BorshDeserialize"
66      ))
67    )]
68    block: Option<B::Hash>,
69  },
70  Precommit {
71    #[cfg_attr(
72      feature = "alloc",
73      borsh(bound(
74        serialize = "S: borsh::BorshSerialize, B::Hash: borsh::BorshSerialize",
75        deserialize = "S: borsh::BorshDeserialize, B::Hash: borsh::BorshDeserialize"
76      ))
77    )]
78    block_and_precommit_signature: Option<(B::Hash, S)>,
79  },
80}
81
82impl<S: Signature, A: AggregateSignature, B: Block> PartialEq for Data<S, A, B> {
83  /// This equality is semantic and does not consider if any present signatures are equal. This
84  /// ensures even for signature schemes with malleable signatures, multiple signatures over the
85  /// same messages are not semantically treated as distinct signatures. However, this also means a
86  /// value with an invalid signature will be considered equal to a message with a valid signature.
87  fn eq(&self, other: &Self) -> bool {
88    match (self, other) {
89      (
90        Data::Proposal { valid_round, proposal },
91        Data::Proposal { valid_round: other_valid_round, proposal: other_proposal },
92      ) => {
93        // This uses the block's proposal hash, not its semantic hash, as the proposal hash affects
94        // the semantics of this proposal message
95        (valid_round == other_valid_round) &&
96          (proposal.proposal_hash() == other_proposal.proposal_hash())
97      }
98      (Data::Prevote { block }, Data::Prevote { block: other_block }) => block == other_block,
99      (
100        Data::Precommit { block_and_precommit_signature: None },
101        Data::Precommit { block_and_precommit_signature: None },
102      ) => true,
103      (
104        Data::Precommit { block_and_precommit_signature: Some((block, _)) },
105        Data::Precommit { block_and_precommit_signature: Some((other_block, _)) },
106      ) => block == other_block,
107      (
108        Data::Precommit { block_and_precommit_signature: Some(_) },
109        Data::Precommit { block_and_precommit_signature: None },
110      ) |
111      (
112        Data::Precommit { block_and_precommit_signature: None },
113        Data::Precommit { block_and_precommit_signature: Some(_) },
114      ) |
115      (Data::Proposal { .. }, Data::Prevote { .. } | Data::Precommit { .. }) |
116      (Data::Prevote { .. }, Data::Proposal { .. } | Data::Precommit { .. }) |
117      (Data::Precommit { .. }, Data::Proposal { .. } | Data::Prevote { .. }) => false,
118    }
119  }
120}
121impl<S: Signature, A: AggregateSignature, B: Block> Eq for Data<S, A, B> {}
122
123#[doc(hidden)]
124pub(crate) enum MessageSegment<'genesis, S: Signature, A: AggregateSignature, B: Block> {
125  Dst([u8; 1]),
126  Genesis(&'genesis [u8]),
127  U64([u8; 8]),
128  AggregateSignature(A),
129  Block(B::Hash),
130  PrecommitSignature(S),
131}
132impl<S: Signature, A: AggregateSignature, B: Block> AsRef<[u8]> for MessageSegment<'_, S, A, B> {
133  fn as_ref(&self) -> &[u8] {
134    match self {
135      Self::Dst(dst) => dst.as_slice(),
136      Self::Genesis(genesis) => genesis,
137      Self::U64(round_number) => round_number.as_slice(),
138      Self::AggregateSignature(aggregate_signature) => aggregate_signature.as_ref(),
139      Self::Block(block) => block.as_ref(),
140      Self::PrecommitSignature(precommit_signature) => precommit_signature.as_ref(),
141    }
142  }
143}
144
145impl<S: Signature, A: AggregateSignature, B: Block> Data<S, A, B> {
146  /// The serialization used for signing.
147  ///
148  /// This exists primarily as we do not want to sign the block in a proposal but solely its hash.
149  /// This allows proving an equivocation occurred without rebroadcasting the blocks as a whole but
150  /// solely their hashes.
151  ///
152  /// The result can be mapped to an `Iterator<Item = &[u8]>` as needed to be chained with a larger
153  /// context of such schema. While this is rather annoying to do here, the borrow-checker somewhat
154  /// requires this pattern.
155  #[must_use]
156  fn signature_message(&self) -> [Option<MessageSegment<'static, S, A, B>>; 5] {
157    let (kind, round_number, aggregate_signature, block, precommit_signature) = match self {
158      Data::Proposal { valid_round, proposal } => {
159        let (round_number, aggregate_signature) = valid_round
160          .as_ref()
161          .map(|ValidRound { round_number, aggregate_signature }| {
162            (u64::from(*round_number).to_le_bytes(), aggregate_signature.clone())
163          })
164          .unzip();
165        (
166          0u8,
167          /*
168            `round_number` and `aggregate_signature` are both `Some` or both `None`, and
169            `round_number` is fixed-length, preventing collisions between the two of them.
170          */
171          round_number,
172          aggregate_signature,
173          /*
174            We only sign the hash to avoid having to serialize/store the entire block.
175
176            This is bound to be of fixed-length so it does not need length-prefixing, nor do the
177            prior two fields (which behave as a single field, the sole field of variable length in
178            this message).
179          */
180          Some(proposal.proposal_hash()),
181          None,
182        )
183      }
184      /*
185        This omits the encoding of the block hash to signify `None`, which is fine as this is
186        without collisions and this doesn't have to be able to be deserialized from.
187      */
188      Data::Prevote { block } => (1u8, None, None, *block, None),
189      Data::Precommit { block_and_precommit_signature } => {
190        let (block, precommit_signature) = block_and_precommit_signature.clone().unzip();
191        (
192          2u8,
193          None,
194          None,
195          /*
196            The block hash has a fixed length and these are both `Some` or both `None`, meaning
197            that regardless of the precommit signature's encoding, this is without conflict.
198          */
199          block,
200          precommit_signature,
201        )
202      }
203    };
204
205    [
206      Some(MessageSegment::<S, A, B>::Dst([kind])),
207      round_number.map(MessageSegment::U64),
208      aggregate_signature.map(MessageSegment::AggregateSignature),
209      block.map(MessageSegment::Block),
210      precommit_signature.map(MessageSegment::PrecommitSignature),
211    ]
212  }
213}
214
215/// A message from the Tendermint consensus process.
216///
217/// This encapsulates a [`Data`] with the validator, block and round numbers, and signature.
218#[derive(Clone)]
219#[cfg_attr(feature = "alloc", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
220pub struct Message<V: Validator, S: Signature, A: AggregateSignature, B: Block> {
221  pub(crate) validator: V,
222  pub(crate) block_number: BlockNumber,
223  pub(crate) round_number: RoundNumber,
224  #[cfg_attr(
225    feature = "alloc",
226    borsh(bound(
227      serialize = "
228        A: borsh::BorshSerialize,
229        B: borsh::BorshSerialize,
230        B::Hash: borsh::BorshSerialize
231      ",
232      deserialize = "
233        A: borsh::BorshDeserialize,
234        B: borsh::BorshDeserialize,
235        B::Hash: borsh::BorshDeserialize
236      "
237    ))
238  )]
239  pub(crate) data: Data<S, A, B>,
240  pub(crate) signature: S,
241}
242
243impl<V: Validator, S: Signature, A: AggregateSignature, B: Block> PartialEq
244  for Message<V, S, A, B>
245{
246  /// This equality is semantic and does not consider if any present signatures are equal. This
247  /// ensures even for signature schemes with malleable signatures, multiple signatures over the
248  /// same messages are not semantically treated as distinct signatures. However, this also means a
249  /// value with an invalid signature will be considered equal to a message with a valid signature.
250  fn eq(&self, other: &Self) -> bool {
251    let Self { validator, block_number, round_number, data, signature: _ } = self;
252    ((*validator) == other.validator) &&
253      ((*block_number) == other.block_number) &&
254      ((*round_number) == other.round_number) &&
255      (data == &other.data)
256  }
257}
258impl<V: Validator, S: Signature, A: AggregateSignature, B: Block> Eq for Message<V, S, A, B> {}
259
260/// The message type for a blockchain.
261pub type MessageFor<B> = Message<
262  <B as Blockchain>::Validator,
263  <<B as Blockchain>::SignatureScheme as SignatureScheme>::Signature,
264  <<B as Blockchain>::SignatureScheme as SignatureScheme>::AggregateSignature,
265  <B as Blockchain>::Block,
266>;
267
268#[cfg_attr(test, derive(Debug))]
269pub(crate) enum MessageError<S: Signature, A: AggregateSignature, H: BlockHash> {
270  /// The message was stale within the current context.
271  Stale,
272  /// The message was for a future context.
273  ///
274  /// This MAY suggest the local view is historic.
275  Future,
276  /// The message was not from a validator.
277  NotValidator,
278  /// The message had an invalid signature and could not be authenticated as from the validator.
279  InvalidOuterSignature,
280  /// The message has an invalid intenal structure.
281  Invalid(SlashReason<S, A, H>),
282  /// The message contained a fatally invalid proposal.
283  FatalProposal,
284  /// This message has already been handled.
285  AlreadyHandled,
286}
287
288type MessageSignatureMessage<'genesis, S, A, B> =
289  Flatten<<[Option<MessageSegment<'genesis, S, A, B>>; 10] as IntoIterator>::IntoIter>;
290impl<V: Validator, S: Signature, A: AggregateSignature, B: Block> Message<V, S, A, B> {
291  #[expect(clippy::many_single_char_names)]
292  pub(crate) fn signature_message<'genesis>(
293    genesis: &'genesis [u8],
294    block_number: BlockNumber,
295    round_number: RoundNumber,
296    data: &Data<S, A, B>,
297  ) -> MessageSignatureMessage<'genesis, S, A, B> {
298    let [a, b, c, d, e] = [
299      MessageSegment::Dst([1]),
300      MessageSegment::Dst([u8::try_from(genesis.len()).unwrap()]),
301      MessageSegment::Genesis(genesis),
302      MessageSegment::U64(u64::from(block_number).to_le_bytes()),
303      MessageSegment::U64(u64::from(round_number).to_le_bytes()),
304    ]
305    .map(Some);
306    let [f, g, h, i, j] = data.signature_message();
307
308    [a, b, c, d, e, f, g, h, i, j].into_iter().flatten()
309  }
310
311  #[must_use]
312  pub(crate) async fn sign(
313    signer: &(impl ?Sized + Signer<Validator = V, Signature = S>),
314    genesis: &[u8],
315    block_number: BlockNumber,
316    round_number: RoundNumber,
317    data: Data<S, A, B>,
318  ) -> Self {
319    let signature =
320      signer.sign(Self::signature_message(genesis, block_number, round_number, &data)).await;
321    Self { validator: signer.validator(), block_number, round_number, data, signature }
322  }
323
324  /// Perform static verification for this message.
325  ///
326  /// This only verifies the values within this message which can be verified against solely the
327  /// blockchain's parameters itself, without any state from the Tendermint consensus process. This
328  /// includes:
329  ///
330  /// - The message is from a validator
331  /// - The message's signature
332  /// - The signatures inside the message ([`ValidRound`], the precommit signature)
333  /// - The proposer is actually the proposer for this round
334  /// - The valid round's round number is less than this message's round number
335  pub(crate) fn static_verificiation(
336    &self,
337    genesis: impl AsRef<[u8]>,
338    validator_set: &(impl ?Sized + ValidatorSet<Validator = V>),
339    signature_scheme: &(
340       impl ?Sized + SignatureScheme<Validator = V, Signature = S, AggregateSignature = A>
341     ),
342  ) -> Result<(), MessageError<S, A, B::Hash>> {
343    let genesis = genesis.as_ref();
344
345    if validator_set.weight(&self.validator).is_none() {
346      Err(MessageError::NotValidator)?;
347    }
348
349    if !signature_scheme.verify(
350      &self.validator,
351      Self::signature_message(genesis, self.block_number, self.round_number, &self.data),
352      &self.signature,
353    ) {
354      Err(MessageError::InvalidOuterSignature)?;
355    }
356
357    match &self.data {
358      Data::Proposal { valid_round, proposal } => {
359        if !(valid_round.as_ref().is_none_or(|ValidRound { round_number, aggregate_signature }| {
360          ((*round_number) < self.round_number) &&
361            signature_scheme
362              .verify_aggregate(
363                Self::signature_message(
364                  genesis,
365                  self.block_number,
366                  *round_number,
367                  &Data::Prevote { block: Some(proposal.proposal_hash()) },
368                ),
369                aggregate_signature,
370              )
371              .is_ok_and(|validators| {
372                crate::validators_satisfy_threshold(validators, validator_set)
373              })
374        }) && (self.validator == validator_set.proposer(self.block_number, self.round_number)))
375        {
376          Err(MessageError::Invalid(SlashReason {
377            block_number: self.block_number,
378            round_number: self.round_number,
379            evidence: Evidence::InvalidProposal {
380              valid_round: valid_round.clone(),
381              proposal: proposal.proposal_hash(),
382              signature: self.signature.clone(),
383            },
384          }))?;
385        }
386      }
387      Data::Precommit { block_and_precommit_signature: Some((block, precommit_signature)) } => {
388        if !Commit::verify_precommit(
389          signature_scheme,
390          &self.validator,
391          genesis,
392          self.block_number,
393          self.round_number,
394          block.as_ref(),
395          precommit_signature,
396        ) {
397          Err(MessageError::Invalid(SlashReason {
398            block_number: self.block_number,
399            round_number: self.round_number,
400            evidence: Evidence::InvalidPrecommit {
401              block: *block,
402              precommit_signature: precommit_signature.clone(),
403              signature: self.signature.clone(),
404            },
405          }))?;
406        }
407      }
408      Data::Prevote { .. } | Data::Precommit { block_and_precommit_signature: None } => {}
409    }
410
411    Ok(())
412  }
413}
414
415#[cfg(test)]
416pub(crate) fn random_valid_round()
417-> Option<ValidRound<<crate::TestSignatureScheme as SignatureScheme>::AggregateSignature>> {
418  use core::num::NonZero;
419  use rand_core::{TryRngCore as _, OsRng};
420
421  ((OsRng.try_next_u64().unwrap() & 1) == 1).then(|| {
422    let round_number =
423      RoundNumber(NonZero::new(OsRng.try_next_u64().unwrap().saturating_add(1)).unwrap());
424    let mut aggregate_signature = [0; 8 + 32];
425    OsRng.try_fill_bytes(&mut aggregate_signature).unwrap();
426    ValidRound { round_number, aggregate_signature }
427  })
428}
429
430#[test]
431fn test_random_valid_round() {
432  let mut some = false;
433  let mut none = false;
434  for _ in 0 .. 128 {
435    some |= random_valid_round().is_some();
436    none |= random_valid_round().is_none();
437  }
438  assert!(some);
439  assert!(none);
440}
441
442#[cfg(feature = "alloc")]
443#[test]
444fn signature_message() {
445  use core::num::NonZero;
446  use alloc::{vec::Vec, vec};
447
448  use rand_core::{TryRngCore as _, OsRng};
449
450  use crate::{StubBlock, TestSignatureScheme};
451
452  for _ in 0 .. 128 {
453    #[expect(clippy::as_conversions, clippy::cast_possible_truncation)]
454    let genesis_len = OsRng.try_next_u64().unwrap() as u8;
455    let mut genesis = vec![0xff; usize::from(genesis_len)];
456    OsRng.try_fill_bytes(&mut genesis).unwrap();
457    let genesis = genesis.as_ref();
458
459    let block_number =
460      BlockNumber(NonZero::new(OsRng.try_next_u64().unwrap().saturating_add(1)).unwrap());
461    let round_number =
462      RoundNumber(NonZero::new(OsRng.try_next_u64().unwrap().saturating_add(1)).unwrap());
463
464    let mut block = [0xff; 32];
465    OsRng.try_fill_bytes(&mut block).unwrap();
466    let block = StubBlock::from(&block);
467
468    type TestData<'hash> = Data<
469      <TestSignatureScheme as SignatureScheme>::Signature,
470      <TestSignatureScheme as SignatureScheme>::AggregateSignature,
471      StubBlock<'hash>,
472    >;
473
474    let mut signature = [0; 1 + 8];
475    OsRng.try_fill_bytes(&mut signature).unwrap();
476
477    let valid_round = loop {
478      let valid_round = random_valid_round();
479      if let Some(valid_round) = valid_round {
480        break valid_round;
481      }
482    };
483
484    let prefix = [
485      [1].as_slice(),
486      [genesis_len].as_slice(),
487      genesis,
488      u64::from(block_number).to_le_bytes().as_slice(),
489      u64::from(round_number).to_le_bytes().as_slice(),
490    ]
491    .concat();
492
493    assert_eq!(
494      Message::<<TestSignatureScheme as SignatureScheme>::Validator, _, _, _>::signature_message(
495        genesis,
496        block_number,
497        round_number,
498        &TestData::Proposal { valid_round: Some(valid_round.clone()), proposal: block.clone() }
499      )
500      .fold(Vec::<u8>::new(), |mut accum, item| {
501        accum.extend(item.as_ref());
502        accum
503      }),
504      [
505        prefix.as_slice(),
506        [0].as_slice(),
507        u64::from(valid_round.round_number).to_le_bytes().as_slice(),
508        valid_round.aggregate_signature.as_ref(),
509        block.proposal_hash().as_ref(),
510      ]
511      .concat(),
512    );
513
514    assert_eq!(
515      Message::<<TestSignatureScheme as SignatureScheme>::Validator, _, _, _>::signature_message(
516        genesis,
517        block_number,
518        round_number,
519        &TestData::Proposal { valid_round: None, proposal: block.clone() }
520      )
521      .fold(Vec::<u8>::new(), |mut accum, item| {
522        accum.extend(item.as_ref());
523        accum
524      }),
525      [prefix.as_slice(), [0].as_slice(), block.proposal_hash().as_ref()].concat(),
526    );
527
528    assert_eq!(
529      Message::<<TestSignatureScheme as SignatureScheme>::Validator, _, _, _>::signature_message(
530        genesis,
531        block_number,
532        round_number,
533        &TestData::Prevote { block: Some(block.proposal_hash()) }
534      )
535      .fold(Vec::<u8>::new(), |mut accum, item| {
536        accum.extend(item.as_ref());
537        accum
538      }),
539      [prefix.as_slice(), [1].as_slice(), block.proposal_hash().as_ref()].concat(),
540    );
541
542    assert_eq!(
543      Message::<<TestSignatureScheme as SignatureScheme>::Validator, _, _, _>::signature_message(
544        genesis,
545        block_number,
546        round_number,
547        &TestData::Prevote { block: None }
548      )
549      .fold(Vec::<u8>::new(), |mut accum, item| {
550        accum.extend(item.as_ref());
551        accum
552      }),
553      [prefix.as_slice(), [1].as_slice()].concat(),
554    );
555
556    assert_eq!(
557      Message::<<TestSignatureScheme as SignatureScheme>::Validator, _, _, _>::signature_message(
558        genesis,
559        block_number,
560        round_number,
561        &TestData::Precommit {
562          block_and_precommit_signature: Some((block.semantic_hash(), signature))
563        }
564      )
565      .fold(Vec::<u8>::new(), |mut accum, item| {
566        accum.extend(item.as_ref());
567        accum
568      }),
569      [prefix.as_slice(), [2].as_slice(), block.semantic_hash().as_ref(), signature.as_ref()]
570        .concat(),
571    );
572
573    assert_eq!(
574      Message::<<TestSignatureScheme as SignatureScheme>::Validator, _, _, _>::signature_message(
575        genesis,
576        block_number,
577        round_number,
578        &TestData::Precommit { block_and_precommit_signature: None }
579      )
580      .fold(Vec::<u8>::new(), |mut accum, item| {
581        accum.extend(item.as_ref());
582        accum
583      }),
584      [prefix.as_slice(), [2].as_slice()].concat(),
585    );
586  }
587}
588
589#[cfg(feature = "alloc")]
590#[test]
591fn sign() {
592  use core::num::NonZero;
593  use core::{
594    pin::pin,
595    task::{Poll, Waker, Context},
596    future::Future as _,
597  };
598
599  use rand_core::{TryRngCore as _, OsRng};
600
601  use crate::{OpaqueBlockHash, StubBlock, TestSignatureScheme};
602
603  for _ in 0 .. 128 {
604    let mut block = [0; 32];
605    OsRng.try_fill_bytes(&mut block).unwrap();
606    let block = ((OsRng.try_next_u64().unwrap() & 1) == 1).then_some(block);
607
608    let data =
609      Data::Prevote { block: block.as_ref().map(|block| OpaqueBlockHash(block.as_slice())) };
610
611    let mut genesis = [0; 32];
612    OsRng.try_fill_bytes(&mut genesis).unwrap();
613
614    let block_number =
615      BlockNumber(NonZero::new(OsRng.try_next_u64().unwrap().saturating_add(1)).unwrap());
616    let round_number =
617      RoundNumber(NonZero::new(OsRng.try_next_u64().unwrap().saturating_add(1)).unwrap());
618
619    let signature_scheme = TestSignatureScheme::new();
620    let signer = signature_scheme.signer(0);
621
622    let mut context = Context::from_waker(Waker::noop());
623    let Poll::Ready(message) =
624      pin!(Message::<
625        _,
626        _,
627        <TestSignatureScheme as SignatureScheme>::AggregateSignature,
628        StubBlock<'_>,
629      >::sign(&signer, &genesis, block_number, round_number, data))
630      .poll(&mut context)
631    else {
632      panic!("`TestSignatureScheme::sign` returned `Poll::Pending`")
633    };
634
635    let one_weight = NonZero::new(1).unwrap();
636    let validator_set = alloc::collections::BTreeMap::from([(0, one_weight), (1, one_weight)]);
637    message.static_verificiation(genesis, &validator_set, &signature_scheme).unwrap();
638
639    {
640      let mut message = message.clone();
641      message.signature[0] ^= 1;
642      assert!(matches!(
643        message.static_verificiation(genesis, &validator_set, &signature_scheme),
644        Err(MessageError::InvalidOuterSignature)
645      ));
646    }
647
648    {
649      let mut message = message.clone();
650      message.validator = 1;
651      assert!(matches!(
652        message.static_verificiation(genesis, &validator_set, &signature_scheme),
653        Err(MessageError::InvalidOuterSignature)
654      ));
655    }
656
657    {
658      let mut message = message.clone();
659      message.validator = 2;
660      assert!(matches!(
661        message.static_verificiation(genesis, &validator_set, &signature_scheme),
662        Err(MessageError::NotValidator)
663      ));
664    }
665  }
666}