frostito 0.6.0

nested FROST, hardened DKG, and proactive resharing, on ZF frost-core
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
//! Liveness proofs for custodian participation
//!
//! Ensures custodians are actively running infrastructure by requiring
//! cryptographic proofs of block verification alongside reshare contributions.
//!
//! # Architecture
//!
//! ```text
//! Custodian Node On-Chain
//! ┌──────────────────┐ ┌──────────────────┐
//! │ Verify block N │ │ ReshareState │
//! │ Generate proof │───contribution────▶│ + LivenessProofs │
//! │ Compute NOMT root│ │ verify_all() │
//! └──────────────────┘ └──────────────────┘
//! ```
//!
//! # Integration with Ligerito
//!
//! Uses the existing `ligerito::verify_sha256()` or `verify_blake2b()`
//! to verify that a custodian correctly processed a recent block.

use alloc::vec::Vec;

use crate::curve::{CurvePoint, CurveScalar};
use crate::error::Error;
use crate::reshare::DealerCommitment;

// ============================================================================
// Checkpoint Types
// ============================================================================

/// A checkpoint anchor for liveness proofs
///
/// Represents a known-good block that custodians must prove they've verified.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CheckpointAnchor {
 /// Block height (relay chain or target chain)
 pub height: u64,
 /// Block hash (32 bytes)
 pub block_hash: [u8; 32],
 /// Timestamp (unix seconds)
 pub timestamp: u64,
}

impl CheckpointAnchor {
 pub fn new(height: u64, block_hash: [u8; 32], timestamp: u64) -> Self {
 Self {
 height,
 block_hash,
 timestamp,
 }
 }

 /// Serialize for hashing/signing
 pub fn to_bytes(&self) -> [u8; 48] {
 let mut buf = [0u8; 48];
 buf[0..8].copy_from_slice(&self.height.to_le_bytes());
 buf[8..40].copy_from_slice(&self.block_hash);
 buf[40..48].copy_from_slice(&self.timestamp.to_le_bytes());
 buf
 }

 /// Check if checkpoint is recent enough
 pub fn is_recent(&self, current_height: u64, max_age_blocks: u64) -> bool {
 current_height.saturating_sub(self.height) <= max_age_blocks
 }
}

/// Domain tag for the liveness contribution signature.
pub const LIVENESS_SIG_DOMAIN: &[u8] = b"frostito/liveness-sig/v1";

/// Domain tag for the message a [`DealerContribution`] signature covers.
///
/// `v2` because 0.5.0 length-prefixed the encoding; the `v1` tag was
/// the last `SCREAMING-CASE-V1` string in the crate and its digest differs
/// from this one for every input, so a 0.4.x signature does not verify here
/// and vice versa.
pub const CONTRIBUTION_SIG_MSG_DOMAIN: &[u8] = b"frostito/contribution-sig/v2";

// ============================================================================
// Liveness Proof
// ============================================================================

/// Proof that custodian verified a checkpoint block
///
/// Contains a Ligerito proof of correct block verification.
#[derive(Clone, Debug)]
pub struct LivenessProof {
 /// The checkpoint being attested
 pub anchor: CheckpointAnchor,
 /// Ligerito proof bytes (from verify_sha256 or verify_blake2b)
 pub ligerito_proof: Vec<u8>,
 /// Custodian's local NOMT state root at this checkpoint
 pub state_root: [u8; 32],
}

impl LivenessProof {
 pub fn new(anchor: CheckpointAnchor, ligerito_proof: Vec<u8>, state_root: [u8; 32]) -> Self {
 Self {
 anchor,
 ligerito_proof,
 state_root,
 }
 }

 /// Estimated proof size for gas/weight estimation
 pub fn byte_size(&self) -> usize {
 48 + 4 + self.ligerito_proof.len() + 32
 }

 /// Serialize for on-chain storage
 pub fn to_bytes(&self) -> Vec<u8> {
 let mut buf = Vec::with_capacity(self.byte_size());
 buf.extend_from_slice(&self.anchor.to_bytes());
 buf.extend_from_slice(&(self.ligerito_proof.len() as u32).to_le_bytes());
 buf.extend_from_slice(&self.ligerito_proof);
 buf.extend_from_slice(&self.state_root);
 buf
 }

 /// Deserialize
 pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
 if bytes.len() < 48 + 4 + 32 {
 return Err(Error::InvalidCommitment);
 }

