tributary-framework 0.1.1

A mini-blockchain framework, intended for being embedded into applications
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
use core::{ops::Deref as _, convert::AsRef};
use alloc::{boxed::Box, vec::Vec, vec};

use zeroize::Zeroizing;
use rand::rngs::OsRng;

use blake2::{
  digest::{Digest as _, CustomizedInit as _},
  Blake2b512,
};
use ciphersuite::{
  group::{ff::{PrimeField, FromUniformBytes as _}, GroupEncoding},
  Ciphersuite,
};
use dalek_ff_group::Ristretto;
use schnorr::{
  SchnorrSignature,
  aggregate::{SchnorrAggregator, SchnorrAggregate},
};

use borsh::{
  io::{self, Read, Write},
  BorshSerialize, BorshDeserialize,
};
use tendermint::InvalidAggregateSignature;

/// The DST used for aggregating Schnorr signatures.
const AGGREGATOR_DST: &[u8] = b"Tributary Tendermint Commit Aggregator";

/// A transcript which has already been scoped to a message.
///
/// The `SignatureScheme` API expected by `tendermint-consensus` supports aggregation where
/// multiple signers sign the same message and then non-interactively produce a single signature.
/// Because the messages are the same, we first transcript the message, _then_ the signer's key and
/// nonce. If we hashed the signer's key and nonce _first_, as traditional, we'd have to re-hash
/// the message for each signer. This is safe, without a risk of collisions, as the length of the
/// signer's key and nonce is constant.
#[derive(Clone)]
struct MessageScopedTranscript(Blake2b512);
impl MessageScopedTranscript {
  fn challenge(self, key: [u8; 32], nonce: &[u8]) -> <Ristretto as Ciphersuite>::F {
    <Ristretto as Ciphersuite>::F::from_uniform_bytes(
      &self.0.chain_update(key).chain_update(nonce).finalize().into(),
    )
  }
}

#[test]
fn message_scoped_transcript() {
  let transcript = MessageScopedTranscript(Blake2b512::new());

  let rand_bytes = || {
    use rand::RngCore as _;

    let mut bytes = [0; 32];
    rand::rngs::OsRng.fill_bytes(&mut bytes);
    bytes
  };

  let key_a = rand_bytes();
  let key_b = rand_bytes();

  let nonce_a = rand_bytes();
  let nonce_b = rand_bytes();

  // This should be consistent if quieried multiple times, not mutated
  assert_eq!(
    transcript.clone().challenge(key_a, &nonce_a),
    transcript.clone().challenge(key_a, &nonce_a)
  );
  // Yet either the key or the nonce being different should produce a different challenge
  assert_ne!(
    transcript.clone().challenge(key_a, &nonce_a),
    transcript.clone().challenge(key_b, &nonce_a)
  );
  assert_ne!(
    transcript.clone().challenge(key_a, &nonce_a),
    transcript.clone().challenge(key_a, &nonce_b)
  );
  assert_ne!(
    transcript.clone().challenge(key_a, &nonce_a),
    transcript.clone().challenge(key_b, &nonce_b)
  );
}

/// The signature scheme for a Tendermint process.
///
/// This is bound to the genesis hash of the Tributary, providing domain-separation across
/// Tributaries.
// TODO: We currently represent validators as `[u8; 32]`, the byte representation of their public
// keys. Should we represent them as `u16`, as possible by also including a sorted list of
// validators here?
#[derive(Clone)]
pub(crate) struct SignatureScheme {
  genesis_scoped_transcript: Blake2b512,
  validators: usize,
}

/// A signer for a signature scheme for a Tendermint process.
///
/// This is scoped to a specific signature scheme (and therefore a specific Tributary).
#[derive(Clone)]
pub(crate) struct Signer {
  signature_scheme: SignatureScheme,
  private_key: Zeroizing<<Ristretto as Ciphersuite>::F>,
  public_key: [u8; 32],
}

impl SignatureScheme {
  /// Instance a new signature scheme for Tendermint, scoped to a specific Tributary.
  pub(crate) fn new(genesis: [u8; 32], validators: usize) -> Self {
    Self {
      // Initialize the transcripts for Tendermint with a customization of "tendermint", ensuring a
      // separate domain then the Tributary itself will use for its transcripts.
      genesis_scoped_transcript: Blake2b512::new_customized(b"tendermint").chain_update(genesis),
      validators,
    }
  }

