tendermint-machine 0.3.0

An implementation of the Tendermint state machine in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
use crate::{
  BlockNumber, RoundNumber, Validator, ValidatorSet, AggregateSignature, SignatureScheme, Signer,
  Blockchain,
};

/// A commit for a specific block.
///
/// In order for this to be valid, the signature MUST be valid and aggregated from signatures by
/// validators whose weight is sufficient for the threshold. Deserialization or instantiation alone
/// DOES NOT signify validity.
#[derive(Debug)]
#[cfg_attr(feature = "alloc", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
pub struct Commit<A: AggregateSignature> {
  /// The block number this is a commit for.
  pub(crate) block_number: BlockNumber,

  /// The round number which produced this commit.
  ///
  /// This is not a canonical round number and there may be multiple valid commits, for the same
  /// block, with differing `round_number` values without implying a break in soundness. This is
  /// only here to provide separation such that precommits from distinct rounds cannot be used in
  /// conjunction with each other.
  pub(crate) round_number: RoundNumber,

  /// The aggregate signature for the validators used to create this commit.
  pub(crate) aggregate_signature: A,
}

/// The [`Commit`] type for a [`Blockchain`].
pub type CommitFor<B> =
  Commit<<<B as Blockchain>::SignatureScheme as SignatureScheme>::AggregateSignature>;

impl<A: AggregateSignature> Clone for Commit<A> {
  fn clone(&self) -> Self {
    Self {
      block_number: self.block_number,
      round_number: self.round_number,
      aggregate_signature: self.aggregate_signature.clone(),
    }
  }
}

/// Check if a list of validators have a sum weight satisfying the threshold.
///
/// This returns `false` if any validator present was not actually a validator. This DOES NOT check
/// the validators were unique however.
#[must_use]
pub(crate) fn validators_satisfy_threshold<V: Validator>(
  validators: impl IntoIterator<Item = V>,
  validator_set: &(impl ?Sized + ValidatorSet<Validator = V>),
) -> bool {
  // Ensure every validator is in fact a validator and their sum weight satisfies the threshold
  validators
    .into_iter()
    .try_fold(0u16, |accum, validator| {
      validator_set.weight(&validator).and_then(|weight| accum.checked_add(u16::from(weight)))
    })
    .is_some_and(|sum| sum >= validator_set.threshold())
}