 let height = u64::from_le_bytes(bytes[0..8].try_into().unwrap());
 let block_hash: [u8; 32] = bytes[8..40].try_into().unwrap();
 let timestamp = u64::from_le_bytes(bytes[40..48].try_into().unwrap());
 let anchor = CheckpointAnchor {
 height,
 block_hash,
 timestamp,
 };

 let proof_len = u32::from_le_bytes(bytes[48..52].try_into().unwrap()) as usize;

 if bytes.len() < 52 + proof_len + 32 {
 return Err(Error::InvalidCommitment);
 }

 let ligerito_proof = bytes[52..52 + proof_len].to_vec();
 let state_root: [u8; 32] = bytes[52 + proof_len..52 + proof_len + 32]
 .try_into()
 .unwrap();

 Ok(Self {
 anchor,
 ligerito_proof,
 state_root,
 })
 }
}

// ============================================================================
// Dealer Contribution with Liveness
// ============================================================================

/// Complete dealer contribution for reshare
///
/// Combines reshare commitment with liveness proof.
#[derive(Clone, Debug)]
pub struct DealerContribution<P: CurvePoint> {
 /// Reshare polynomial commitment
 pub commitment: DealerCommitment<P>,
 /// Proof of infrastructure participation
 pub liveness: LivenessProof,
 /// Schnorr signature binding commitment + liveness
 pub signature: ContributionSignature<P>,
}

/// Schnorr signature over contribution
///
/// `r` is held as a point, not as bytes: the curve's canonical compressed
/// encoding is not 32 bytes on every backend (secp256k1 is 33), and carrying
/// bytes meant re-deriving a point from a possibly non-canonical encoding on
/// every verification.
#[derive(Clone)]
pub struct ContributionSignature<P: CurvePoint> {
 /// R = g^k
 pub r: P,
 /// s = k + e * x
 pub s: P::Scalar,
}

impl<P: CurvePoint> ContributionSignature<P> {
 pub fn new(r: P, s: P::Scalar) -> Self {
 Self { r, s }
 }

 /// Byte length of the serialized form.
 #[inline]
 pub fn byte_size() -> usize {
 P::COMPRESSED_SIZE + 32
 }

 pub fn to_bytes(&self) -> Vec<u8> {
 let mut buf = Vec::with_capacity(Self::byte_size());
 buf.extend_from_slice(self.r.compress().as_ref());
 buf.extend_from_slice(&self.s.to_bytes());
 buf
 }

 pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
 if bytes.len() != Self::byte_size() {
 return Err(Error::InvalidCommitment);
 }
 let n = P::COMPRESSED_SIZE;
 let r = P::decompress(&bytes[0..n]).ok_or(Error::InvalidCommitment)?;
 let s = P::Scalar::from_canonical_bytes(&bytes[n..n + 32].try_into().unwrap())
 .ok_or(Error::InvalidResponse)?;
 Ok(Self { r, s })
 }
}

impl<P: CurvePoint> core::fmt::Debug for ContributionSignature<P> {
 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
 f.debug_struct("ContributionSignature")
 .field("r", &hex_short(self.r.compress().as_ref()))
 .field("s", &"[SCALAR]")
 .finish()
 }
}

fn hex_short(bytes: &[u8]) -> alloc::string::String {
 use alloc::format;
 if bytes.len() <= 8 {
 bytes.iter().map(|b| format!("{:02x}", b)).collect()
 } else {
 format!(
 "{}...{}",
 bytes[0..4]
 .iter()
 .map(|b| format!("{:02x}", b))
 .collect::<alloc::string::String>(),
 bytes[bytes.len() - 4..]
 .iter()
 .map(|b| format!("{:02x}", b))
 .collect::<alloc::string::String>()
 )
 }
}

impl<P: CurvePoint> DealerContribution<P> {
 /// Create new contribution (signature must be computed separately)
 pub fn new(
 commitment: DealerCommitment<P>,
 liveness: LivenessProof,
 signature: ContributionSignature<P>,
 ) -> Self {
 Self {
 commitment,
 liveness,
 signature,
 }
 }

 /// Get dealer index
 pub fn dealer_index(&self) -> u32 {
 self.commitment.dealer_index
 }

