vouch-core 3.2.0

Vouch Protocol canonical core: JCS canonicalization, Ed25519 + ML-DSA proofs, did:key/multikey, Data Integrity (eddsa-jcs-2022), credentials, delegation, revocation. One byte-exact implementation shared by every language SDK via WASM and UniFFI/C-FFI.
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
//! Root-identity recovery by Shamir secret sharing.
//!
//! Splits a root identity's Ed25519 seed into `shares` pieces so that any
//! `threshold` of them reconstruct it, and fewer reveal nothing. Distribute
//! shares to separate guardians or locations; gather `threshold` only during
//! a deliberate recovery.
//!
//! This is the recovery / escrow primitive, distinct from [`crate::threshold`]
//! (FROST), where the key is never reassembled: here the seed IS reconstructed
//! at recovery time, so do it on a trusted device and re-seal afterwards. Use
//! it for cold recovery of a root, not for hot signing.
//!
//! The arithmetic is textbook Shamir over GF(2^8) (the AES field, reducing
//! polynomial 0x11B). [`split_backup`] and [`recover_backup`] carry the whole
//! identity (its DID, its Ed25519 seed and further keys such as the ML-DSA-44
//! key) with a check value that catches a wrong, damaged or missing share.
//! [`split_identity`] and [`recover_identity`] handle the earlier seed-only
//! shares, which carry no check value and do not hold the DID, so recovering
//! them needs the DID from the caller.

use crate::error::{CoreError, Result};
use crate::keys::{Ed25519KeyPair, ED25519_SEED_LEN};

fn recovery_err(msg: impl Into<String>) -> CoreError {
    CoreError::Crypto(msg.into())
}

// ---------------------------------------------------------------------------
// GF(2^8) arithmetic (AES field, reducing polynomial 0x11B)
// ---------------------------------------------------------------------------

struct GfTables {
    exp: [u8; 512],
    log: [u8; 256],
}

fn gf_tables() -> &'static GfTables {
    use std::sync::OnceLock;
    static TABLES: OnceLock<GfTables> = OnceLock::new();
    TABLES.get_or_init(|| {
        // 3 (not 2) is a primitive element of GF(2^8) under 0x11B, so powers of
        // 3 cycle through all 255 non-zero elements. Multiply by 3 = (x*2) XOR x.
        let mut exp = [0u8; 512];
        let mut log = [0u8; 256];
        let mut x: u16 = 1;
        #[allow(clippy::needless_range_loop)] // log is indexed by x, not by i
        for i in 0..255usize {
            exp[i] = x as u8;
            log[x as usize] = i as u8;
            let mut x2 = x << 1;
            if x2 & 0x100 != 0 {
                x2 ^= 0x11B;
            }
            x ^= x2;
        }
        // exp[255..512) mirrors exp[0..257) (period 255); each entry depends on
        // one already computed earlier in this same range, so this must stay a
        // sequential loop rather than a single bulk copy.
        #[allow(clippy::needless_range_loop)]
        for i in 255..512 {
            exp[i] = exp[i - 255];
        }
        GfTables { exp, log }
    })
}

fn gf_mul(a: u8, b: u8) -> u8 {
    if a == 0 || b == 0 {
        return 0;
    }
    let t = gf_tables();
    t.exp[t.log[a as usize] as usize + t.log[b as usize] as usize]
}

fn gf_inv(a: u8) -> Result<u8> {
    if a == 0 {
        return Err(recovery_err("no inverse for 0 in GF(2^8)"));
    }
    let t = gf_tables();
    Ok(t.exp[255 - t.log[a as usize] as usize])
}

/// Evaluates a polynomial (coefficients low-order first) at `x` in GF(2^8).
fn eval_poly(coeffs: &[u8], x: u8) -> u8 {
    let mut result = 0u8;
    for &c in coeffs.iter().rev() {
        result = gf_mul(result, x) ^ c;
    }
    result
}