#[doc(hidden)]
pub(crate) enum CommitSegment<'genesis, 'block_hash> {
  Dst([u8; 1]),
  Genesis(&'genesis [u8]),
  U64([u8; 8]),
  Block(&'block_hash [u8]),
}
impl AsRef<[u8]> for CommitSegment<'_, '_> {
  fn as_ref(&self) -> &[u8] {
    match self {
      Self::Dst(dst) => dst.as_slice(),
      Self::Genesis(genesis) => genesis,
      Self::U64(number) => number.as_slice(),
      Self::Block(block_hash) => block_hash,
    }
  }
}

impl<A: AggregateSignature> Commit<A> {
  /// The block number this commit is for.
  #[must_use]
  pub fn block_number(&self) -> BlockNumber {
    self.block_number
  }

  #[must_use]
  pub(crate) fn signature_message<'genesis, 'block_hash>(
    genesis: &'genesis [u8],
    block_number: BlockNumber,
    round_number: RoundNumber,
    block_hash: &'block_hash [u8],
  ) -> <[CommitSegment<'genesis, 'block_hash>; 6] as IntoIterator>::IntoIter {
    [
      CommitSegment::Dst([0]),
      /*
        Length-prefix the genesis to prevent one genesis from being a valid prefix of another,
        breaking the intended domain separation of this.
      */
      CommitSegment::Dst([u8::try_from(genesis.as_ref().len()).unwrap()]),
      CommitSegment::Genesis(genesis),
      CommitSegment::U64(u64::from(block_number.0).to_le_bytes()),
      CommitSegment::U64(u64::from(round_number.0).to_le_bytes()),
      /*
        This doesn't length-prefix the block hash as it's presumably fixed-length and is definitely
        unnecessary.
      */
      CommitSegment::Block(block_hash),
    ]
    .into_iter()
  }

  #[must_use]
  pub(crate) async fn sign<S: ?Sized + SignatureScheme<AggregateSignature = A>>(
    signer: &(impl ?Sized + Signer<Signature = <S as SignatureScheme>::Signature>),
    genesis: &[u8],
    block_number: BlockNumber,
    round_number: RoundNumber,
    block_hash: &[u8],
  ) -> <S as SignatureScheme>::Signature {
    signer.sign(Self::signature_message(genesis, block_number, round_number, block_hash)).await
  }

  #[must_use]
  pub(crate) fn verify_precommit<S: ?Sized + SignatureScheme<AggregateSignature = A>>(
    signature_scheme: &S,
    validator: &S::Validator,
    genesis: &[u8],
    block_number: BlockNumber,
    round_number: RoundNumber,
    block_hash: &[u8],
    signature: &S::Signature,
  ) -> bool {
    signature_scheme.verify(
      validator,
      Self::signature_message(genesis, block_number, round_number, block_hash),
      signature,
    )
  }

  /// Verify a commit.
  #[must_use]
  pub fn verify<S: ?Sized + SignatureScheme<AggregateSignature = A>>(
    &self,
    validator_set: &(impl ?Sized + ValidatorSet<Validator = S::Validator>),
    signature_scheme: &S,
    genesis: impl AsRef<[u8]>,
    block_hash: impl AsRef<[u8]>,
  ) -> bool {
    // Ensure the signature was valid
    let Ok(validators) = signature_scheme.verify_aggregate(
      Self::signature_message(
        genesis.as_ref(),
        self.block_number,
        self.round_number,
        block_hash.as_ref(),
      ),
      &self.aggregate_signature,
    ) else {
      return false;
    };

    // Ensure the signers satisfy the threshold
    validators_satisfy_threshold(validators, validator_set)
  }
}

#[cfg(test)]
mod tests {
  use super::*;

  struct RandomCommit {
    genesis_len: u8,
    #[expect(clippy::as_conversions)]
    genesis: [u8; u8::MAX as usize],

    block_number: BlockNumber,
    round_number: RoundNumber,

    block_hash_len: u16,
    #[expect(clippy::as_conversions)]
    block_hash: [u8; u16::MAX as usize],
  }

  impl RandomCommit {
    fn new() -> Self {
      use core::num::NonZero;
      use rand_core::{TryRngCore as _, OsRng};

      #[expect(clippy::as_conversions, clippy::cast_possible_truncation)]
      let genesis_len = OsRng.try_next_u64().unwrap() as u8;
      #[expect(clippy::as_conversions)]
      let mut genesis = [0xff; u8::MAX as usize];
      OsRng.try_fill_bytes(&mut genesis[.. usize::from(genesis_len)]).unwrap();

      let block_number =
        BlockNumber(NonZero::new(OsRng.try_next_u64().unwrap().saturating_add(1)).unwrap());
      let round_number =
        RoundNumber(NonZero::new(OsRng.try_next_u64().unwrap().saturating_add(1)).unwrap());

      #[expect(clippy::as_conversions, clippy::cast_possible_truncation)]
      let block_hash_len = OsRng.try_next_u64().unwrap() as u16;
      #[expect(clippy::as_conversions, clippy::large_stack_arrays)]
      let mut block_hash = [0xff; u16::MAX as usize];
      OsRng.try_fill_bytes(&mut block_hash[.. usize::from(block_hash_len)]).unwrap();

      Self { genesis_len, genesis, block_number, round_number, block_hash_len, block_hash }
    }

    fn genesis(&self) -> &[u8] {
      &self.genesis[.. usize::from(self.genesis_len)]
    }

    fn block_hash(&self) -> &[u8] {
      &self.block_hash[.. usize::from(self.block_hash_len)]
    }
  }

  #[cfg(feature = "alloc")]
  #[test]
  fn signature_message() {
    for _ in 0 .. 128 {
      let commit = RandomCommit::new();

      let expected = [
        [0].as_slice(),
        &[commit.genesis_len],
        commit.genesis(),
        &u64::from(commit.block_number).to_le_bytes(),
        &u64::from(commit.round_number).to_le_bytes(),
        commit.block_hash(),
      ]
      .concat();

      let mut concatenated = alloc::vec![];
      for chunk in Commit::<
        <crate::TestSignatureScheme as SignatureScheme>::AggregateSignature
      >::signature_message(
        commit.genesis(),
        commit.block_number,
        commit.round_number,
        commit.block_hash(),
      ) {
        concatenated.extend(chunk.as_ref());
      }

      assert_eq!(expected, concatenated);
    }
  }

  #[cfg(feature = "alloc")]
  #[test]
  fn sign_and_verify_precommit() {
    use core::{
      pin::pin,
      task::{Poll, Waker, Context},
      future::Future as _,
    };

    use crate::TestSignatureScheme;

    let mut context = Context::from_waker(Waker::noop());
    let signature_scheme = TestSignatureScheme::new();

    for i in 0 .. u8::MAX {
      let signer = signature_scheme.signer(i);
      let commit = RandomCommit::new();
      let Poll::Ready(mut signature) = pin!(Commit::<
        <TestSignatureScheme as SignatureScheme>::AggregateSignature,
      >::sign::<TestSignatureScheme>(
        &signer,
        commit.genesis(),
        commit.block_number,
        commit.round_number,
        commit.block_hash(),
      ))
      .poll(&mut context) else {
        panic!("`TestSignatureScheme::sign` returned `Poll::Pending`")
      };
      assert!(
        Commit::<<TestSignatureScheme as SignatureScheme>::AggregateSignature>::verify_precommit(
          &signature_scheme,
          &i,
          commit.genesis(),
          commit.block_number,
          commit.round_number,
          commit.block_hash(),
          &signature
        )
      );
      signature[0] ^= 1;
      assert!(
        !Commit::<<TestSignatureScheme as SignatureScheme>::AggregateSignature>::verify_precommit(
          &signature_scheme,
          &i,
          commit.genesis(),
          commit.block_number,
          commit.round_number,
          commit.block_hash(),
          &signature
        )
      );
    }
  }

  #[test]
  fn verify_commit() {
    use core::{
      num::NonZero,
      pin::pin,
      task::{Poll, Waker, Context},
      future::Future as _,
    };
    use alloc::{vec::Vec, vec, collections::BTreeMap};

    use crate::TestSignatureScheme;

    let signature_scheme = TestSignatureScheme::new();
    let commit = RandomCommit::new();

    let signature = |validator| {
      let mut context = Context::from_waker(Waker::noop());
      let signer = signature_scheme.signer(validator);
      let Poll::Ready(signature) = pin!(Commit::<
        <TestSignatureScheme as SignatureScheme>::AggregateSignature,
      >::sign::<TestSignatureScheme>(
        &signer,
        commit.genesis(),
        commit.block_number,
        commit.round_number,
        commit.block_hash(),
      ))
      .poll(&mut context) else {
        panic!("`TestSignatureScheme::sign` returned `Poll::Pending`")
      };
      signature
    };
    let signatures = [signature(0), signature(2), signature(3)];

    let aggregate_signature = signature_scheme.aggregate(
      Commit::<<TestSignatureScheme as SignatureScheme>::AggregateSignature>::signature_message(
        commit.genesis(),
        commit.block_number,
        commit.round_number,
        commit.block_hash(),
      ),
      [(&0, &signatures[0])],
    );

    let actual_commit = Commit {
      block_number: commit.block_number,
      round_number: commit.round_number,
      aggregate_signature,
    };
    assert_eq!(actual_commit.block_number(), commit.block_number);

    let verify = |valid, actual_commit: &Commit<_>, weights: Vec<(_, u16)>| {
      assert_eq!(
        actual_commit.verify(
          &weights
            .into_iter()
            .map(|(validator, weight)| (validator, NonZero::new(weight).unwrap()))
            .collect::<BTreeMap<_, _>>(),
          &signature_scheme,
          commit.genesis(),
          commit.block_hash()
        ),
        valid
      );
    };
    // This should verify if the threshold is satisfied
    verify(true, &actual_commit, vec![(0, 1)]);
    // It shouldn't if the threshold isn't satisfied
    verify(false, &actual_commit, vec![(0, 1), (1, 1)]);
    // But this is a weighted threshold, so increasing the validator's weight should be sufficient
    verify(false, &actual_commit, vec![(0, 2), (1, 1)]);
    verify(true, &actual_commit, vec![(0, 3), (1, 1)]);

    // Malleating the signature should cause the commit's verification to fail
    {
      let mut actual_commit = actual_commit.clone();
      *actual_commit.aggregate_signature.last_mut().unwrap() ^= 1;
      verify(false, &actual_commit, vec![(0, 1)]);
    }

    // Test a commit which requires the sum weight from multiple validators
    {
      let aggregate_signature = signature_scheme.aggregate(
        Commit::<<TestSignatureScheme as SignatureScheme>::AggregateSignature>::signature_message(
          commit.genesis(),
          commit.block_number,
          commit.round_number,
          commit.block_hash(),
        ),
        [0, 2, 3].iter().zip(signatures.iter()),
      );
      let actual_commit = Commit {
        block_number: commit.block_number,
        round_number: commit.round_number,
        aggregate_signature,
      };
      assert_eq!(actual_commit.block_number(), commit.block_number);
      verify(true, &actual_commit, vec![(0, 1), (1, 1), (2, 1), (3, 1)]);
    }
  }
}