 /// The message a contribution signature covers.
 ///
 /// ```text
 /// SHA-512(
 /// len(domain):u64 LE ‖ CONTRIBUTION_SIG_MSG_DOMAIN ‖
 /// len(commitment):u64 LE ‖ commitment.to_bytes() ‖
 /// len(liveness):u64 LE ‖ liveness.to_bytes() ‖
 /// len(context):u64 LE ‖ context
 /// )
 /// ```
 ///
 /// # Injectivity
 ///
 /// Until 0.5.0 the four fields were concatenated bare. `DealerCommitment`
 /// serializes as `dealer_index:4 ‖ t compressed points` — variable length,
 /// no prefix, and `from_bytes` needs the threshold out of band.
 /// `LivenessProof` is self-delimiting only once its *start offset* is
 /// known, and that offset is exactly what the missing prefix left
 /// undetermined; `context` is caller-supplied and trailing. So reading
 /// `t+1` coefficients instead of `t` shifted the commitment/liveness
 /// boundary by one point and, where the shifted bytes parsed, produced a
 /// second `(commitment, liveness, context)` triple with the same digest.
 ///
 /// Every variable-length field now carries a `u64` length prefix, so the
 /// encoding is injective and no field can absorb bytes from its
 /// neighbour — the discipline
 /// [`SigningContext::encode`](crate::SigningContext::encode) already
 /// applies and documents.
 ///
 /// The prior severity assessment still stands on the old code: a dealer
 /// only ever signs a commitment it built itself, and a verifier parses
 /// with a threshold pinned out of band, so this was an encoding defect
 /// rather than a live forgery primitive. It rides 0.5.0 because it is
 /// signature-incompatible and 0.5.0 already breaks the wire.
 pub fn signing_message(
 commitment: &DealerCommitment<P>,
 liveness: &LivenessProof,
 context: &[u8],
 ) -> [u8; 64] {
 use sha2::{Digest, Sha512};

 fn field(hasher: &mut sha2::Sha512, bytes: &[u8]) {
 use sha2::Digest;
 hasher.update((bytes.len() as u64).to_le_bytes());
 hasher.update(bytes);
 }

 let mut hasher = Sha512::new();
 field(&mut hasher, CONTRIBUTION_SIG_MSG_DOMAIN);
 field(&mut hasher, &commitment.to_bytes());
 field(&mut hasher, &liveness.to_bytes());
 field(&mut hasher, context);

 hasher.finalize().into()
 }

 /// Sign a contribution
 pub fn sign<R: rand_core::RngCore + rand_core::CryptoRng>(
 commitment: DealerCommitment<P>,
 liveness: LivenessProof,
 secret_key: &P::Scalar,
 context: &[u8],
 rng: &mut R,
 ) -> Self {
 let message = Self::signing_message(&commitment, &liveness, context);

 // Schnorr signature
 let k = P::Scalar::random(rng);
 let r_point = P::generator().mul_scalar(&k);
 let public_key = P::generator().mul_scalar(secret_key);

 // e = H(dom || R || Y || message)
 let e = Self::challenge_hash(&r_point, &public_key, &message);

 // s = k + e * x
 let s = k.add(&e.mul(secret_key));

 let signature = ContributionSignature::new(r_point, s);

 Self {
 commitment,
 liveness,
 signature,
 }
 }

 /// Verify contribution signature
 pub fn verify_signature(&self, public_key: &P, context: &[u8]) -> bool {
 let message = Self::signing_message(&self.commitment, &self.liveness, context);

 // e = H(dom || R || Y || message)
 let e = Self::challenge_hash(&self.signature.r, public_key, &message);

 // Verify: g^s == R + Y^e
 let lhs = P::generator().mul_scalar(&self.signature.s);
 let rhs = self.signature.r.add(&public_key.mul_scalar(&e));

 lhs == rhs
 }

 /// Challenge for the contribution signature.
 ///
 /// `e = H(LIVENESS_SIG_DOMAIN || R || Y || message)`
 ///
 /// # Why the key is in the hash
 ///
 /// Until 0.4.0 this was `SHA512(R || message)`. Verification is
 /// `g^s == R + e·Y` with `e` independent of `Y`, so a valid `(R, s)` under
 /// `Y` became a valid `(R, s + e·delta)` under `Y + delta·G` for any
 /// `delta` — equivalently, an adversary could pick `R` and `s` freely and
 /// back-solve a key for which they verify. Whether that was exploitable
 /// depended on whether the registry established dealer keys with a proof
 /// of possession, which osst does not do either way. RFC 8032 and BIP340
 /// both bind the key into the challenge for exactly this reason.
 ///
 /// The domain tag additionally separates this hash from the OSST
 /// contribution challenge, which it used to equal byte-for-byte.
 pub fn challenge_hash(r: &P, public_key: &P, message: &[u8; 64]) -> P::Scalar {
 use sha2::{Digest, Sha512};

 let mut hasher = Sha512::new();
 hasher.update(LIVENESS_SIG_DOMAIN);
 hasher.update(r.compress());
 hasher.update(public_key.compress());
 hasher.update(message);

 let hash: [u8; 64] = hasher.finalize().into();
 P::Scalar::from_bytes_wide(&hash)
 }
}