/// Lagrange-interpolates the points and returns the value at x = 0.
fn interpolate_at_zero(xs: &[u8], ys: &[u8]) -> Result<u8> {
    let mut result = 0u8;
    for i in 0..xs.len() {
        let mut num = 1u8;
        let mut den = 1u8;
        for j in 0..xs.len() {
            if i == j {
                continue;
            }
            num = gf_mul(num, xs[j]); // (0 - xj) == xj in GF(2^8)
            den = gf_mul(den, xs[i] ^ xs[j]); // (xi - xj) == xi ^ xj
        }
        let inv = gf_inv(den)?;
        result ^= gf_mul(ys[i], gf_mul(num, inv));
    }
    Ok(result)
}

// ---------------------------------------------------------------------------
// Byte-level split / combine
// ---------------------------------------------------------------------------

/// Splits `secret` into `shares` pieces; any `threshold` of them reconstruct
/// it. Each returned share is a leading index byte (1..=shares) followed by
/// the share body, the same length as `secret`.
pub fn split_secret(secret: &[u8], threshold: u16, shares: u16) -> Result<Vec<Vec<u8>>> {
    if secret.is_empty() {
        return Err(recovery_err("secret must be non-empty bytes"));
    }
    if threshold < 2 || threshold > shares || shares > 255 {
        return Err(recovery_err("require 2 <= threshold <= shares <= 255"));
    }

    let mut out: Vec<Vec<u8>> = (1..=shares).map(|i| vec![i as u8]).collect();

    for &b in secret {
        let mut coeffs = vec![0u8; threshold as usize];
        coeffs[0] = b;
        if threshold > 1 {
            getrandom::getrandom(&mut coeffs[1..])
                .map_err(|e| recovery_err(format!("rng: {e}")))?;
        }
        for (i, out_share) in out.iter_mut().enumerate() {
            out_share.push(eval_poly(&coeffs, (i + 1) as u8));
        }
    }
    Ok(out)
}

/// Reconstructs a secret from `threshold` (or more) shares. Supplying fewer
/// than the original threshold returns a wrong value, not an error.
pub fn combine_shares(shares: &[Vec<u8>]) -> Result<Vec<u8>> {
    if shares.len() < 2 {
        return Err(recovery_err("need at least 2 shares"));
    }
    let mut xs = Vec::with_capacity(shares.len());
    let mut bodies = Vec::with_capacity(shares.len());
    let mut seen = std::collections::HashSet::new();
    for s in shares {
        if s.len() < 2 {
            return Err(recovery_err("malformed share"));
        }
        if s[0] == 0 {
            // x = 0 is where the secret sits: a share there would be taken as
            // the secret itself, whatever the other shares say.
            return Err(recovery_err("malformed share: index 0 is not a share"));
        }
        if !seen.insert(s[0]) {
            return Err(recovery_err("shares must have distinct indices"));
        }
        xs.push(s[0]);
        bodies.push(&s[1..]);
    }
    let length = bodies[0].len();
    if bodies.iter().any(|b| b.len() != length) {
        return Err(recovery_err("shares have inconsistent length"));
    }

    let mut secret = vec![0u8; length];
    for j in 0..length {
        let ys: Vec<u8> = bodies.iter().map(|b| b[j]).collect();
        secret[j] = interpolate_at_zero(&xs, &ys)?;
    }
    Ok(secret)
}

// ---------------------------------------------------------------------------
// Vouch identity recovery
// ---------------------------------------------------------------------------

/// Splits a root identity's Ed25519 seed into shares in the earlier,
/// seed-only format. Any threshold of them recover the identity via
/// [`recover_identity`]. Prefer [`split_backup`], which also carries the DID and
/// further keys and catches a damaged share.
pub fn split_identity(seed: &[u8], threshold: u16, shares: u16) -> Result<Vec<Vec<u8>>> {
    if seed.len() != ED25519_SEED_LEN {
        return Err(CoreError::InvalidKeyLength {
            expected: ED25519_SEED_LEN,
            got: seed.len(),
        });
    }
    split_secret(seed, threshold, shares)
}

