Skip to main content

tendermint_consensus/
commit.rs

1use crate::{
2  BlockNumber, RoundNumber, Validator, ValidatorSet, AggregateSignature, SignatureScheme, Signer,
3  Blockchain,
4};
5
6/// A commit for a specific block.
7///
8/// In order for this to be valid, the signature MUST be valid and aggregated from signatures by
9/// validators whose weight is sufficient for the threshold. Deserialization or instantiation alone
10/// DOES NOT signify validity.
11#[derive(Debug)]
12#[cfg_attr(feature = "alloc", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
13pub struct Commit<A: AggregateSignature> {
14  /// The block number this is a commit for.
15  pub(crate) block_number: BlockNumber,
16
17  /// The round number which produced this commit.
18  ///
19  /// This is not a canonical round number and there may be multiple valid commits, for the same
20  /// block, with differing `round_number` values without implying a break in soundness. This is
21  /// only here to provide separation such that precommits from distinct rounds cannot be used in
22  /// conjunction with each other.
23  pub(crate) round_number: RoundNumber,
24
25  /// The aggregate signature for the validators used to create this commit.
26  pub(crate) aggregate_signature: A,
27}
28
29/// The [`Commit`] type for a [`Blockchain`].
30pub type CommitFor<B> =
31  Commit<<<B as Blockchain>::SignatureScheme as SignatureScheme>::AggregateSignature>;
32
33impl<A: AggregateSignature> Clone for Commit<A> {
34  fn clone(&self) -> Self {
35    Self {
36      block_number: self.block_number,
37      round_number: self.round_number,
38      aggregate_signature: self.aggregate_signature.clone(),
39    }
40  }
41}
42
43/// Check if a list of validators have a sum weight satisfying the threshold.
44///
45/// This returns `false` if any validator present was not actually a validator. This DOES NOT check
46/// the validators were unique however.
47#[must_use]
48pub(crate) fn validators_satisfy_threshold<V: Validator>(
49  validators: impl IntoIterator<Item = V>,
50  validator_set: &(impl ?Sized + ValidatorSet<Validator = V>),
51) -> bool {
52  // Ensure every validator is in fact a validator and their sum weight satisfies the threshold
53  validators
54    .into_iter()
55    .try_fold(0u16, |accum, validator| {
56      validator_set.weight(&validator).and_then(|weight| accum.checked_add(u16::from(weight)))
57    })
58    .is_some_and(|sum| sum >= validator_set.threshold())
59}
60
61#[doc(hidden)]
62pub(crate) enum CommitSegment<'genesis, 'block_hash> {
63  Dst([u8; 1]),
64  Genesis(&'genesis [u8]),
65  U64([u8; 8]),
66  Block(&'block_hash [u8]),
67}
68impl AsRef<[u8]> for CommitSegment<'_, '_> {
69  fn as_ref(&self) -> &[u8] {
70    match self {
71      Self::Dst(dst) => dst.as_slice(),
72      Self::Genesis(genesis) => genesis,
73      Self::U64(number) => number.as_slice(),
74      Self::Block(block_hash) => block_hash,
75    }
76  }
77}
78
79impl<A: AggregateSignature> Commit<A> {
80  /// The block number this commit is for.
81  #[must_use]
82  pub fn block_number(&self) -> BlockNumber {
83    self.block_number
84  }
85
86  pub(crate) fn signature_message<'genesis, 'block_hash>(
87    genesis: &'genesis [u8],
88    block_number: BlockNumber,
89    round_number: RoundNumber,
90    block_hash: &'block_hash [u8],
91  ) -> <[CommitSegment<'genesis, 'block_hash>; 6] as IntoIterator>::IntoIter {
92    [
93      CommitSegment::Dst([0]),
94      /*
95        Length-prefix the genesis to prevent one genesis from being a valid prefix of another,
96        breaking the intended domain separation of this.
97      */
98      CommitSegment::Dst([u8::try_from(genesis.as_ref().len()).unwrap()]),
99      CommitSegment::Genesis(genesis),
100      CommitSegment::U64(u64::from(block_number.0).to_le_bytes()),
101      CommitSegment::U64(u64::from(round_number.0).to_le_bytes()),
102      /*
103        This doesn't length-prefix the block hash as it's presumably fixed-length and is definitely
104        unnecessary.
105      */
106      CommitSegment::Block(block_hash),
107    ]
108    .into_iter()
109  }
110
111  #[must_use]
112  pub(crate) async fn sign<S: ?Sized + SignatureScheme<AggregateSignature = A>>(
113    signer: &(impl ?Sized + Signer<Signature = <S as SignatureScheme>::Signature>),
114    genesis: &[u8],
115    block_number: BlockNumber,
116    round_number: RoundNumber,
117    block_hash: &[u8],
118  ) -> <S as SignatureScheme>::Signature {
119    signer.sign(Self::signature_message(genesis, block_number, round_number, block_hash)).await
120  }
121
122  #[must_use]
123  pub(crate) fn verify_precommit<S: ?Sized + SignatureScheme<AggregateSignature = A>>(
124    signature_scheme: &S,
125    validator: &S::Validator,
126    genesis: &[u8],
127    block_number: BlockNumber,
128    round_number: RoundNumber,
129    block_hash: &[u8],
130    signature: &S::Signature,
131  ) -> bool {
132    signature_scheme.verify(
133      validator,
134      Self::signature_message(genesis, block_number, round_number, block_hash),
135      signature,
136    )
137  }
138
139  /// Verify a commit.
140  ///
141  /// The genesis MUST be a valid genesis for a [`Blockchain`].
142  #[must_use]
143  pub fn verify<S: ?Sized + SignatureScheme<AggregateSignature = A>>(
144    &self,
145    validator_set: &(impl ?Sized + ValidatorSet<Validator = S::Validator>),
146    signature_scheme: &S,
147    genesis: impl AsRef<[u8]>,
148    block_hash: impl AsRef<[u8]>,
149  ) -> bool {
150    // Ensure the signature was valid
151    let Ok(validators) = signature_scheme.verify_aggregate(
152      Self::signature_message(
153        genesis.as_ref(),
154        self.block_number,
155        self.round_number,
156        block_hash.as_ref(),
157      ),
158      &self.aggregate_signature,
159    ) else {
160      return false;
161    };
162
163    // Ensure the signers satisfy the threshold
164    validators_satisfy_threshold(validators, validator_set)
165  }
166}
167
168#[cfg(test)]
169mod tests {
170  use super::*;
171
172  struct RandomCommit {
173    genesis_len: u8,
174    #[expect(clippy::as_conversions)]
175    genesis: [u8; u8::MAX as usize],
176
177    block_number: BlockNumber,
178    round_number: RoundNumber,
179
180    block_hash_len: u16,
181    #[expect(clippy::as_conversions)]
182    block_hash: [u8; u16::MAX as usize],
183  }
184
185  impl RandomCommit {
186    fn new() -> Self {
187      use core::num::NonZero;
188      use rand_core::{TryRngCore as _, OsRng};
189
190      #[expect(clippy::as_conversions, clippy::cast_possible_truncation)]
191      let genesis_len = OsRng.try_next_u64().unwrap() as u8;
192      #[expect(clippy::as_conversions)]
193      let mut genesis = [0xff; u8::MAX as usize];
194      OsRng.try_fill_bytes(&mut genesis[.. usize::from(genesis_len)]).unwrap();
195
196      let block_number =
197        BlockNumber(NonZero::new(OsRng.try_next_u64().unwrap().saturating_add(1)).unwrap());
198      let round_number =
199        RoundNumber(NonZero::new(OsRng.try_next_u64().unwrap().saturating_add(1)).unwrap());
200
201      #[expect(clippy::as_conversions, clippy::cast_possible_truncation)]
202      let block_hash_len = OsRng.try_next_u64().unwrap() as u16;
203      #[expect(clippy::as_conversions, clippy::large_stack_arrays)]
204      let mut block_hash = [0xff; u16::MAX as usize];
205      OsRng.try_fill_bytes(&mut block_hash[.. usize::from(block_hash_len)]).unwrap();
206
207      Self { genesis_len, genesis, block_number, round_number, block_hash_len, block_hash }
208    }
209
210    fn genesis(&self) -> &[u8] {
211      &self.genesis[.. usize::from(self.genesis_len)]
212    }
213
214    fn block_hash(&self) -> &[u8] {
215      &self.block_hash[.. usize::from(self.block_hash_len)]
216    }
217  }
218
219  #[cfg(feature = "alloc")]
220  #[test]
221  fn signature_message() {
222    for _ in 0 .. 128 {
223      let commit = RandomCommit::new();
224
225      let expected = [
226        [0].as_slice(),
227        &[commit.genesis_len],
228        commit.genesis(),
229        &u64::from(commit.block_number).to_le_bytes(),
230        &u64::from(commit.round_number).to_le_bytes(),
231        commit.block_hash(),
232      ]
233      .concat();
234
235      let mut concatenated = alloc::vec![];
236      for chunk in Commit::<
237        <crate::TestSignatureScheme as SignatureScheme>::AggregateSignature
238      >::signature_message(
239        commit.genesis(),
240        commit.block_number,
241        commit.round_number,
242        commit.block_hash(),
243      ) {
244        concatenated.extend(chunk.as_ref());
245      }
246
247      assert_eq!(expected, concatenated);
248    }
249  }
250
251  #[cfg(feature = "alloc")]
252  #[test]
253  fn sign_and_verify_precommit() {
254    use core::{
255      pin::pin,
256      task::{Poll, Waker, Context},
257      future::Future as _,
258    };
259
260    use crate::TestSignatureScheme;
261
262    let mut context = Context::from_waker(Waker::noop());
263    let signature_scheme = TestSignatureScheme::new();
264
265    for i in 0 .. u8::MAX {
266      let signer = signature_scheme.signer(i);
267      let commit = RandomCommit::new();
268      let Poll::Ready(mut signature) = pin!(Commit::<
269        <TestSignatureScheme as SignatureScheme>::AggregateSignature,
270      >::sign::<TestSignatureScheme>(
271        &signer,
272        commit.genesis(),
273        commit.block_number,
274        commit.round_number,
275        commit.block_hash(),
276      ))
277      .poll(&mut context) else {
278        panic!("`TestSignatureScheme::sign` returned `Poll::Pending`")
279      };
280      assert!(
281        Commit::<<TestSignatureScheme as SignatureScheme>::AggregateSignature>::verify_precommit(
282          &signature_scheme,
283          &i,
284          commit.genesis(),
285          commit.block_number,
286          commit.round_number,
287          commit.block_hash(),
288          &signature
289        )
290      );
291      signature[0] ^= 1;
292      assert!(
293        !Commit::<<TestSignatureScheme as SignatureScheme>::AggregateSignature>::verify_precommit(
294          &signature_scheme,
295          &i,
296          commit.genesis(),
297          commit.block_number,
298          commit.round_number,
299          commit.block_hash(),
300          &signature
301        )
302      );
303    }
304  }
305
306  #[test]
307  fn verify_commit() {
308    use core::{
309      num::NonZero,
310      pin::pin,
311      task::{Poll, Waker, Context},
312      future::Future as _,
313    };
314    use alloc::{vec::Vec, vec, collections::BTreeMap};
315
316    use crate::TestSignatureScheme;
317
318    let signature_scheme = TestSignatureScheme::new();
319    let commit = RandomCommit::new();
320
321    let signature = |validator| {
322      let mut context = Context::from_waker(Waker::noop());
323      let signer = signature_scheme.signer(validator);
324      let Poll::Ready(signature) = pin!(Commit::<
325        <TestSignatureScheme as SignatureScheme>::AggregateSignature,
326      >::sign::<TestSignatureScheme>(
327        &signer,
328        commit.genesis(),
329        commit.block_number,
330        commit.round_number,
331        commit.block_hash(),
332      ))
333      .poll(&mut context) else {
334        panic!("`TestSignatureScheme::sign` returned `Poll::Pending`")
335      };
336      signature
337    };
338    let signatures = [signature(0), signature(2), signature(3)];
339
340    let aggregate_signature = signature_scheme.aggregate(
341      Commit::<<TestSignatureScheme as SignatureScheme>::AggregateSignature>::signature_message(
342        commit.genesis(),
343        commit.block_number,
344        commit.round_number,
345        commit.block_hash(),
346      ),
347      [(&0, &signatures[0])],
348    );
349
350    let actual_commit = Commit {
351      block_number: commit.block_number,
352      round_number: commit.round_number,
353      aggregate_signature,
354    };
355    assert_eq!(actual_commit.block_number(), commit.block_number);
356
357    let verify = |valid, actual_commit: &Commit<_>, weights: Vec<(_, u16)>| {
358      assert_eq!(
359        actual_commit.verify(
360          &weights
361            .into_iter()
362            .map(|(validator, weight)| (validator, NonZero::new(weight).unwrap()))
363            .collect::<BTreeMap<_, _>>(),
364          &signature_scheme,
365          commit.genesis(),
366          commit.block_hash()
367        ),
368        valid
369      );
370    };
371    // This should verify if the threshold is satisfied
372    verify(true, &actual_commit, vec![(0, 1)]);
373    // It shouldn't if the threshold isn't satisfied
374    verify(false, &actual_commit, vec![(0, 1), (1, 1)]);
375    // But this is a weighted threshold, so increasing the validator's weight should be sufficient
376    verify(false, &actual_commit, vec![(0, 2), (1, 1)]);
377    verify(true, &actual_commit, vec![(0, 3), (1, 1)]);
378
379    // Malleating the signature should cause the commit's verification to fail
380    {
381      let mut actual_commit = actual_commit.clone();
382      *actual_commit.aggregate_signature.last_mut().unwrap() ^= 1;
383      verify(false, &actual_commit, vec![(0, 1)]);
384    }
385
386    // Test a commit which requires the sum weight from multiple validators
387    {
388      let aggregate_signature = signature_scheme.aggregate(
389        Commit::<<TestSignatureScheme as SignatureScheme>::AggregateSignature>::signature_message(
390          commit.genesis(),
391          commit.block_number,
392          commit.round_number,
393          commit.block_hash(),
394        ),
395        [0, 2, 3].iter().zip(signatures.iter()),
396      );
397      let actual_commit = Commit {
398        block_number: commit.block_number,
399        round_number: commit.round_number,
400        aggregate_signature,
401      };
402      assert_eq!(actual_commit.block_number(), commit.block_number);
403      verify(true, &actual_commit, vec![(0, 1), (1, 1), (2, 1), (3, 1)]);
404    }
405  }
406}