// ============================================================================
// Liveness Verifier Trait
// ============================================================================

/// Trait for verifying Ligerito proofs
///
/// Implement this to connect to your on-chain Ligerito verifier.
pub trait LivenessVerifier {
 /// Verify a Ligerito proof for a checkpoint
 fn verify_ligerito_proof(
 &self,
 anchor: &CheckpointAnchor,
 proof: &[u8],
 state_root: &[u8; 32],
 ) -> bool;

 /// Get the current checkpoint anchor
 fn current_anchor(&self) -> CheckpointAnchor;

 /// Maximum age of valid checkpoints (in blocks)
 fn max_checkpoint_age(&self) -> u64;
}

/// Batch verifier for multiple contributions
pub struct ContributionVerifier<'a, P: CurvePoint, V: LivenessVerifier> {
 verifier: &'a V,
 context: &'a [u8],
 _marker: core::marker::PhantomData<P>,
}

impl<'a, P: CurvePoint, V: LivenessVerifier> ContributionVerifier<'a, P, V> {
 pub fn new(verifier: &'a V, context: &'a [u8]) -> Self {
 Self {
 verifier,
 context,
 _marker: core::marker::PhantomData,
 }
 }

 /// Verify a single contribution
 pub fn verify(
 &self,
 contribution: &DealerContribution<P>,
 public_key: &P,
 ) -> Result<(), ContributionError> {
 let current = self.verifier.current_anchor();

 // Check checkpoint is recent
 if !contribution
 .liveness
 .anchor
 .is_recent(current.height, self.verifier.max_checkpoint_age())
 {
 return Err(ContributionError::CheckpointTooOld);
 }

 // Verify Schnorr signature
 if !contribution.verify_signature(public_key, self.context) {
 return Err(ContributionError::InvalidSignature);
 }

 // Verify Ligerito proof
 if !self.verifier.verify_ligerito_proof(
 &contribution.liveness.anchor,
 &contribution.liveness.ligerito_proof,
 &contribution.liveness.state_root,
 ) {
 return Err(ContributionError::InvalidLigerito);
 }

 Ok(())
 }

 /// Verify one contribution against a roster keyed by dealer index.
 ///
 /// # Errors
 ///
 /// [`ContributionError::IndexMismatch`] when the roster has no key for
 /// this contribution's dealer, plus the errors of [`Self::verify`].
 pub fn verify_keyed(
 &self,
 contribution: &DealerContribution<P>,
 public_keys: &[(u32, P)],
 ) -> Result<(), ContributionError> {
 let pk = public_keys
 .iter()
 .find(|(i, _)| *i == contribution.dealer_index())
 .map(|(_, k)| k)
 .ok_or(ContributionError::IndexMismatch)?;
 self.verify(contribution, pk)
 }

 /// Verify multiple contributions, returning the positions of the valid
 /// ones.
 ///
 /// Public keys are looked up by `dealer_index`, not by position: the
 /// previous signature zipped the two lists, so a caller that passed them
 /// in different orders verified every contribution against the wrong key
 /// and the `IndexMismatch` variant was never constructed.
 pub fn verify_batch(
 &self,
 contributions: &[DealerContribution<P>],
 public_keys: &[(u32, P)],
 ) -> Vec<usize> {
 contributions
 .iter()
 .enumerate()
 .filter_map(|(i, contrib)| self.verify_keyed(contrib, public_keys).ok().map(|_| i))
 .collect()
 }
}

/// Contribution verification errors
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ContributionError {
 /// Checkpoint is too old
 CheckpointTooOld,
 /// Schnorr signature invalid
 InvalidSignature,
 /// Ligerito proof invalid
 InvalidLigerito,
 /// Dealer index mismatch
 IndexMismatch,
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(all(test, feature = "ristretto255"))]
mod tests {
 use super::*;
 use crate::reshare::Dealer;
 use curve25519_dalek::{ristretto::RistrettoPoint, scalar::Scalar};
 use rand::rngs::OsRng;

 /// Mock liveness verifier for testing
 struct MockVerifier {
 current_height: u64,
 max_age: u64,
 }