/// The answer when shares in the earlier seed-only format come with no DID.
pub const OLD_SHARES_NEED_DID: &str =
    "these shares come from an older backup that does not hold the DID; pass the DID to recover them";

/// A root identity rebuilt from recovery shares.
pub struct RecoveredIdentity {
    pub did: String,
    pub seed: [u8; ED25519_SEED_LEN],
    pub public_key: [u8; 32],
}

/// Recovers a root identity from threshold shares in the earlier seed-only
/// format. The recovered seed is deterministic, so the rebuilt key is
/// identical to the original. These shares do not say which DID they belong
/// to, so `did` must name it (the DID the shares were split under); `None` or
/// an empty DID is an error.
pub fn recover_identity(shares: &[Vec<u8>], did: Option<&str>) -> Result<RecoveredIdentity> {
    let did = match did {
        Some(d) if !d.is_empty() => d.to_string(),
        _ => return Err(recovery_err(OLD_SHARES_NEED_DID)),
    };
    let seed_vec = combine_shares(shares)?;
    if seed_vec.len() != ED25519_SEED_LEN {
        return Err(recovery_err(format!(
            "recovered seed is not {ED25519_SEED_LEN} bytes; wrong or too few shares"
        )));
    }
    let seed: [u8; ED25519_SEED_LEN] = seed_vec
        .try_into()
        .map_err(|_| recovery_err("recovered seed had unexpected length"))?;

    let keypair = Ed25519KeyPair::from_seed(&seed);
    let public_key = keypair.public_key();

    Ok(RecoveredIdentity {
        did,
        seed,
        public_key,
    })
}

// ---------------------------------------------------------------------------
// Identity backups (the "vouch-recovery-2:" share format)
// ---------------------------------------------------------------------------
//
// A recovery share is the text "vouch-recovery-2:" followed by the standard
// base64 of `set_id (8 bytes) | threshold (1 byte) | index (1 byte) | body`.
// All shares of one split carry the same random set_id. The bodies are the
// Shamir split of `SHA-256(J) | J`, where J is the UTF-8 JSON object
// `{"v":2,"did"?:string,"seed":b64,"keys":[{"id","alg","public_key","private_key":b64}]}`.
// One set of shares brings back every key of the identity, and the check value
// tells a wrong, damaged or missing share apart from a good recovery. The
// format is defined by the Python reference (vouch.recovery) and pinned by
// test-vectors/recovery/vector.json.

/// The text every share in the backup format starts with.
pub const SHARE_PREFIX: &str = "vouch-recovery-2:";
const SET_ID_LEN: usize = 8;
const BACKUP_VERSION: u64 = 2;
const MLDSA44: &str = "ML-DSA-44";
const MLDSA44_KEY_ID: &str = "#key-2";

/// A further key of an identity carried in a backup, such as its ML-DSA-44
/// key in the "#key-2" slot. The private key is wiped from memory on drop.
#[derive(Clone)]
pub struct BackupKey {
    pub id: String,
    pub alg: String,
    /// The public key as a Multikey string.
    pub public_key: String,
    /// The raw private key bytes.
    pub private_key: Vec<u8>,
}

impl Drop for BackupKey {
    fn drop(&mut self) {
        use zeroize::Zeroize;
        self.private_key.zeroize();
    }
}

impl std::fmt::Debug for BackupKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BackupKey")
            .field("id", &self.id)
            .field("alg", &self.alg)
            .field("public_key", &self.public_key)
            .finish_non_exhaustive()
    }
}

/// An identity rebuilt from backup shares.
pub struct RecoveredBackup {
    /// The DID the shares were made for, when they carry one.
    pub did: Option<String>,
    pub seed: [u8; ED25519_SEED_LEN],
    pub public_key: [u8; 32],
    pub keys: Vec<BackupKey>,
}

impl Drop for RecoveredBackup {
    fn drop(&mut self) {
        use zeroize::Zeroize;
        self.seed.zeroize();
    }
}