  /// Instance a signer for this signature scheme.
  pub(crate) fn signer(&self, private_key: Zeroizing<<Ristretto as Ciphersuite>::F>) -> Signer {
    let public_key = (Ristretto::generator() * private_key.deref()).to_bytes();
    Signer { signature_scheme: self.clone(), private_key, public_key }
  }

  /// Scope a transcript from this signature scheme to a specific message.
  ///
  /// The message-scoped transcript may then be scoped to a specific signer, nonce, to obtain the
  /// signature's challenge.
  fn message_scope(
    &self,
    message: impl IntoIterator<Item: AsRef<[u8]>>,
  ) -> MessageScopedTranscript {
    let mut transcript = self.genesis_scoped_transcript.clone();
    for message_part in message {
      transcript.update(message_part);
    }
    MessageScopedTranscript(transcript)
  }
}

#[test]
fn genesis_scoped_transcript() {
  let rand_scheme = || {
    use rand::RngCore as _;

    let mut bytes = [0; 32];
    rand::rngs::OsRng.fill_bytes(&mut bytes);
    SignatureScheme::new(bytes, 1)
  };

  let scheme = rand_scheme();

  // This should be binding to a genesis
  assert_ne!(
    scheme.genesis_scoped_transcript.clone().finalize(),
    rand_scheme().genesis_scoped_transcript.finalize()
  );

  // This should handle messages by their concatenation
  assert_eq!(
    scheme.message_scope([*b"a", *b"b"]).0.finalize(),
    scheme.message_scope([b"ab"]).0.finalize()
  );
  // This should be binding to the message
  assert_ne!(scheme.message_scope([b"a"]).0.finalize(), scheme.message_scope([b"b"]).0.finalize());
}

/// The type for an aggregate signature.
///
/// This contains the _serialization_ of a [`schnorr::aggregate::SchnorrAggregate`]. It may or may
/// not be valid.
#[derive(Clone)]
#[cfg_attr(test, derive(PartialEq, Eq, Debug))]
pub struct AggregateSignature(Box<[u8]>);
impl AsRef<[u8]> for AggregateSignature {
  fn as_ref(&self) -> &[u8] {
    self.0.as_ref()
  }
}

impl AggregateSignature {
  /// The amount of validators within this aggregate signature.
  fn validators(&self) -> usize {
    /*
      The serialization is a list of signers, and their nonces, nonces followed by a single scalar.
      We solely need to determine the length of the list of signers and their nonces to know how
      many signers were included.

      This can be minorly optimized as `self.0.len() / (32 + 32)`, relying on the integer division
      to truncate the `32` bytes for the scalar. The lack of clarity that would incur isn't
      preferable though.
    */
    #[expect(clippy::manual_assert)]
    const {
      if core::mem::size_of::<<<Ristretto as Ciphersuite>::G as GroupEncoding>::Repr>() != 32 {
        panic!("(memory) representation of a Ristretto point's encoding wasn't 32 bytes")
      }
      if core::mem::size_of::<<<Ristretto as Ciphersuite>::F as PrimeField>::Repr>() != 32 {
        panic!("(memory) representation of a Ristretto scalar's encoding wasn't 32 bytes")
      }
    }
    let validators = (self.0.len() - 32) / (32 + 32);
    debug_assert_eq!((validators * (32 + 32)) + 32, self.0.len());
    validators
  }
}

impl BorshSerialize for AggregateSignature {
  fn serialize<W: Write>(&self, writer: &mut W) -> Result<(), io::Error> {
    /*
      We use `u16` to represent the amount of validators included due to Tendermint having the
      following definition:

      ```rs
      trait ValidatorSet {
        ...
        fn total_weight(&self) -> NonZero<u16>;
        ...
      }

      which means any legitimate aggregate signature will have at most `u16::MAX` weight and
      therefore `u16::MAX` validators.
    */
    writer.write_all(
      &u16::try_from(self.validators())
        .map_err(|_| {
          io::Error::other("aggregate signature has more validators than possible weight")
        })?
        .to_le_bytes(),
    )?;
    writer.write_all(&self.0)
  }
}
impl BorshDeserialize for AggregateSignature {
  fn deserialize_reader<R: Read>(reader: &mut R) -> Result<Self, io::Error> {
    let validators = {
      let mut bytes = [0; 2];
      reader.read_exact(&mut bytes)?;
      u16::from_le_bytes(bytes)
    };

    let len =
      usize::from(validators).checked_mul(32 + 32).and_then(|len| len.checked_add(32)).ok_or_else(
        || io::Error::other("length of aggregate signature overflowed platform's `usize`"),
      )?;

    let mut result = vec![0; len].into_boxed_slice();
    reader.read_exact(&mut result)?;
    Ok(Self(result))
  }
}