 impl LivenessVerifier for MockVerifier {
 fn verify_ligerito_proof(
 &self,
 _anchor: &CheckpointAnchor,
 proof: &[u8],
 _state_root: &[u8; 32],
 ) -> bool {
 // Accept any non-empty proof in tests
 !proof.is_empty()
 }

 fn current_anchor(&self) -> CheckpointAnchor {
 CheckpointAnchor::new(self.current_height, [0u8; 32], 0)
 }

 fn max_checkpoint_age(&self) -> u64 {
 self.max_age
 }
 }

 /// the pre-0.5.0 contribution message concatenated the domain tag,
 /// the commitment, the liveness proof and the context with no length
 /// prefixes, and `DealerCommitment::to_bytes` is variable-length with the
 /// threshold supplied out of band. So the commitment/liveness boundary was
 /// undetermined and the encoding was not injective.
 ///
 /// This builds an explicit collision against the old rule — two distinct
 /// `(commitment, liveness)` pairs whose bare concatenations are equal
 /// byte-for-byte, the second commitment carrying one extra coefficient
 /// that the first pair spends on the head of its liveness proof — and
 /// asserts that the length-prefixed v2 message separates them.
 #[test]
 fn contribution_message_is_injective_across_the_commitment_boundary() {
 let mut rng = OsRng;
 let g = <RistrettoPoint as CurvePoint>::generator();
 let p1 = g.mul_scalar(&Scalar::random(&mut rng));
 let p2 = g.mul_scalar(&Scalar::random(&mut rng));
 // the extra coefficient, which pair A instead reads as the first 32
 // bytes of its anchor
 let x = g.mul_scalar(&Scalar::random(&mut rng));
 let x_bytes = CurvePoint::compress(&x);

 // --- pair A: two coefficients, the extra point absorbed by the anchor
 let commitment_a = DealerCommitment::<RistrettoPoint> {
 dealer_index: 7,
 coefficients: vec![p1, p2],
 };
 let height_a = u64::from_le_bytes(x_bytes[0..8].try_into().unwrap());
 let mut block_hash_a = [0u8; 32];
 block_hash_a[0..24].copy_from_slice(&x_bytes[8..32]);
 block_hash_a[24..32].copy_from_slice(&[0xA1; 8]);
 let timestamp_a = 0x0102_0304_0506_0708u64;
 // 32 proof bytes whose last four are zero: those four are pair B's
 // proof length, and it must read as empty
 let mut proof_a = [0x5Au8; 32];
 proof_a[28..32].copy_from_slice(&0u32.to_le_bytes());
 let state_root = [0xC3u8; 32];
 let liveness_a = LivenessProof::new(
 CheckpointAnchor::new(height_a, block_hash_a, timestamp_a),
 proof_a.to_vec(),
 state_root,
 );

 // --- pair B: three coefficients, its liveness proof made of the
 // bytes pair A spent on the tail of its anchor and its proof
 let commitment_b = DealerCommitment::<RistrettoPoint> {
 dealer_index: 7,
 coefficients: vec![p1, p2, x],
 };
 let tail = &liveness_a.to_bytes()[32..];
 let liveness_b = LivenessProof::from_bytes(tail).expect("tail parses as a liveness proof");

 let context = b"osst-epoch-42";

 // the old rule: domain ‖ commitment ‖ liveness ‖ context, bare
 let old = |c: &DealerCommitment<RistrettoPoint>, l: &LivenessProof| {
 use sha2::{Digest, Sha512};
 let mut h = Sha512::new();
 h.update(b"OSST-CONTRIBUTION-V1");
 h.update(c.to_bytes());
 h.update(l.to_bytes());
 h.update(context);
 let out: [u8; 64] = h.finalize().into();
 out
 };

 assert_ne!(
 commitment_a.to_bytes(),
 commitment_b.to_bytes(),
 "the two commitments must genuinely differ"
 );
 assert_eq!(
 old(&commitment_a, &liveness_a),
 old(&commitment_b, &liveness_b),
 "the pre-0.5.0 encoding really did collide here"
 );

 assert_ne!(
 DealerContribution::<RistrettoPoint>::signing_message(
 &commitment_a,
 &liveness_a,
 context
 ),
 DealerContribution::<RistrettoPoint>::signing_message(
 &commitment_b,
 &liveness_b,
 context
 ),
 "length prefixes must separate the two triples"
 );
 }