/// Checks one further key: slot and algorithm agree, and an ML-DSA-44 key's
/// private half is exactly the one key generation makes for its public half
/// (see [`crate::mldsa_check`]).
fn check_backup_key(key: &BackupKey) -> std::result::Result<(), String> {
    if key.id.is_empty()
        || key.alg.is_empty()
        || key.public_key.is_empty()
        || key.private_key.is_empty()
    {
        return Err("a key entry is malformed".into());
    }
    if (key.alg == MLDSA44) != (key.id == MLDSA44_KEY_ID) {
        return Err("a key entry is malformed".into());
    }
    if key.alg != MLDSA44 {
        return Ok(());
    }
    let decoded = crate::multikey::decode(&key.public_key)
        .map_err(|_| "the ML-DSA-44 public key is not a Multikey".to_string())?;
    if decoded.algorithm != MLDSA44 || decoded.raw_key.len() != crate::pq::MLDSA44_PUBLIC_LEN {
        return Err("the ML-DSA-44 public key is not an ML-DSA-44 key".into());
    }
    if key.private_key.len() != crate::pq::MLDSA44_SECRET_LEN {
        return Err("the ML-DSA-44 private key is the wrong size".into());
    }
    if !crate::mldsa_check::mldsa44_keys_match(&decoded.raw_key, &key.private_key) {
        return Err("the ML-DSA-44 public key does not match its private key".into());
    }
    Ok(())
}

/// The rules every set of further keys follows, on split and on recovery.
fn check_backup_keys(keys: &[BackupKey]) -> std::result::Result<(), String> {
    for (i, key) in keys.iter().enumerate() {
        check_backup_key(key)?;
        if keys[..i].iter().any(|k| k.id == key.id || k.alg == key.alg) {
            return Err("it repeats a key: one key per slot and per algorithm".into());
        }
    }
    Ok(())
}

/// Splits an identity into backup shares, any `threshold` of which bring it
/// back with [`recover_backup`]: its Ed25519 seed, its DID when given, and its
/// further keys, such as the ML-DSA-44 key in "#key-2". Keys are checked with
/// the same rules recovery uses, so a backup that splits also recovers.
pub fn split_backup(
    seed: &[u8],
    did: Option<&str>,
    keys: &[BackupKey],
    threshold: u16,
    shares: u16,
) -> Result<Vec<String>> {
    use base64::{engine::general_purpose::STANDARD, Engine};
    use sha2::{Digest, Sha256};
    use zeroize::Zeroizing;

    if seed.len() != ED25519_SEED_LEN {
        return Err(CoreError::InvalidKeyLength {
            expected: ED25519_SEED_LEN,
            got: seed.len(),
        });
    }
    check_backup_keys(keys).map_err(recovery_err)?;
    let mut backup = serde_json::Map::new();
    backup.insert("v".into(), serde_json::json!(BACKUP_VERSION));
    if let Some(d) = did.filter(|d| !d.is_empty()) {
        backup.insert("did".into(), serde_json::json!(d));
    }
    backup.insert("seed".into(), serde_json::json!(STANDARD.encode(seed)));
    let rows: Vec<serde_json::Value> = keys
        .iter()
        .map(|k| {
            serde_json::json!({
                "id": k.id,
                "alg": k.alg,
                "public_key": k.public_key,
                "private_key": STANDARD.encode(&k.private_key),
            })
        })
        .collect();
    backup.insert("keys".into(), serde_json::Value::Array(rows));
    let body = Zeroizing::new(crate::jcs::canonicalize(&serde_json::Value::Object(backup)));
    let mut data = Zeroizing::new(Sha256::digest(&*body).to_vec());
    data.extend_from_slice(&body);

    let pieces = split_secret(&data, threshold, shares)?;
    let mut set_id = [0u8; SET_ID_LEN];
    getrandom::getrandom(&mut set_id).map_err(|e| recovery_err(format!("rng: {e}")))?;
    Ok(pieces
        .into_iter()
        .map(|piece| {
            let mut raw = set_id.to_vec();
            raw.push(threshold as u8);
            raw.extend_from_slice(&piece);
            format!("{SHARE_PREFIX}{}", STANDARD.encode(raw))
        })
        .collect())
}