impl tendermint::SignatureScheme for SignatureScheme {
  // The byte representation of the validator's public key
  type Validator = [u8; 32];
  // The byte representation of a Schnorr signature
  type Signature = [u8; 64];
  type AggregateSignature = AggregateSignature;

  fn verify(
    &self,
    validator: &Self::Validator,
    message: impl IntoIterator<Item = impl AsRef<[u8]>>,
    signature: &Self::Signature,
  ) -> bool {
    let challenge = self.message_scope(message).challenge(*validator, &signature[.. 32]);
    /*
      We are not required to confirm this 'validator' is actually a validator with weight, hence
      why we solely decode and verify the corresponding signature.

      If we do represent validators by their index, then this property would become almost inherent
      however.
    */
    let Ok(validator) = Ristretto::read_G(&mut validator.as_slice()) else {
      return false;
    };
    let Ok(signature) = SchnorrSignature::<Ristretto>::read(signature.as_slice()) else {
      return false;
    };
    signature.verify(validator, challenge)
  }

  fn aggregate<'sig>(
    &self,
    message: impl IntoIterator<Item = impl AsRef<[u8]>>,
    signatures: impl IntoIterator<Item = (&'sig Self::Validator, &'sig Self::Signature)>,
  ) -> Self::AggregateSignature
  where
    Self::Validator: 'sig,
    Self::Signature: 'sig,
  {
    let transcript = self.message_scope(message);
    let signatures = signatures.into_iter();

    let sorted = {
      let mut sorted = Vec::with_capacity({
        let (lower, _upper) = signatures.size_hint();
        lower
      });
      for signature in signatures {
        sorted.push(signature);
      }
      sorted.sort_by_key(|(validator, _signature)| **validator);
      sorted
    };

    let mut result = Vec::with_capacity((sorted.len() * (32 + 32)) + 32);
    let mut aggregator = SchnorrAggregator::<Ristretto>::new(AGGREGATOR_DST);
    for (validator, signature) in sorted {
      result.write_all(validator).expect("`<Vec<_> as io::Write>` is infallible");

      let challenge = transcript.clone().challenge(*validator, &signature[.. 32]);
      let signature = SchnorrSignature::<Ristretto>::read(signature.as_slice())
        .expect("asked to aggregate an invalid signature");
      aggregator.aggregate(challenge, signature);
    }
    let aggregate = aggregator.complete().expect("asked to aggregate no signatures");
    aggregate.write(&mut result).expect("`<Vec<_> as io::Write>` is infallible");

    AggregateSignature(result.into_boxed_slice())
  }

  fn verify_aggregate(
    &self,
    message: impl IntoIterator<Item = impl AsRef<[u8]>>,
    aggregate_signature: &Self::AggregateSignature,
  ) -> Result<impl IntoIterator<Item = Self::Validator>, InvalidAggregateSignature> {
    let transcript = self.message_scope(message);

    let (validators, aggregate_signature) = {
      let validators_len = aggregate_signature.validators();
      if validators_len > self.validators {
        Err(InvalidAggregateSignature)?;
      }
      let aggregate_signature = aggregate_signature.as_ref();

      let (validators, mut aggregate_signature) = aggregate_signature.split_at(validators_len * 32);

      let (validators, []) = validators.as_chunks::<32>() else {
        panic!("multiple of `32` wasn't evenly divisible into chunks of length `32`")
      };
      // Ensure the validators were sorted, ensuring no validators were present multiple times
      if !validators.is_sorted_by(|a, b| a < b) {
        Err(InvalidAggregateSignature)?;
      }

      let aggregate_signature = {
        let Ok(aggregate_signature_value) =
          SchnorrAggregate::<Ristretto>::read(&mut aggregate_signature, validators_len)
        else {
          Err(InvalidAggregateSignature)?
        };
        debug_assert_eq!(aggregate_signature, &[]);
        aggregate_signature_value
      };

      (validators, aggregate_signature)
    };

    let mut challenges = vec![];
    for (validator, nonce) in validators.iter().zip(aggregate_signature.Rs()) {
      let challenge = transcript.clone().challenge(*validator, nonce.to_bytes().as_ref());
      let Ok(validator) = <Ristretto as Ciphersuite>::read_G(&mut validator.as_slice()) else {
        Err(InvalidAggregateSignature)?
      };
      challenges.push((validator, challenge));
    }

    if !aggregate_signature.verify(AGGREGATOR_DST, &challenges) {
      Err(InvalidAggregateSignature)?;
    }

    Ok(validators.iter().copied())
  }
}