 /// The context field is trailing; a length prefix must stop it absorbing
 /// bytes from, or donating bytes to, its neighbour.
 #[test]
 fn contribution_message_separates_the_context_field() {
 let mut rng = OsRng;
 let dealer: Dealer<RistrettoPoint> =
 Dealer::new(1, Scalar::random(&mut rng), 3, &mut rng).expect("index is 1-indexed by construction");
 let commitment = dealer.commitment().clone();
 let liveness = LivenessProof::new(
 CheckpointAnchor::new(100, [1u8; 32], 1234567890),
 vec![1, 2, 3, 4],
 [2u8; 32],
 );
 assert_ne!(
 DealerContribution::<RistrettoPoint>::signing_message(&commitment, &liveness, b"ab"),
 DealerContribution::<RistrettoPoint>::signing_message(&commitment, &liveness, b"abc"),
 );
 }

 #[test]
 fn test_contribution_sign_verify() {
 let mut rng = OsRng;

 // Generate dealer key
 let secret = Scalar::random(&mut rng);
 let public: RistrettoPoint = RistrettoPoint::generator().mul_scalar(&secret);

 // Create dealer and commitment
 let dealer: Dealer<RistrettoPoint> = Dealer::new(1, Scalar::random(&mut rng), 3, &mut rng).expect("index is 1-indexed by construction");
 let commitment = dealer.commitment().clone();

 // Create liveness proof
 let anchor = CheckpointAnchor::new(100, [1u8; 32], 1234567890);
 let liveness = LivenessProof::new(anchor, vec![1, 2, 3, 4], [2u8; 32]);

 // Sign contribution
 let context = b"test-epoch-42";
 let contribution =
 DealerContribution::sign(commitment, liveness, &secret, context, &mut rng);

 // Verify signature
 assert!(contribution.verify_signature(&public, context));

 // Wrong context should fail
 assert!(!contribution.verify_signature(&public, b"wrong-context"));

 // Wrong public key should fail
 let wrong_public: RistrettoPoint =
 RistrettoPoint::generator().mul_scalar(&Scalar::random(&mut rng));
 assert!(!contribution.verify_signature(&wrong_public, context));
 }

 #[test]
 fn test_contribution_verifier() {
 let mut rng = OsRng;

 let verifier = MockVerifier {
 current_height: 100,
 max_age: 10,
 };

 let secret = Scalar::random(&mut rng);
 let public: RistrettoPoint = RistrettoPoint::generator().mul_scalar(&secret);

 let dealer: Dealer<RistrettoPoint> = Dealer::new(1, Scalar::random(&mut rng), 3, &mut rng).expect("index is 1-indexed by construction");
 let commitment = dealer.commitment().clone();

 // Recent checkpoint - should pass
 let anchor = CheckpointAnchor::new(95, [1u8; 32], 0);
 let liveness = LivenessProof::new(anchor, vec![1, 2, 3], [0u8; 32]);
 let context = b"epoch-1";

 let contribution =
 DealerContribution::sign(commitment.clone(), liveness, &secret, context, &mut rng);

 let cv = ContributionVerifier::<RistrettoPoint, _>::new(&verifier, context);
 assert!(cv.verify(&contribution, &public).is_ok());

 // Old checkpoint - should fail
 let old_anchor = CheckpointAnchor::new(50, [1u8; 32], 0);
 let old_liveness = LivenessProof::new(old_anchor, vec![1, 2, 3], [0u8; 32]);

 let old_contribution =
 DealerContribution::sign(commitment, old_liveness, &secret, context, &mut rng);

 assert_eq!(
 cv.verify(&old_contribution, &public),
 Err(ContributionError::CheckpointTooOld)
 );
 }

 #[test]
 fn test_checkpoint_serialization() {
 let anchor = CheckpointAnchor::new(12345, [0xab; 32], 1700000000);
 let bytes = anchor.to_bytes();

 assert_eq!(bytes.len(), 48);
 assert_eq!(u64::from_le_bytes(bytes[0..8].try_into().unwrap()), 12345);
 }

 #[test]
 fn test_liveness_proof_serialization() {
 let anchor = CheckpointAnchor::new(100, [1u8; 32], 123);
 let proof = LivenessProof::new(anchor.clone(), vec![1, 2, 3, 4, 5], [2u8; 32]);

 let bytes = proof.to_bytes();
 let recovered = LivenessProof::from_bytes(&bytes).unwrap();

 assert_eq!(recovered.anchor, anchor);
 assert_eq!(recovered.ligerito_proof, vec![1, 2, 3, 4, 5]);
 assert_eq!(recovered.state_root, [2u8; 32]);
 }
}