/// Spaces, tabs and line breaks around a share are not part of it.
pub fn trim_share(share: &str) -> &str {
    share.trim_matches(|c| matches!(c, ' ' | '\t' | '\r' | '\n'))
}

/// True when `share` is in the backup format rather than the earlier one.
pub fn is_backup_share(share: &str) -> bool {
    trim_share(share).starts_with(SHARE_PREFIX)
}

/// Standard, padded base64 written the one canonical way.
pub fn strict_base64(text: &str) -> Option<Vec<u8>> {
    use base64::{engine::general_purpose::STANDARD, Engine};
    let raw = STANDARD.decode(text).ok()?;
    (STANDARD.encode(&raw) == text).then_some(raw)
}

fn same_bytes(a: &[u8], b: &[u8]) -> bool {
    a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
}

/// Reads J, which must be exactly its own canonical JSON with the known members.
fn parse_backup(body: &[u8]) -> std::result::Result<RecoveredBackup, String> {
    let backup: serde_json::Value =
        serde_json::from_slice(body).map_err(|_| "it is not valid JSON text".to_string())?;
    if crate::jcs::canonicalize(&backup) != body {
        return Err("it is not in canonical form".into());
    }
    let object = backup.as_object().ok_or("it has unexpected members")?;
    let allowed = ["v", "seed", "keys", "did"];
    if !object.keys().all(|k| allowed.contains(&k.as_str()))
        || !["v", "seed", "keys"]
            .iter()
            .all(|k| object.contains_key(*k))
    {
        return Err("it has unexpected members".into());
    }
    if object["v"].as_u64() != Some(BACKUP_VERSION) {
        return Err("unknown backup version".into());
    }
    let seed_vec = object["seed"]
        .as_str()
        .and_then(strict_base64)
        .ok_or("the seed is not canonical base64")?;
    let seed: [u8; ED25519_SEED_LEN] = seed_vec
        .try_into()
        .map_err(|_| "the seed is not 32 bytes".to_string())?;
    let did = match object.get("did") {
        None => None,
        Some(serde_json::Value::String(d)) if !d.is_empty() => Some(d.clone()),
        Some(_) => return Err("its DID is not a DID".into()),
    };
    let rows = object["keys"]
        .as_array()
        .ok_or("its key list is not a list")?;
    let mut keys = Vec::with_capacity(rows.len());
    for row in rows {
        let fields = row.as_object().ok_or("a key entry is malformed")?;
        let names = ["id", "alg", "public_key", "private_key"];
        if fields.len() != names.len()
            || !names
                .iter()
                .all(|n| fields.get(*n).is_some_and(|v| v.is_string()))
        {
            return Err("a key entry is malformed".into());
        }
        let text = |n: &str| fields[n].as_str().unwrap_or_default().to_string();
        let private_key = strict_base64(&text("private_key")).ok_or("a key entry is malformed")?;
        keys.push(BackupKey {
            id: text("id"),
            alg: text("alg"),
            public_key: text("public_key"),
            private_key,
        });
    }
    check_backup_keys(&keys)?;
    let public_key = Ed25519KeyPair::from_seed(&seed).public_key();
    Ok(RecoveredBackup {
        did,
        seed,
        public_key,
        keys,
    })
}