impl tendermint::Signer for Signer {
  type Validator = [u8; 32];
  type Signature = [u8; 64];

  fn validator(&self) -> Self::Validator {
    self.public_key
  }

  type SignFuture = core::future::Ready<Self::Signature>;
  fn sign(&self, message: impl IntoIterator<Item = impl AsRef<[u8]>>) -> Self::SignFuture {
    let transcript = self.signature_scheme.message_scope(message);

    let nonce = Zeroizing::new(<Ristretto as Ciphersuite>::F::random(&mut OsRng));
    let challenge = transcript
      .challenge(self.public_key, (Ristretto::generator() * nonce.deref()).to_bytes().as_ref());
    let signature = SchnorrSignature::<Ristretto>::sign(&self.private_key, nonce, challenge);

    core::future::ready(crate::fixed_write::<{ 32 + 32 }>(|writer| signature.write(writer)))
  }
}

#[cfg(test)]
#[tokio::test]
async fn sign() {
  use ::tendermint::{SignatureScheme as _, Signer as _};

  let genesis = [0xfe; 32];
  let signature_scheme = SignatureScheme::new(genesis, 4);
  let key = Zeroizing::new(<Ristretto as Ciphersuite>::F::random(&mut OsRng));
  let signer = signature_scheme.signer(key);
  const MESSAGE: [&[u8]; 1] = [b"abc"];
  const OTHER_MESSAGE: [&[u8]; 1] = [b"def"];
  let signature = signer.sign(MESSAGE).await;
  assert!(signature_scheme.verify(&signer.validator(), MESSAGE, &signature));
  assert!(!signature_scheme.verify(&signer.validator(), OTHER_MESSAGE, &signature));
}

#[cfg(test)]
#[tokio::test]
async fn aggregate() {
  use ::tendermint::{SignatureScheme as _, Signer as _};

  let genesis = [0xfe; 32];
  let signature_scheme = SignatureScheme::new(genesis, 4);

  let alice =
    signature_scheme.signer(Zeroizing::new(<Ristretto as Ciphersuite>::F::random(&mut OsRng)));
  let bob =
    signature_scheme.signer(Zeroizing::new(<Ristretto as Ciphersuite>::F::random(&mut OsRng)));

  const MESSAGE: [&[u8]; 1] = [b"abc"];
  const OTHER_MESSAGE: [&[u8]; 1] = [b"def"];

  let test = async move |signature_scheme: &SignatureScheme, signers: &[&Signer]| {
    let mut aggregate = vec![];
    for signer in signers {
      aggregate.push((signer.validator(), signer.sign(MESSAGE).await));
    }
    let aggregate = signature_scheme
      .aggregate(MESSAGE, aggregate.iter().map(|(signer, signature)| (signer, signature)));

    assert_eq!(aggregate.validators(), signers.len());

    {
      let deserialized_aggregate = {
        let aggregate = borsh::to_vec(&aggregate).unwrap();
        let mut aggregate = aggregate.as_slice();
        let deserialized_aggregate =
          AggregateSignature::deserialize_reader(&mut aggregate).unwrap();
        assert_eq!(aggregate, []);
        deserialized_aggregate
      };
      assert_eq!(aggregate, deserialized_aggregate);
    }

    let mut validators = signers.iter().copied().map(Signer::validator).collect::<Vec<_>>();
    validators.sort_unstable();
    assert_eq!(
      signature_scheme
        .verify_aggregate(MESSAGE, &aggregate)
        .unwrap()
        .into_iter()
        .collect::<Vec<_>>(),
      validators
    );
    assert!(signature_scheme.verify_aggregate(OTHER_MESSAGE, &aggregate).is_err());
  };

  test(&signature_scheme, &[&alice]).await;
  test(&signature_scheme, &[&bob]).await;
  test(&signature_scheme, &[&alice, &bob]).await;
}