ms_codec/shares.rs
1//! K-of-N codex32 Shamir share encoding (ms v0.2).
2//!
3//! A secret (`entr` or `mnem`) splits into N shares, any K of which recombine
4//! to the original — using codex32's *native* threshold(k)+index Shamir
5//! mechanism, NOT a payload byte (SPEC_ms_v0_2_kofn §1). The codex32 header
6//! threshold char is the share-vs-single discriminator; the prefix byte
7//! (`0x00`=entr / `0x02`=mnem) remains the payload-KIND discriminator, recovered
8//! only on the secret-at-S after interpolation.
9//!
10//! v0.1/mnem single-strings stay byte-identical: `encode_shares(tag, ZERO, 1, &p)`
11//! reduces to the exact `package()`/`encode()` construction (the Phase-0 gate).
12
13use crate::consts::{HRP, RESERVED_ID_BLOCKLIST, SHARE_INDEX_V01};
14use crate::envelope::{dispatch_payload, extract_wire_fields, payload_wire_bytes, wire_string};
15use crate::error::{Error, Result};
16use crate::payload::Payload;
17use crate::tag::Tag;
18use codex32::{Codex32String, Fe};
19use zeroize::Zeroizing;
20
21/// The codex32 bech32 alphabet (32 chars). Index `s` (position 16) is the
22/// secret-at-S index — never a distributed-share index.
23const CODEX32_ALPHABET: &[u8; 32] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
24
25/// The 31 valid non-`s` share indices, taken from the bech32 alphabet in its
26/// own order with `s` removed (deterministic, front-to-back). `n <= 31` is
27/// enforced by `encode_shares`, so this pool never runs out.
28fn non_s_index_pool() -> Vec<Fe> {
29 CODEX32_ALPHABET
30 .iter()
31 .filter(|&&b| b != b's')
32 .map(|&b| Fe::from_char(b as char).expect("alphabet char is a valid Fe"))
33 .collect()
34}
35
36/// Generate a random 4-char codex32-alphabet `id`, re-rolling while it lands in
37/// `RESERVED_ID_BLOCKLIST` (a v0.1 type-tag-shaped value). Uses `getrandom`
38/// (0.3.x `getrandom::fill`) — no injected-RNG param (the `mk_codec::encode`
39/// precedent).
40fn random_id() -> String {
41 loop {
42 let mut raw = [0u8; 4];
43 getrandom::fill(&mut raw).expect("getrandom::fill must not fail");
44 let id: [u8; 4] = [
45 CODEX32_ALPHABET[(raw[0] & 0x1f) as usize],
46 CODEX32_ALPHABET[(raw[1] & 0x1f) as usize],
47 CODEX32_ALPHABET[(raw[2] & 0x1f) as usize],
48 CODEX32_ALPHABET[(raw[3] & 0x1f) as usize],
49 ];
50 if !RESERVED_ID_BLOCKLIST.contains(&id) {
51 // Every byte is a codex32-alphabet ASCII char → always valid UTF-8.
52 return String::from_utf8(id.to_vec()).expect("codex32 alphabet is ASCII");
53 }
54 }
55}
56
57/// A codex32 share threshold.
58///
59/// `ZERO` is the unshared v0.1 single-string sentinel (codex32 threshold `0`,
60/// share-index `s`); `new(k)` accepts a K-of-N share threshold `k in 2..=9`
61/// (codex32 `from_seed` accepts threshold `0` or `2..=9` only — `1` is invalid).
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub struct Threshold(u8);
64
65impl Threshold {
66 /// The unshared single-string sentinel (threshold `0`). A const, NOT
67 /// `new(0)` — `new` only admits the K-of-N share range `2..=9`.
68 pub const ZERO: Threshold = Threshold(0);
69
70 /// Construct a K-of-N share threshold. `k` MUST be in `2..=9`, else
71 /// `Error::InvalidThreshold(k)`.
72 pub fn new(k: u8) -> Result<Threshold> {
73 if (2..=9).contains(&k) {
74 Ok(Threshold(k))
75 } else {
76 Err(Error::InvalidThreshold(k))
77 }
78 }
79
80 /// The threshold value (`0` for `ZERO`, `2..=9` for a share threshold).
81 pub fn get(self) -> u8 {
82 self.0
83 }
84}
85
86/// Split a secret (`entr` or `mnem`) into `n` codex32 K-of-N shares.
87///
88/// - `threshold == ZERO`: `n` MUST be 1; returns a single string **byte-identical**
89/// to `encode(tag, secret)` — the v0.1 single-string construction
90/// (`from_seed(HRP, 0, tag, Fe::S, [prefix]||payload)`, deterministic). The
91/// `id` stays the type `tag` (NOT random) — load-bearing for byte-identity.
92/// - `threshold == k ∈ 2..=9`: validate `k <= n <= 31` (else `InvalidShareCount`).
93/// A random 4-char `id` (not in `RESERVED_ID_BLOCKLIST`) keys the share-set.
94/// The secret-at-S (`Fe::S`) holds the real payload; `k-1` random **defining
95/// shares** at fixed canonical non-`s` indices + `interpolate_at` for the
96/// remaining `n-(k-1)` indices produce the `n` **distributed** shares. The
97/// secret-at-S is NEVER returned (it is the recovery target only).
98///
99/// Works identically for `entr` and `mnem` (byte-agnostic); language survives a
100/// `mnem` split (it rides the secret-at-S wire bytes).
101pub fn encode_shares(
102 tag: Tag,
103 threshold: Threshold,
104 n: usize,
105 secret: &Payload,
106) -> Result<Vec<String>> {
107 secret.validate()?;
108 let bytes = payload_wire_bytes(secret);
109
110 if threshold == Threshold::ZERO {
111 // Unshared single-string: must be n==1; byte-identical to encode().
112 if n != 1 {
113 return Err(Error::InvalidShareCount { k: 0, n });
114 }
115 let single = Codex32String::from_seed(HRP, 0, tag.as_str(), Fe::S, &bytes[..])?;
116 return Ok(vec![single.to_string()]);
117 }
118
119 let k = threshold.get();
120 let k_usize = k as usize;
121 // Bounds (SPEC §1): 2 <= k <= n <= 31 (31 valid non-`s` indices).
122 if !(k_usize <= n && n <= 31) {
123 return Err(Error::InvalidShareCount { k, n });
124 }
125
126 let id = random_id();
127 let pool = non_s_index_pool();
128
129 // 1. secret-at-S carries the real payload at index `s`, threshold `k`.
130 let secret_s = Codex32String::from_seed(HRP, k_usize, &id, Fe::S, &bytes[..])?;
131
132 // 2. k-1 random DEFINING shares at the first k-1 pool indices. Each gets a
133 // CSPRNG payload of the SAME byte length as the secret (Zeroizing scrub).
134 // The defining set [secret_s, def_1..def_{k-1}] is k points → fully
135 // determines the Shamir polynomial.
136 let mut defining: Vec<Codex32String> = Vec::with_capacity(k_usize);
137 defining.push(secret_s);
138 for pool_idx in pool.iter().take(k_usize - 1) {
139 let mut filler: Zeroizing<Vec<u8>> = Zeroizing::new(vec![0u8; bytes.len()]);
140 getrandom::fill(&mut filler[..]).expect("getrandom::fill must not fail");
141 let share = Codex32String::from_seed(HRP, k_usize, &id, *pool_idx, &filler[..])?;
142 defining.push(share);
143 }
144
145 // 3. The n DISTRIBUTED shares: the k-1 defining shares (indices 0..k-1) plus
146 // interpolation-derived shares at the remaining n-(k-1) pool indices.
147 // The secret-at-S (defining[0]) is NEVER distributed.
148 let mut distributed: Vec<String> = Vec::with_capacity(n);
149 for share in defining.iter().skip(1) {
150 distributed.push(share.to_string());
151 }
152 for pool_idx in pool.iter().take(n).skip(k_usize - 1) {
153 let derived = Codex32String::interpolate_at(&defining, *pool_idx)?;
154 distributed.push(derived.to_string());
155 }
156
157 debug_assert_eq!(distributed.len(), n);
158 Ok(distributed)
159}
160
161/// Recombine `k` (or more) distributed shares of a K-of-N share-set into the
162/// original secret `(Tag, Payload)`.
163///
164/// Pre-validation runs BEFORE `interpolate_at` because codex32's
165/// `interpolate_at` short-circuits when the target index (`s`) is among the
166/// inputs (`lib.rs:262`) — bypassing its own payload validation. Order:
167/// 1. parse each share (`Error::Codex32` on failure — preserves the
168/// within-one-string mixed-case `InvalidCase` rejection), then re-parse the
169/// lowercased copy into the CANONICAL vector (BIP-173 uppercase QR form
170/// folds to canonical lowercase; codex32's `interpolate_at` does raw
171/// case-sensitive cross-share hrp/id compares, so canonicalization here —
172/// not field extraction — is what makes an uppercase or mixed-case SET
173/// combine, and what lets the index-`s` guard below see `b's'`);
174/// 2. **reject any share at index `s`** → `SecretShareSuppliedToCombine` (C1 —
175/// the secret-at-S is the recovery target, never a combine input);
176/// 3. `shares.len() >= k` (the first share's threshold) else surface
177/// `ThresholdNotPassed`;
178/// 4. distinct share indices else `RepeatedIndex` (codex32's own check is lazy);
179/// 5. recover the secret-at-S from EXACTLY the first `k` shares (which define
180/// the polynomial) via `interpolate_at(&parsed[..k], Fe::S)` (surfaces
181/// `Mismatched{Hrp,Id,Threshold,Length}` on a header-inconsistent k-set),
182/// then verify every EXTRA supplied share lies on that same polynomial
183/// (`interpolate_at(k_set, idx)` re-derived value must equal the supplied
184/// share) → `InconsistentShareSet` on any mismatch. (M6 — codex32 K-of-N
185/// carries no digest share; a same-id but cross-polynomial set previously
186/// combined to a SILENT WRONG secret. A valid exactly-k or n>k all-consistent
187/// combine is bit-identical to the prior all-shares interpolation.)
188///
189/// Returns **`(Tag::ENTR, …)`** always: the recovered secret-at-S carries the
190/// share-set's RANDOM `id` (NOT a type tag); the payload KIND is the prefix byte
191/// (via `dispatch_payload`), so the random id is discarded. (We do NOT route
192/// through `discriminate` — it would rebuild a `Tag` from the random id.)
193pub fn combine_shares(shares: &[String]) -> Result<(Tag, Payload)> {
194 // 1. Parse each share (map codex32 parse/checksum failure via Error::Codex32).
195 let parsed: Vec<Codex32String> = shares
196 .iter()
197 .map(|s| Codex32String::from_string(s.clone()).map_err(Error::Codex32))
198 .collect::<Result<Vec<_>>>()?;
199
200 // 1b. Canonicalize: re-parse each share's lowercased wire copy (NEVER
201 // lowercase before the first parse above — that would launder the
202 // within-one-string mixed-case `InvalidCase` rejection). codex32's
203 // checksum engine case-folds, so this re-parse is infallible in
204 // practice (probe-proven byte-identical for lowercase input); still
205 // route the Result via `?`. The canonical vector feeds both the field
206 // extraction below AND `interpolate_at` (whose raw case-sensitive
207 // cross-share hrp/id compares are why extraction-side lowercasing
208 // alone cannot fix combine) — it also makes the recovered output
209 // lowercase.
210 let parsed: Vec<Codex32String> = parsed
211 .iter()
212 .map(|c| {
213 Codex32String::from_string(c.to_string().to_ascii_lowercase())
214 .map_err(Error::Codex32)
215 })
216 .collect::<Result<Vec<_>>>()?;
217
218 if parsed.is_empty() {
219 // No shares → surface as below-threshold (k unknown; report 1/0).
220 return Err(Error::Codex32(codex32::Error::ThresholdNotPassed {
221 threshold: 1,
222 n_shares: 0,
223 }));
224 }
225
226 // Re-parse wire fields for each → (threshold_byte, share_index_byte). Both
227 // are `u8` (Copy), so this owns nothing that borrows the per-share string.
228 // `wire_string` is subsumed by the canonical vector above (already
229 // lowercase) — kept as harmless defense-in-depth; the canonical vector is
230 // the load-bearing mechanism for combine.
231 let fields: Vec<(u8, u8)> = parsed
232 .iter()
233 .map(|c| {
234 let s = wire_string(c);
235 extract_wire_fields(&s).map(|f| (f.threshold_byte, f.share_index_byte))
236 })
237 .collect::<Result<Vec<_>>>()?;
238
239 // 2. C1: reject any input at index `s` BEFORE interpolate_at (the
240 // short-circuit at codex32 lib.rs:262 would otherwise bypass validation).
241 if fields.iter().any(|&(_, idx)| idx == SHARE_INDEX_V01) {
242 return Err(Error::SecretShareSuppliedToCombine);
243 }
244
245 // 3. count >= k (the first share's threshold char). codex32 thresholds are
246 // single ASCII digits ('2'..'9'); '0' (an unshared single) here means the
247 // caller passed a v0.1 single-string into combine — also below any share
248 // threshold, surfaced as ThresholdNotPassed.
249 let k = (fields[0].0 - b'0') as usize;
250 if parsed.len() < k {
251 return Err(Error::Codex32(codex32::Error::ThresholdNotPassed {
252 threshold: k,
253 n_shares: parsed.len(),
254 }));
255 }
256
257 // 4. distinct share indices (codex32's RepeatedIndex check is lazy — only
258 // fires for the i==j Lagrange term — so pre-check exhaustively).
259 for i in 0..fields.len() {
260 for j in (i + 1)..fields.len() {
261 if fields[i].1 == fields[j].1 {
262 let idx = Fe::from_char(fields[i].1 as char).map_err(Error::Codex32)?;
263 return Err(Error::Codex32(codex32::Error::RepeatedIndex(idx)));
264 }
265 }
266 }
267
268 // 5. Recover the secret-at-S from EXACTLY k shares, then verify every
269 // EXTRA supplied share lies on that same polynomial (M6 — beyond-BIP-93
270 // defense-in-depth: codex32 K-of-N carries no digest share, so a same-id
271 // [same hrp/id/threshold/length] but cross-polynomial set would otherwise
272 // interpolate to a SILENT WRONG secret). The first k shares define the
273 // polynomial; recovery surfaces Mismatched{Hrp,Id,Threshold,Length} via
274 // Error::Codex32 on a header-inconsistent k-set, exactly as before.
275 //
276 // Hard invariant (BRAINSTORM §6.0): a valid exactly-k combine is
277 // bit-identical to the prior `interpolate_at(&parsed, Fe::S)` (k == n →
278 // k_set == parsed, empty membership loop), and a valid n>k all-consistent
279 // combine recovers the same secret (every extra lies on the curve).
280 let k_set = &parsed[..k];
281 let secret = Codex32String::interpolate_at(k_set, Fe::S).map_err(Error::Codex32)?;
282
283 // For each EXTRA supplied share, re-derive the polynomial's value at that
284 // share's index from the k-set and require it to equal the supplied share
285 // (full canonical lowercased Codex32String compare — header fields are
286 // already cross-checked by interpolate_at; this adds the polynomial/data
287 // dimension). The share-index char comes from the already-extracted `fields`
288 // (codex32's `Parts::share_index` is private); reuse the same `Fe::from_char`
289 // conversion as the distinct-index check above. Any mismatch ⇒ the set is
290 // not all from one split.
291 for j in k..parsed.len() {
292 let idx = Fe::from_char(fields[j].1 as char).map_err(Error::Codex32)?;
293 let derived = Codex32String::interpolate_at(k_set, idx).map_err(Error::Codex32)?;
294 if derived != parsed[j] {
295 return Err(Error::InconsistentShareSet);
296 }
297 }
298
299 // Payload KIND is the recovered prefix byte; the id is random → discard it
300 // and always return Tag::ENTR (the kind lives in the Payload, NOT the tag).
301 let data: Zeroizing<Vec<u8>> = Zeroizing::new(secret.parts().data());
302 let payload = dispatch_payload(&data)?;
303 Ok((Tag::ENTR, payload))
304}
305
306#[cfg(test)]
307mod tests {
308 use super::*;
309
310 #[test]
311 fn new_accepts_2_through_9() {
312 for k in 2u8..=9 {
313 let t = Threshold::new(k).unwrap_or_else(|e| panic!("new({k}) should be Ok, got {e:?}"));
314 assert_eq!(t.get(), k);
315 }
316 }
317
318 #[test]
319 fn new_rejects_zero() {
320 assert!(matches!(Threshold::new(0), Err(Error::InvalidThreshold(0))));
321 }
322
323 #[test]
324 fn new_rejects_one() {
325 assert!(matches!(Threshold::new(1), Err(Error::InvalidThreshold(1))));
326 }
327
328 #[test]
329 fn new_rejects_ten() {
330 assert!(matches!(Threshold::new(10), Err(Error::InvalidThreshold(10))));
331 }
332
333 #[test]
334 fn zero_const_get_is_zero() {
335 assert_eq!(Threshold::ZERO.get(), 0);
336 }
337
338 #[test]
339 fn new_five_get_is_five() {
340 assert_eq!(Threshold::new(5).unwrap().get(), 5);
341 }
342
343 // --- encode_shares tests (Task 1.3) ---
344
345 use crate::consts::RESERVED_PREFIX;
346 use crate::encode::encode;
347 use crate::payload::Payload;
348 use crate::tag::Tag;
349 use codex32::{Codex32String, Fe};
350
351 fn entr_p() -> Payload {
352 Payload::Entr(vec![0xCDu8; 16])
353 }
354 fn mnem_p() -> Payload {
355 Payload::Mnem { language: 1, entropy: vec![0xCDu8; 16] }
356 }
357
358 /// Re-parse a share string and return (threshold_char, share_index_char, id).
359 fn share_header(s: &str) -> (char, char, String) {
360 let sep = s.rfind('1').unwrap();
361 let b = s.as_bytes();
362 let threshold = b[sep + 1] as char;
363 let id: String = s[sep + 2..sep + 6].to_string();
364 let index = b[sep + 6] as char;
365 (threshold, index, id)
366 }
367
368 #[test]
369 fn zero_share_is_byte_identical_to_encode_entr() {
370 let p = entr_p();
371 let shares = encode_shares(Tag::ENTR, Threshold::ZERO, 1, &p).unwrap();
372 assert_eq!(shares, vec![encode(Tag::ENTR, &p).unwrap()]);
373 }
374
375 #[test]
376 fn zero_share_is_byte_identical_to_encode_mnem() {
377 let p = mnem_p();
378 let shares = encode_shares(Tag::ENTR, Threshold::ZERO, 1, &p).unwrap();
379 assert_eq!(shares, vec![encode(Tag::ENTR, &p).unwrap()]);
380 }
381
382 #[test]
383 fn zero_share_requires_n_eq_1() {
384 let p = entr_p();
385 assert!(matches!(
386 encode_shares(Tag::ENTR, Threshold::ZERO, 2, &p),
387 Err(Error::InvalidShareCount { k: 0, n: 2 })
388 ));
389 }
390
391 #[test]
392 fn encode_shares_2_of_3_shape() {
393 let p = entr_p();
394 let shares = encode_shares(Tag::ENTR, Threshold::new(2).unwrap(), 3, &p).unwrap();
395 assert_eq!(shares.len(), 3);
396 // Each parses, threshold char '2', distinct non-`s` indices, same id.
397 let mut indices = Vec::new();
398 let mut ids = Vec::new();
399 for s in &shares {
400 Codex32String::from_string(s.clone()).expect("each share must parse");
401 let (thr, idx, id) = share_header(s);
402 assert_eq!(thr, '2', "threshold char");
403 assert_ne!(idx, 's', "distributed share must not be index s");
404 indices.push(idx);
405 ids.push(id);
406 }
407 // Distinct indices.
408 let mut sorted = indices.clone();
409 sorted.sort_unstable();
410 sorted.dedup();
411 assert_eq!(sorted.len(), indices.len(), "indices must be distinct");
412 // Same id across the set.
413 assert!(ids.windows(2).all(|w| w[0] == w[1]), "id must be shared");
414 }
415
416 #[test]
417 fn encode_shares_rejects_n_below_k() {
418 let p = entr_p();
419 assert!(matches!(
420 encode_shares(Tag::ENTR, Threshold::new(2).unwrap(), 1, &p),
421 Err(Error::InvalidShareCount { k: 2, n: 1 })
422 ));
423 }
424
425 #[test]
426 fn encode_shares_rejects_n_32() {
427 let p = entr_p();
428 assert!(matches!(
429 encode_shares(Tag::ENTR, Threshold::new(2).unwrap(), 32, &p),
430 Err(Error::InvalidShareCount { k: 2, n: 32 })
431 ));
432 }
433
434 #[test]
435 fn encode_shares_id_not_in_blocklist() {
436 // Statistical: across many splits, the random id never lands in the blocklist.
437 let p = entr_p();
438 for _ in 0..64 {
439 let shares = encode_shares(Tag::ENTR, Threshold::new(2).unwrap(), 2, &p).unwrap();
440 let (_, _, id) = share_header(&shares[0]);
441 let id_bytes: [u8; 4] = id.as_bytes().try_into().unwrap();
442 assert!(
443 !crate::consts::RESERVED_ID_BLOCKLIST.contains(&id_bytes),
444 "id {id:?} must not be in RESERVED_ID_BLOCKLIST"
445 );
446 }
447 }
448
449 /// Inline round-trip (combine_shares lands in Task 1.4): any k of the n
450 /// distributed shares, interpolated at S, recover the secret wire bytes.
451 #[test]
452 fn encode_shares_round_trip_via_interpolate_entr_and_mnem() {
453 for p in [entr_p(), mnem_p()] {
454 let secret_wire = crate::envelope::payload_wire_bytes(&p);
455 for k in 2u8..=9 {
456 let n = (k as usize) + 2; // exercise interpolation-derived shares
457 let shares = encode_shares(Tag::ENTR, Threshold::new(k).unwrap(), n, &p).unwrap();
458 assert_eq!(shares.len(), n);
459 let parsed: Vec<Codex32String> = shares
460 .iter()
461 .map(|s| Codex32String::from_string(s.clone()).unwrap())
462 .collect();
463 // First k and last k subsets both recover the secret.
464 for subset in [&parsed[..k as usize], &parsed[n - k as usize..]] {
465 let recovered = Codex32String::interpolate_at(subset, Fe::S).unwrap();
466 assert_eq!(
467 recovered.parts().data(),
468 secret_wire[..],
469 "k={k} n={n} kind={:?} must recover secret wire bytes",
470 p.kind()
471 );
472 }
473 }
474 }
475 }
476
477 // --- combine_shares tests (Task 1.4) ---
478
479 #[test]
480 fn combine_round_trip_entr_and_mnem_all_lengths() {
481 for ent_len in [16usize, 20, 24, 28, 32] {
482 let entr = Payload::Entr(vec![0x37u8; ent_len]);
483 let mnem = Payload::Mnem { language: 7, entropy: vec![0x91u8; ent_len] };
484 for p in [entr, mnem] {
485 for k in 2u8..=9 {
486 let n = (k as usize) + 1;
487 let shares =
488 encode_shares(Tag::ENTR, Threshold::new(k).unwrap(), n, &p).unwrap();
489 // First k and last k subsets both combine back to the secret.
490 for subset in [&shares[..k as usize], &shares[n - k as usize..]] {
491 let (tag, recovered) = combine_shares(subset).unwrap();
492 assert_eq!(tag, Tag::ENTR, "combine always returns Tag::ENTR");
493 assert_eq!(
494 recovered,
495 p,
496 "k={k} n={n} ent_len={ent_len} must recover the exact payload"
497 );
498 }
499 }
500 }
501 }
502 }
503
504 #[test]
505 fn combine_rejects_below_threshold() {
506 let p = entr_p();
507 let shares = encode_shares(Tag::ENTR, Threshold::new(3).unwrap(), 4, &p).unwrap();
508 // Only 2 of a 3-of-4 set.
509 let err = combine_shares(&shares[..2]).unwrap_err();
510 assert!(
511 matches!(err, Error::Codex32(codex32::Error::ThresholdNotPassed { .. })),
512 "expected ThresholdNotPassed, got {err:?}"
513 );
514 }
515
516 #[test]
517 fn combine_rejects_duplicate_index() {
518 let p = entr_p();
519 let shares = encode_shares(Tag::ENTR, Threshold::new(2).unwrap(), 3, &p).unwrap();
520 // Same share twice → duplicate index.
521 let dup = vec![shares[0].clone(), shares[0].clone()];
522 assert!(matches!(
523 combine_shares(&dup),
524 Err(Error::Codex32(codex32::Error::RepeatedIndex(_)))
525 ));
526 }
527
528 #[test]
529 fn combine_rejects_secret_share_index_s() {
530 // Hand-build the secret-at-S directly (index `s`, threshold 2). It must
531 // be rejected BEFORE interpolate_at (C1 — the short-circuit would
532 // otherwise bypass payload validation).
533 let bytes = crate::envelope::payload_wire_bytes(&entr_p());
534 let secret_s = Codex32String::from_seed(HRP, 2, "tst7", Fe::S, &bytes[..])
535 .unwrap()
536 .to_string();
537 // Need >= k shares to get past the count check and reach the index check;
538 // but the index-s check runs first regardless, so a single secret-s input
539 // is rejected on the index axis.
540 let p = entr_p();
541 let shares = encode_shares(Tag::ENTR, Threshold::new(2).unwrap(), 2, &p).unwrap();
542 let with_secret = vec![secret_s, shares[0].clone()];
543 assert!(matches!(
544 combine_shares(&with_secret),
545 Err(Error::SecretShareSuppliedToCombine)
546 ));
547 }
548
549 #[test]
550 fn combine_rejects_mismatched_threshold() {
551 // Two shares from different-threshold sets, at DISTINCT indices (so the
552 // distinct-index pre-check passes and interpolate_at's eager
553 // MismatchedThreshold check fires). set2[0]=index q; set3[1]=index p.
554 let p = entr_p();
555 let set2 = encode_shares(Tag::ENTR, Threshold::new(2).unwrap(), 2, &p).unwrap();
556 let set3 = encode_shares(Tag::ENTR, Threshold::new(3).unwrap(), 3, &p).unwrap();
557 let mixed = vec![set2[0].clone(), set3[1].clone()];
558 let err = combine_shares(&mixed).unwrap_err();
559 assert!(
560 matches!(err, Error::Codex32(codex32::Error::MismatchedThreshold(..))),
561 "expected MismatchedThreshold, got {err:?}"
562 );
563 }
564
565 #[test]
566 fn combine_rejects_unparseable() {
567 let bad = vec!["not-an-ms1-string".to_string(), "also-bad".to_string()];
568 assert!(matches!(combine_shares(&bad), Err(Error::Codex32(_))));
569 }
570
571 // --- audit I9: combine must REJECT (not panic on) a non-standard-length
572 // Entr share set. The encode path validates length up front, but codex32
573 // share strings are an open format — an externally-constructed valid-checksum
574 // set with a non-standard payload length must surface a clean error, not abort.
575
576 /// Build a valid-checksum K-of-N Entr share set whose recovered payload has a
577 /// NON-STANDARD entropy length, bypassing `encode_shares`' `secret.validate()`
578 /// guard (which would reject it). Mirrors `encode_shares`' codex32
579 /// construction with a fixed id for determinism.
580 fn nonstandard_entr_distributed(k: usize, n: usize, entropy_len: usize) -> Vec<String> {
581 // wire payload = [RESERVED_PREFIX] || entropy
582 let mut bytes = vec![RESERVED_PREFIX];
583 bytes.extend(std::iter::repeat(0xCDu8).take(entropy_len));
584 let id = "tst7";
585 let secret_s = Codex32String::from_seed(HRP, k, id, Fe::S, &bytes[..]).unwrap();
586 let pool = non_s_index_pool();
587 let mut defining = vec![secret_s];
588 for pidx in pool.iter().take(k - 1) {
589 let filler = vec![0u8; bytes.len()];
590 defining.push(Codex32String::from_seed(HRP, k, id, *pidx, &filler[..]).unwrap());
591 }
592 let mut out = Vec::new();
593 for s in defining.iter().skip(1) {
594 out.push(s.to_string());
595 }
596 for pidx in pool.iter().take(n).skip(k - 1) {
597 out.push(Codex32String::interpolate_at(&defining, *pidx).unwrap().to_string());
598 }
599 out
600 }
601
602 #[test]
603 fn combine_rejects_nonstandard_entr_length_not_panics() {
604 // 17-byte entropy ∉ VALID_ENTR_LENGTHS. Pre-fix `combine_shares` returned
605 // Ok(unvalidated Entr) and `ms combine`'s from_entropy_in panicked
606 // (exit 101). Post-fix: a clean PayloadLengthMismatch, no panic.
607 let shares = nonstandard_entr_distributed(2, 2, 17);
608 let res = combine_shares(&shares);
609 assert!(
610 matches!(res, Err(Error::PayloadLengthMismatch { got: 17, .. })),
611 "expected PayloadLengthMismatch{{got:17}}, got {res:?}"
612 );
613 }
614
615 #[test]
616 fn dispatch_payload_validates_entr_length() {
617 // Unit-level: the Entr arm now validates length (parity with the Mnem arm
618 // and this fn's doc contract). Audit I9.
619 let mut bad = vec![RESERVED_PREFIX];
620 bad.extend(std::iter::repeat(0xCDu8).take(17));
621 assert!(
622 matches!(dispatch_payload(&bad), Err(Error::PayloadLengthMismatch { got: 17, .. })),
623 "non-standard Entr length must Err"
624 );
625 // Positive control: a standard length (16) still decodes Ok — no over-rejection.
626 let mut good = vec![RESERVED_PREFIX];
627 good.extend(std::iter::repeat(0xCDu8).take(16));
628 assert!(
629 matches!(dispatch_payload(&good), Ok(Payload::Entr(_))),
630 "standard Entr length must Ok"
631 );
632 }
633
634 // --- M6: cross-share polynomial-consistency check in combine_shares ---
635 //
636 // Beyond-BIP-93 defense-in-depth (BRAINSTORM §6.0): codex32 K-of-N has no
637 // digest share, so combining a same-id (same hrp/id/threshold/length) but
638 // DIFFERENT-polynomial share set silently returns a WRONG secret. The check
639 // truncates to the first k shares (which define the polynomial), recovers
640 // the secret from them, then verifies every EXTRA supplied share lies on
641 // that polynomial. Valid combines (exactly-k, or n>k all-consistent) MUST
642 // stay bit-identical.
643
644 /// Build a valid-checksum 2-of-`n` distributed share set carrying a STANDARD
645 /// 16-byte Entr secret, with a CALLER-FIXED `id` and a caller-chosen secret
646 /// entropy byte (→ a distinct Shamir polynomial). Two sets with the same
647 /// `id` but different `secret_byte` are same-id-but-inconsistent: their
648 /// shares pairwise lie on DIFFERENT polynomials. Mirrors `encode_shares`'
649 /// codex32 construction (deterministic filler, no CSPRNG → reproducible).
650 fn same_id_2_of_n(id: &str, secret_byte: u8, filler_byte: u8, n: usize) -> Vec<String> {
651 let k = 2usize;
652 // wire payload = [RESERVED_PREFIX] || 16-byte entropy (a STANDARD length,
653 // so a clean combine recovers a valid Entr payload).
654 let mut bytes = vec![RESERVED_PREFIX];
655 bytes.extend(std::iter::repeat(secret_byte).take(16));
656 let secret_s = Codex32String::from_seed(HRP, k, id, Fe::S, &bytes[..]).unwrap();
657 let pool = non_s_index_pool();
658 let mut defining = vec![secret_s];
659 for pidx in pool.iter().take(k - 1) {
660 let filler = vec![filler_byte; bytes.len()];
661 defining.push(Codex32String::from_seed(HRP, k, id, *pidx, &filler[..]).unwrap());
662 }
663 let mut out = Vec::new();
664 for s in defining.iter().skip(1) {
665 out.push(s.to_string());
666 }
667 for pidx in pool.iter().take(n).skip(k - 1) {
668 out.push(Codex32String::interpolate_at(&defining, *pidx).unwrap().to_string());
669 }
670 out
671 }
672
673 #[test]
674 fn combine_inconsistent_same_id_set_rejected() {
675 // Two DIFFERENT secrets A, B split 2-of-3 with the SAME id/threshold/
676 // length. Supply an over-threshold (n>k) same-id set [A1, A2, B3]:
677 // distinct indices, same header, but B3 is NOT on A's polynomial. RED
678 // today: combine interpolates over all three and returns a WRONG
679 // (garbage) secret with no error. Post-fix: the membership check derives
680 // A's value at B3's index from {A1,A2} and finds it ≠ B3 →
681 // Error::InconsistentShareSet. (BRAINSTORM §6.5 test #1, n>k extras form.)
682 //
683 // NOTE the spec's documented irreducible limit (§6.2 edge cases): an
684 // EXACTLY-k mixed pair [A1, B2] is NOT detectable — any k points define
685 // *a* polynomial, so there is no extra share to cross-check. M6 closes
686 // only the detectable case (any over-threshold set not all-on-one-curve).
687 let set_a = same_id_2_of_n("aaaa", 0x11, 0x22, 3);
688 let set_b = same_id_2_of_n("aaaa", 0x33, 0x44, 3);
689 // A's first two distributed shares (the consistent k-set) + B's third.
690 let mixed = vec![set_a[0].clone(), set_a[1].clone(), set_b[2].clone()];
691 let res = combine_shares(&mixed);
692 assert!(
693 matches!(res, Err(Error::InconsistentShareSet)),
694 "expected InconsistentShareSet for a same-id mixed-polynomial set, got {res:?}"
695 );
696 }
697
698 #[test]
699 fn combine_valid_exactly_k_unchanged() {
700 // Positive control (BRAINSTORM §6.0 hard invariant): a clean 2-of-3,
701 // supply exactly k=2 consistent shares → recovers the correct secret A,
702 // byte-identical to the current behavior. MUST stay GREEN.
703 let p = Payload::Entr(vec![0xCDu8; 16]);
704 let shares = encode_shares(Tag::ENTR, Threshold::new(2).unwrap(), 3, &p).unwrap();
705 let (tag, recovered) = combine_shares(&shares[..2]).unwrap();
706 assert_eq!(tag, Tag::ENTR);
707 assert_eq!(recovered, p, "exactly-k combine must recover the exact payload");
708 }
709
710 #[test]
711 fn combine_valid_n_gt_k_all_consistent() {
712 // Positive control: supply all 3 consistent shares of A (n > k) → the
713 // extra share passes the membership check → recovers A unchanged. MUST
714 // stay GREEN (no regression on the over-supplied legitimate case).
715 let p = Payload::Entr(vec![0xCDu8; 16]);
716 let shares = encode_shares(Tag::ENTR, Threshold::new(2).unwrap(), 3, &p).unwrap();
717 let (tag, recovered) = combine_shares(&shares).unwrap();
718 assert_eq!(tag, Tag::ENTR);
719 assert_eq!(recovered, p, "n>k all-consistent combine must recover the exact payload");
720 }
721
722 #[test]
723 fn combine_inconsistent_extra_share_rejected() {
724 // 2 consistent A-shares (the k-set) + a consistent A-extra + a same-id
725 // B-extra, with the INCONSISTENT extra in a NON-terminal position
726 // [A1, A2, B3, A4]: the first k recover A and the membership loop must
727 // catch the B-share even though it is not the last extra. RED today
728 // (combine interpolates over all 4 → garbage). Post-fix:
729 // Error::InconsistentShareSet.
730 // id chars must be in the codex32 (bech32) alphabet — 'b'/'i'/'o'/'1'
731 // are excluded, so use 'cqcq'.
732 let set_a = same_id_2_of_n("cqcq", 0x55, 0x66, 4);
733 let set_b = same_id_2_of_n("cqcq", 0x77, 0x88, 4);
734 // k-set [A1, A2] (pool indices 0,1) + B's index-2 share (inconsistent,
735 // a non-terminal extra) + A's index-3 share (consistent, terminal).
736 let mixed = vec![
737 set_a[0].clone(),
738 set_a[1].clone(),
739 set_b[2].clone(),
740 set_a[3].clone(),
741 ];
742 let res = combine_shares(&mixed);
743 assert!(
744 matches!(res, Err(Error::InconsistentShareSet)),
745 "expected InconsistentShareSet for a consistent-k + inconsistent-extra set, got {res:?}"
746 );
747 }
748}