/// Rebuilds an identity from backup shares.
///
/// Errors on too few shares, shares from different backups, the same share
/// twice, a share at index 0, or a damaged or altered share.
pub fn recover_backup(shares: &[String]) -> Result<RecoveredBackup> {
    use sha2::{Digest, Sha256};
    use zeroize::Zeroizing;

    if shares.is_empty() {
        return Err(recovery_err("no recovery shares were given"));
    }
    let mut set_id: Option<Vec<u8>> = None;
    let mut threshold: Option<u8> = None;
    let mut pieces: Vec<Zeroizing<Vec<u8>>> = Vec::with_capacity(shares.len());
    for share in shares {
        let text = trim_share(share)
            .strip_prefix(SHARE_PREFIX)
            .ok_or_else(|| {
                recovery_err("these shares come from different backups; use shares from one backup")
            })?;
        let raw = Zeroizing::new(strict_base64(text).ok_or_else(|| {
            recovery_err("a recovery share is damaged: it is not canonical base64")
        })?);
        if raw.len() < SET_ID_LEN + 3 {
            return Err(recovery_err("a recovery share is damaged: it is too short"));
        }
        if raw[SET_ID_LEN] < 2 {
            return Err(recovery_err(
                "a recovery share is damaged: its threshold is below 2",
            ));
        }
        if raw[SET_ID_LEN + 1] == 0 {
            return Err(recovery_err(
                "a recovery share is damaged: index 0 is not a share",
            ));
        }
        let (id, rest) = raw.split_at(SET_ID_LEN);
        if set_id.get_or_insert_with(|| id.to_vec()) != id
            || *threshold.get_or_insert(rest[0]) != rest[0]
        {
            return Err(recovery_err(
                "these shares come from different backups, or one of them is damaged; \
                 use shares from one backup",
            ));
        }
        pieces.push(Zeroizing::new(rest[1..].to_vec()));
    }
    let mut indices = std::collections::HashSet::new();
    if !pieces.iter().all(|p| indices.insert(p[0])) {
        return Err(recovery_err("the same share was given twice"));
    }
    let needed = threshold.unwrap_or(0) as usize;
    if pieces.len() < needed {
        return Err(recovery_err(format!(
            "this backup needs {needed} shares to recover, and {} were given",
            pieces.len()
        )));
    }
    let plain: Vec<Vec<u8>> = pieces.iter().map(|p| p.to_vec()).collect();
    let combined = combine_shares(&plain);
    for mut p in plain {
        use zeroize::Zeroize;
        p.zeroize();
    }
    let data = Zeroizing::new(combined?);
    if data.len() < 33 || !same_bytes(Sha256::digest(&data[32..]).as_slice(), &data[..32]) {
        return Err(recovery_err(
            "the shares do not recover a backup: one of them is damaged or altered",
        ));
    }
    parse_backup(&data[32..])
        .map_err(|why| recovery_err(format!("the recovered backup cannot be read: {why}")))
}

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

    #[test]
    fn split_and_combine_roundtrips() {
        let secret = [7u8; 32];
        let shares = split_secret(&secret, 3, 5).unwrap();
        assert_eq!(shares.len(), 5);

        let combined = combine_shares(&shares[0..3]).unwrap();
        assert_eq!(combined, secret.to_vec());

        let alt = vec![shares[0].clone(), shares[2].clone(), shares[4].clone()];
        let combined2 = combine_shares(&alt).unwrap();
        assert_eq!(combined2, secret.to_vec());
    }

    #[test]
    fn below_threshold_does_not_reveal_secret() {
        let secret = [9u8; 16];
        let shares = split_secret(&secret, 3, 5).unwrap();
        let combined = combine_shares(&shares[0..2]).unwrap();
        assert_ne!(combined, secret.to_vec());
    }

    #[test]
    fn split_secret_rejects_bad_parameters() {
        assert!(split_secret(&[], 2, 3).is_err());
        assert!(split_secret(&[1], 1, 3).is_err());
        assert!(split_secret(&[1], 4, 3).is_err());
    }

    #[test]
    fn combine_shares_rejects_inconsistent_input() {
        let secret = [1u8; 16];
        let shares = split_secret(&secret, 2, 3).unwrap();
        let dup = vec![shares[0].clone(), shares[0].clone()];
        assert!(combine_shares(&dup).is_err());

        let mut short = shares[1].clone();
        short.truncate(6);
        let mismatched = vec![shares[0].clone(), short];
        assert!(combine_shares(&mismatched).is_err());
    }

    #[test]
    fn split_and_recover_identity_signs_identically() {
        let keypair = Ed25519KeyPair::generate().unwrap();
        let seed = keypair.seed();
        let did = ed25519_to_did_key(&keypair.public_key()).unwrap();

        let shares = split_identity(&seed, 2, 3).unwrap();
        assert_eq!(shares.len(), 3);

        let recovered = recover_identity(&shares[0..2], Some(&did)).unwrap();
        assert_eq!(recovered.did, did);
        assert_eq!(recovered.public_key, keypair.public_key());

        let message = b"charge api.bank invoices/42";
        let sig = Ed25519KeyPair::from_seed(&recovered.seed).sign(message);
        assert!(crate::keys::verify(&keypair.public_key(), message, &sig).unwrap());
    }

    #[test]
    fn earlier_shares_need_the_did() {
        let keypair = Ed25519KeyPair::generate().unwrap();
        let shares = split_identity(&keypair.seed(), 2, 3).unwrap();
        for did in [None, Some("")] {
            let err = recover_identity(&shares[1..3], did)
                .err()
                .expect("earlier shares with no DID must be refused");
            assert!(
                err.to_string().contains(OLD_SHARES_NEED_DID),
                "unexpected error: {err}"
            );
        }
        // The DID is asked for before the shares are read, so damaged
        // shares with no DID get the same answer.
        let err = recover_identity(&[vec![0, 1], vec![1]], None)
            .err()
            .unwrap();
        assert!(err.to_string().contains(OLD_SHARES_NEED_DID));
    }

    fn mldsa_backup_key(private_key: Vec<u8>, public_key: &[u8]) -> BackupKey {
        BackupKey {
            id: MLDSA44_KEY_ID.into(),
            alg: MLDSA44.into(),
            public_key: crate::multikey::encode_mldsa44_public(public_key).unwrap(),
            private_key,
        }
    }

    #[test]
    fn backup_keys_are_checked_by_recomputing_the_key() {
        let pair = crate::pq::MlDsa44KeyPair::generate().unwrap();
        let (pk, sk) = (pair.public_key(), pair.secret_key());
        let seed = [4u8; ED25519_SEED_LEN];
        let good = mldsa_backup_key(sk.to_vec(), &pk);
        let shares = split_backup(&seed, None, &[good], 2, 3).unwrap();
        let back = recover_backup(&shares[..2]).unwrap();
        assert_eq!(back.keys[0].private_key, sk.to_vec());

        // K (bytes 32..64) is the signing seed: any K is a working key.
        let mut other_k = sk.to_vec();
        other_k[32..64].fill(0xA5);
        assert!(split_backup(&seed, None, &[mldsa_backup_key(other_k, &pk)], 2, 3).is_ok());

        // A flipped bit in rho, tr, s1, s2 or t0 is refused.
        for at in [0, 64, 128, 512, 896, 2559] {
            let mut damaged = sk.to_vec();
            damaged[at] ^= 0x01;
            let err = split_backup(&seed, None, &[mldsa_backup_key(damaged, &pk)], 2, 3)
                .expect_err("damaged key must be refused");
            assert!(
                err.to_string().contains("does not match its private key"),
                "byte {at}: {err}"
            );
        }
    }

    #[test]
    fn too_few_shares_gives_a_wrong_key_not_an_error() {
        let keypair = Ed25519KeyPair::generate().unwrap();
        let seed = keypair.seed();
        let did = ed25519_to_did_key(&keypair.public_key()).unwrap();

        let shares = split_identity(&seed, 3, 5).unwrap();
        // Two shares when three are required: recover_identity still returns
        // structurally, but the seed (and therefore the public key) will not
        // match the original, since interpolation with too few points gives
        // the wrong value.
        let recovered = recover_identity(&shares[0..2], Some(&did)).unwrap();
        assert_ne!(recovered.public_key, keypair.public_key());
        assert_ne!(recovered.seed, seed);
    }
}