Skip to main content

vouch_core/
recovery.rs

1//! Root-identity recovery by Shamir secret sharing.
2//!
3//! Splits a root identity's Ed25519 seed into `shares` pieces so that any
4//! `threshold` of them reconstruct it, and fewer reveal nothing. Distribute
5//! shares to separate guardians or locations; gather `threshold` only during
6//! a deliberate recovery.
7//!
8//! This is the recovery / escrow primitive, distinct from [`crate::threshold`]
9//! (FROST), where the key is never reassembled: here the seed IS reconstructed
10//! at recovery time, so do it on a trusted device and re-seal afterwards. Use
11//! it for cold recovery of a root, not for hot signing.
12//!
13//! The arithmetic is textbook Shamir over GF(2^8) (the AES field, reducing
14//! polynomial 0x11B). [`split_backup`] and [`recover_backup`] carry the whole
15//! identity (its DID, its Ed25519 seed and further keys such as the ML-DSA-44
16//! key) with a check value that catches a wrong, damaged or missing share.
17//! [`split_identity`] and [`recover_identity`] handle the earlier seed-only
18//! shares, which carry no check value and do not hold the DID, so recovering
19//! them needs the DID from the caller.
20
21use crate::error::{CoreError, Result};
22use crate::keys::{Ed25519KeyPair, ED25519_SEED_LEN};
23
24fn recovery_err(msg: impl Into<String>) -> CoreError {
25    CoreError::Crypto(msg.into())
26}
27
28// ---------------------------------------------------------------------------
29// GF(2^8) arithmetic (AES field, reducing polynomial 0x11B)
30// ---------------------------------------------------------------------------
31
32struct GfTables {
33    exp: [u8; 512],
34    log: [u8; 256],
35}
36
37fn gf_tables() -> &'static GfTables {
38    use std::sync::OnceLock;
39    static TABLES: OnceLock<GfTables> = OnceLock::new();
40    TABLES.get_or_init(|| {
41        // 3 (not 2) is a primitive element of GF(2^8) under 0x11B, so powers of
42        // 3 cycle through all 255 non-zero elements. Multiply by 3 = (x*2) XOR x.
43        let mut exp = [0u8; 512];
44        let mut log = [0u8; 256];
45        let mut x: u16 = 1;
46        #[allow(clippy::needless_range_loop)] // log is indexed by x, not by i
47        for i in 0..255usize {
48            exp[i] = x as u8;
49            log[x as usize] = i as u8;
50            let mut x2 = x << 1;
51            if x2 & 0x100 != 0 {
52                x2 ^= 0x11B;
53            }
54            x ^= x2;
55        }
56        // exp[255..512) mirrors exp[0..257) (period 255); each entry depends on
57        // one already computed earlier in this same range, so this must stay a
58        // sequential loop rather than a single bulk copy.
59        #[allow(clippy::needless_range_loop)]
60        for i in 255..512 {
61            exp[i] = exp[i - 255];
62        }
63        GfTables { exp, log }
64    })
65}
66
67fn gf_mul(a: u8, b: u8) -> u8 {
68    if a == 0 || b == 0 {
69        return 0;
70    }
71    let t = gf_tables();
72    t.exp[t.log[a as usize] as usize + t.log[b as usize] as usize]
73}
74
75fn gf_inv(a: u8) -> Result<u8> {
76    if a == 0 {
77        return Err(recovery_err("no inverse for 0 in GF(2^8)"));
78    }
79    let t = gf_tables();
80    Ok(t.exp[255 - t.log[a as usize] as usize])
81}
82
83/// Evaluates a polynomial (coefficients low-order first) at `x` in GF(2^8).
84fn eval_poly(coeffs: &[u8], x: u8) -> u8 {
85    let mut result = 0u8;
86    for &c in coeffs.iter().rev() {
87        result = gf_mul(result, x) ^ c;
88    }
89    result
90}
91
92/// Lagrange-interpolates the points and returns the value at x = 0.
93fn interpolate_at_zero(xs: &[u8], ys: &[u8]) -> Result<u8> {
94    let mut result = 0u8;
95    for i in 0..xs.len() {
96        let mut num = 1u8;
97        let mut den = 1u8;
98        for j in 0..xs.len() {
99            if i == j {
100                continue;
101            }
102            num = gf_mul(num, xs[j]); // (0 - xj) == xj in GF(2^8)
103            den = gf_mul(den, xs[i] ^ xs[j]); // (xi - xj) == xi ^ xj
104        }
105        let inv = gf_inv(den)?;
106        result ^= gf_mul(ys[i], gf_mul(num, inv));
107    }
108    Ok(result)
109}
110
111// ---------------------------------------------------------------------------
112// Byte-level split / combine
113// ---------------------------------------------------------------------------
114
115/// Splits `secret` into `shares` pieces; any `threshold` of them reconstruct
116/// it. Each returned share is a leading index byte (1..=shares) followed by
117/// the share body, the same length as `secret`.
118pub fn split_secret(secret: &[u8], threshold: u16, shares: u16) -> Result<Vec<Vec<u8>>> {
119    if secret.is_empty() {
120        return Err(recovery_err("secret must be non-empty bytes"));
121    }
122    if threshold < 2 || threshold > shares || shares > 255 {
123        return Err(recovery_err("require 2 <= threshold <= shares <= 255"));
124    }
125
126    let mut out: Vec<Vec<u8>> = (1..=shares).map(|i| vec![i as u8]).collect();
127
128    for &b in secret {
129        let mut coeffs = vec![0u8; threshold as usize];
130        coeffs[0] = b;
131        if threshold > 1 {
132            getrandom::getrandom(&mut coeffs[1..])
133                .map_err(|e| recovery_err(format!("rng: {e}")))?;
134        }
135        for (i, out_share) in out.iter_mut().enumerate() {
136            out_share.push(eval_poly(&coeffs, (i + 1) as u8));
137        }
138    }
139    Ok(out)
140}
141
142/// Reconstructs a secret from `threshold` (or more) shares. Supplying fewer
143/// than the original threshold returns a wrong value, not an error.
144pub fn combine_shares(shares: &[Vec<u8>]) -> Result<Vec<u8>> {
145    if shares.len() < 2 {
146        return Err(recovery_err("need at least 2 shares"));
147    }
148    let mut xs = Vec::with_capacity(shares.len());
149    let mut bodies = Vec::with_capacity(shares.len());
150    let mut seen = std::collections::HashSet::new();
151    for s in shares {
152        if s.len() < 2 {
153            return Err(recovery_err("malformed share"));
154        }
155        if s[0] == 0 {
156            // x = 0 is where the secret sits: a share there would be taken as
157            // the secret itself, whatever the other shares say.
158            return Err(recovery_err("malformed share: index 0 is not a share"));
159        }
160        if !seen.insert(s[0]) {
161            return Err(recovery_err("shares must have distinct indices"));
162        }
163        xs.push(s[0]);
164        bodies.push(&s[1..]);
165    }
166    let length = bodies[0].len();
167    if bodies.iter().any(|b| b.len() != length) {
168        return Err(recovery_err("shares have inconsistent length"));
169    }
170
171    let mut secret = vec![0u8; length];
172    for j in 0..length {
173        let ys: Vec<u8> = bodies.iter().map(|b| b[j]).collect();
174        secret[j] = interpolate_at_zero(&xs, &ys)?;
175    }
176    Ok(secret)
177}
178
179// ---------------------------------------------------------------------------
180// Vouch identity recovery
181// ---------------------------------------------------------------------------
182
183/// Splits a root identity's Ed25519 seed into shares in the earlier,
184/// seed-only format. Any threshold of them recover the identity via
185/// [`recover_identity`]. Prefer [`split_backup`], which also carries the DID and
186/// further keys and catches a damaged share.
187pub fn split_identity(seed: &[u8], threshold: u16, shares: u16) -> Result<Vec<Vec<u8>>> {
188    if seed.len() != ED25519_SEED_LEN {
189        return Err(CoreError::InvalidKeyLength {
190            expected: ED25519_SEED_LEN,
191            got: seed.len(),
192        });
193    }
194    split_secret(seed, threshold, shares)
195}
196
197/// The answer when shares in the earlier seed-only format come with no DID.
198pub const OLD_SHARES_NEED_DID: &str =
199    "these shares come from an older backup that does not hold the DID; pass the DID to recover them";
200
201/// A root identity rebuilt from recovery shares.
202pub struct RecoveredIdentity {
203    pub did: String,
204    pub seed: [u8; ED25519_SEED_LEN],
205    pub public_key: [u8; 32],
206}
207
208/// Recovers a root identity from threshold shares in the earlier seed-only
209/// format. The recovered seed is deterministic, so the rebuilt key is
210/// identical to the original. These shares do not say which DID they belong
211/// to, so `did` must name it (the DID the shares were split under); `None` or
212/// an empty DID is an error.
213pub fn recover_identity(shares: &[Vec<u8>], did: Option<&str>) -> Result<RecoveredIdentity> {
214    let did = match did {
215        Some(d) if !d.is_empty() => d.to_string(),
216        _ => return Err(recovery_err(OLD_SHARES_NEED_DID)),
217    };
218    let seed_vec = combine_shares(shares)?;
219    if seed_vec.len() != ED25519_SEED_LEN {
220        return Err(recovery_err(format!(
221            "recovered seed is not {ED25519_SEED_LEN} bytes; wrong or too few shares"
222        )));
223    }
224    let seed: [u8; ED25519_SEED_LEN] = seed_vec
225        .try_into()
226        .map_err(|_| recovery_err("recovered seed had unexpected length"))?;
227
228    let keypair = Ed25519KeyPair::from_seed(&seed);
229    let public_key = keypair.public_key();
230
231    Ok(RecoveredIdentity {
232        did,
233        seed,
234        public_key,
235    })
236}
237
238// ---------------------------------------------------------------------------
239// Identity backups (the "vouch-recovery-2:" share format)
240// ---------------------------------------------------------------------------
241//
242// A recovery share is the text "vouch-recovery-2:" followed by the standard
243// base64 of `set_id (8 bytes) | threshold (1 byte) | index (1 byte) | body`.
244// All shares of one split carry the same random set_id. The bodies are the
245// Shamir split of `SHA-256(J) | J`, where J is the UTF-8 JSON object
246// `{"v":2,"did"?:string,"seed":b64,"keys":[{"id","alg","public_key","private_key":b64}]}`.
247// One set of shares brings back every key of the identity, and the check value
248// tells a wrong, damaged or missing share apart from a good recovery. The
249// format is defined by the Python reference (vouch.recovery) and pinned by
250// test-vectors/recovery/vector.json.
251
252/// The text every share in the backup format starts with.
253pub const SHARE_PREFIX: &str = "vouch-recovery-2:";
254const SET_ID_LEN: usize = 8;
255const BACKUP_VERSION: u64 = 2;
256const MLDSA44: &str = "ML-DSA-44";
257const MLDSA44_KEY_ID: &str = "#key-2";
258
259/// A further key of an identity carried in a backup, such as its ML-DSA-44
260/// key in the "#key-2" slot. The private key is wiped from memory on drop.
261#[derive(Clone)]
262pub struct BackupKey {
263    pub id: String,
264    pub alg: String,
265    /// The public key as a Multikey string.
266    pub public_key: String,
267    /// The raw private key bytes.
268    pub private_key: Vec<u8>,
269}
270
271impl Drop for BackupKey {
272    fn drop(&mut self) {
273        use zeroize::Zeroize;
274        self.private_key.zeroize();
275    }
276}
277
278impl std::fmt::Debug for BackupKey {
279    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
280        f.debug_struct("BackupKey")
281            .field("id", &self.id)
282            .field("alg", &self.alg)
283            .field("public_key", &self.public_key)
284            .finish_non_exhaustive()
285    }
286}
287
288/// An identity rebuilt from backup shares.
289pub struct RecoveredBackup {
290    /// The DID the shares were made for, when they carry one.
291    pub did: Option<String>,
292    pub seed: [u8; ED25519_SEED_LEN],
293    pub public_key: [u8; 32],
294    pub keys: Vec<BackupKey>,
295}
296
297impl Drop for RecoveredBackup {
298    fn drop(&mut self) {
299        use zeroize::Zeroize;
300        self.seed.zeroize();
301    }
302}
303
304/// Checks one further key: slot and algorithm agree, and an ML-DSA-44 key's
305/// private half is exactly the one key generation makes for its public half
306/// (see [`crate::mldsa_check`]).
307fn check_backup_key(key: &BackupKey) -> std::result::Result<(), String> {
308    if key.id.is_empty()
309        || key.alg.is_empty()
310        || key.public_key.is_empty()
311        || key.private_key.is_empty()
312    {
313        return Err("a key entry is malformed".into());
314    }
315    if (key.alg == MLDSA44) != (key.id == MLDSA44_KEY_ID) {
316        return Err("a key entry is malformed".into());
317    }
318    if key.alg != MLDSA44 {
319        return Ok(());
320    }
321    let decoded = crate::multikey::decode(&key.public_key)
322        .map_err(|_| "the ML-DSA-44 public key is not a Multikey".to_string())?;
323    if decoded.algorithm != MLDSA44 || decoded.raw_key.len() != crate::pq::MLDSA44_PUBLIC_LEN {
324        return Err("the ML-DSA-44 public key is not an ML-DSA-44 key".into());
325    }
326    if key.private_key.len() != crate::pq::MLDSA44_SECRET_LEN {
327        return Err("the ML-DSA-44 private key is the wrong size".into());
328    }
329    if !crate::mldsa_check::mldsa44_keys_match(&decoded.raw_key, &key.private_key) {
330        return Err("the ML-DSA-44 public key does not match its private key".into());
331    }
332    Ok(())
333}
334
335/// The rules every set of further keys follows, on split and on recovery.
336fn check_backup_keys(keys: &[BackupKey]) -> std::result::Result<(), String> {
337    for (i, key) in keys.iter().enumerate() {
338        check_backup_key(key)?;
339        if keys[..i].iter().any(|k| k.id == key.id || k.alg == key.alg) {
340            return Err("it repeats a key: one key per slot and per algorithm".into());
341        }
342    }
343    Ok(())
344}
345
346/// Splits an identity into backup shares, any `threshold` of which bring it
347/// back with [`recover_backup`]: its Ed25519 seed, its DID when given, and its
348/// further keys, such as the ML-DSA-44 key in "#key-2". Keys are checked with
349/// the same rules recovery uses, so a backup that splits also recovers.
350pub fn split_backup(
351    seed: &[u8],
352    did: Option<&str>,
353    keys: &[BackupKey],
354    threshold: u16,
355    shares: u16,
356) -> Result<Vec<String>> {
357    use base64::{engine::general_purpose::STANDARD, Engine};
358    use sha2::{Digest, Sha256};
359    use zeroize::Zeroizing;
360
361    if seed.len() != ED25519_SEED_LEN {
362        return Err(CoreError::InvalidKeyLength {
363            expected: ED25519_SEED_LEN,
364            got: seed.len(),
365        });
366    }
367    check_backup_keys(keys).map_err(recovery_err)?;
368    let mut backup = serde_json::Map::new();
369    backup.insert("v".into(), serde_json::json!(BACKUP_VERSION));
370    if let Some(d) = did.filter(|d| !d.is_empty()) {
371        backup.insert("did".into(), serde_json::json!(d));
372    }
373    backup.insert("seed".into(), serde_json::json!(STANDARD.encode(seed)));
374    let rows: Vec<serde_json::Value> = keys
375        .iter()
376        .map(|k| {
377            serde_json::json!({
378                "id": k.id,
379                "alg": k.alg,
380                "public_key": k.public_key,
381                "private_key": STANDARD.encode(&k.private_key),
382            })
383        })
384        .collect();
385    backup.insert("keys".into(), serde_json::Value::Array(rows));
386    let body = Zeroizing::new(crate::jcs::canonicalize(&serde_json::Value::Object(backup)));
387    let mut data = Zeroizing::new(Sha256::digest(&*body).to_vec());
388    data.extend_from_slice(&body);
389
390    let pieces = split_secret(&data, threshold, shares)?;
391    let mut set_id = [0u8; SET_ID_LEN];
392    getrandom::getrandom(&mut set_id).map_err(|e| recovery_err(format!("rng: {e}")))?;
393    Ok(pieces
394        .into_iter()
395        .map(|piece| {
396            let mut raw = set_id.to_vec();
397            raw.push(threshold as u8);
398            raw.extend_from_slice(&piece);
399            format!("{SHARE_PREFIX}{}", STANDARD.encode(raw))
400        })
401        .collect())
402}
403
404/// Spaces, tabs and line breaks around a share are not part of it.
405pub fn trim_share(share: &str) -> &str {
406    share.trim_matches(|c| matches!(c, ' ' | '\t' | '\r' | '\n'))
407}
408
409/// True when `share` is in the backup format rather than the earlier one.
410pub fn is_backup_share(share: &str) -> bool {
411    trim_share(share).starts_with(SHARE_PREFIX)
412}
413
414/// Standard, padded base64 written the one canonical way.
415pub fn strict_base64(text: &str) -> Option<Vec<u8>> {
416    use base64::{engine::general_purpose::STANDARD, Engine};
417    let raw = STANDARD.decode(text).ok()?;
418    (STANDARD.encode(&raw) == text).then_some(raw)
419}
420
421fn same_bytes(a: &[u8], b: &[u8]) -> bool {
422    a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
423}
424
425/// Reads J, which must be exactly its own canonical JSON with the known members.
426fn parse_backup(body: &[u8]) -> std::result::Result<RecoveredBackup, String> {
427    let backup: serde_json::Value =
428        serde_json::from_slice(body).map_err(|_| "it is not valid JSON text".to_string())?;
429    if crate::jcs::canonicalize(&backup) != body {
430        return Err("it is not in canonical form".into());
431    }
432    let object = backup.as_object().ok_or("it has unexpected members")?;
433    let allowed = ["v", "seed", "keys", "did"];
434    if !object.keys().all(|k| allowed.contains(&k.as_str()))
435        || !["v", "seed", "keys"]
436            .iter()
437            .all(|k| object.contains_key(*k))
438    {
439        return Err("it has unexpected members".into());
440    }
441    if object["v"].as_u64() != Some(BACKUP_VERSION) {
442        return Err("unknown backup version".into());
443    }
444    let seed_vec = object["seed"]
445        .as_str()
446        .and_then(strict_base64)
447        .ok_or("the seed is not canonical base64")?;
448    let seed: [u8; ED25519_SEED_LEN] = seed_vec
449        .try_into()
450        .map_err(|_| "the seed is not 32 bytes".to_string())?;
451    let did = match object.get("did") {
452        None => None,
453        Some(serde_json::Value::String(d)) if !d.is_empty() => Some(d.clone()),
454        Some(_) => return Err("its DID is not a DID".into()),
455    };
456    let rows = object["keys"]
457        .as_array()
458        .ok_or("its key list is not a list")?;
459    let mut keys = Vec::with_capacity(rows.len());
460    for row in rows {
461        let fields = row.as_object().ok_or("a key entry is malformed")?;
462        let names = ["id", "alg", "public_key", "private_key"];
463        if fields.len() != names.len()
464            || !names
465                .iter()
466                .all(|n| fields.get(*n).is_some_and(|v| v.is_string()))
467        {
468            return Err("a key entry is malformed".into());
469        }
470        let text = |n: &str| fields[n].as_str().unwrap_or_default().to_string();
471        let private_key = strict_base64(&text("private_key")).ok_or("a key entry is malformed")?;
472        keys.push(BackupKey {
473            id: text("id"),
474            alg: text("alg"),
475            public_key: text("public_key"),
476            private_key,
477        });
478    }
479    check_backup_keys(&keys)?;
480    let public_key = Ed25519KeyPair::from_seed(&seed).public_key();
481    Ok(RecoveredBackup {
482        did,
483        seed,
484        public_key,
485        keys,
486    })
487}
488
489/// Rebuilds an identity from backup shares.
490///
491/// Errors on too few shares, shares from different backups, the same share
492/// twice, a share at index 0, or a damaged or altered share.
493pub fn recover_backup(shares: &[String]) -> Result<RecoveredBackup> {
494    use sha2::{Digest, Sha256};
495    use zeroize::Zeroizing;
496
497    if shares.is_empty() {
498        return Err(recovery_err("no recovery shares were given"));
499    }
500    let mut set_id: Option<Vec<u8>> = None;
501    let mut threshold: Option<u8> = None;
502    let mut pieces: Vec<Zeroizing<Vec<u8>>> = Vec::with_capacity(shares.len());
503    for share in shares {
504        let text = trim_share(share)
505            .strip_prefix(SHARE_PREFIX)
506            .ok_or_else(|| {
507                recovery_err("these shares come from different backups; use shares from one backup")
508            })?;
509        let raw = Zeroizing::new(strict_base64(text).ok_or_else(|| {
510            recovery_err("a recovery share is damaged: it is not canonical base64")
511        })?);
512        if raw.len() < SET_ID_LEN + 3 {
513            return Err(recovery_err("a recovery share is damaged: it is too short"));
514        }
515        if raw[SET_ID_LEN] < 2 {
516            return Err(recovery_err(
517                "a recovery share is damaged: its threshold is below 2",
518            ));
519        }
520        if raw[SET_ID_LEN + 1] == 0 {
521            return Err(recovery_err(
522                "a recovery share is damaged: index 0 is not a share",
523            ));
524        }
525        let (id, rest) = raw.split_at(SET_ID_LEN);
526        if set_id.get_or_insert_with(|| id.to_vec()) != id
527            || *threshold.get_or_insert(rest[0]) != rest[0]
528        {
529            return Err(recovery_err(
530                "these shares come from different backups, or one of them is damaged; \
531                 use shares from one backup",
532            ));
533        }
534        pieces.push(Zeroizing::new(rest[1..].to_vec()));
535    }
536    let mut indices = std::collections::HashSet::new();
537    if !pieces.iter().all(|p| indices.insert(p[0])) {
538        return Err(recovery_err("the same share was given twice"));
539    }
540    let needed = threshold.unwrap_or(0) as usize;
541    if pieces.len() < needed {
542        return Err(recovery_err(format!(
543            "this backup needs {needed} shares to recover, and {} were given",
544            pieces.len()
545        )));
546    }
547    let plain: Vec<Vec<u8>> = pieces.iter().map(|p| p.to_vec()).collect();
548    let combined = combine_shares(&plain);
549    for mut p in plain {
550        use zeroize::Zeroize;
551        p.zeroize();
552    }
553    let data = Zeroizing::new(combined?);
554    if data.len() < 33 || !same_bytes(Sha256::digest(&data[32..]).as_slice(), &data[..32]) {
555        return Err(recovery_err(
556            "the shares do not recover a backup: one of them is damaged or altered",
557        ));
558    }
559    parse_backup(&data[32..])
560        .map_err(|why| recovery_err(format!("the recovered backup cannot be read: {why}")))
561}
562
563#[cfg(test)]
564mod tests {
565    use super::*;
566    use crate::keys::ed25519_to_did_key;
567
568    #[test]
569    fn split_and_combine_roundtrips() {
570        let secret = [7u8; 32];
571        let shares = split_secret(&secret, 3, 5).unwrap();
572        assert_eq!(shares.len(), 5);
573
574        let combined = combine_shares(&shares[0..3]).unwrap();
575        assert_eq!(combined, secret.to_vec());
576
577        let alt = vec![shares[0].clone(), shares[2].clone(), shares[4].clone()];
578        let combined2 = combine_shares(&alt).unwrap();
579        assert_eq!(combined2, secret.to_vec());
580    }
581
582    #[test]
583    fn below_threshold_does_not_reveal_secret() {
584        let secret = [9u8; 16];
585        let shares = split_secret(&secret, 3, 5).unwrap();
586        let combined = combine_shares(&shares[0..2]).unwrap();
587        assert_ne!(combined, secret.to_vec());
588    }
589
590    #[test]
591    fn split_secret_rejects_bad_parameters() {
592        assert!(split_secret(&[], 2, 3).is_err());
593        assert!(split_secret(&[1], 1, 3).is_err());
594        assert!(split_secret(&[1], 4, 3).is_err());
595    }
596
597    #[test]
598    fn combine_shares_rejects_inconsistent_input() {
599        let secret = [1u8; 16];
600        let shares = split_secret(&secret, 2, 3).unwrap();
601        let dup = vec![shares[0].clone(), shares[0].clone()];
602        assert!(combine_shares(&dup).is_err());
603
604        let mut short = shares[1].clone();
605        short.truncate(6);
606        let mismatched = vec![shares[0].clone(), short];
607        assert!(combine_shares(&mismatched).is_err());
608    }
609
610    #[test]
611    fn split_and_recover_identity_signs_identically() {
612        let keypair = Ed25519KeyPair::generate().unwrap();
613        let seed = keypair.seed();
614        let did = ed25519_to_did_key(&keypair.public_key()).unwrap();
615
616        let shares = split_identity(&seed, 2, 3).unwrap();
617        assert_eq!(shares.len(), 3);
618
619        let recovered = recover_identity(&shares[0..2], Some(&did)).unwrap();
620        assert_eq!(recovered.did, did);
621        assert_eq!(recovered.public_key, keypair.public_key());
622
623        let message = b"charge api.bank invoices/42";
624        let sig = Ed25519KeyPair::from_seed(&recovered.seed).sign(message);
625        assert!(crate::keys::verify(&keypair.public_key(), message, &sig).unwrap());
626    }
627
628    #[test]
629    fn earlier_shares_need_the_did() {
630        let keypair = Ed25519KeyPair::generate().unwrap();
631        let shares = split_identity(&keypair.seed(), 2, 3).unwrap();
632        for did in [None, Some("")] {
633            let err = recover_identity(&shares[1..3], did)
634                .err()
635                .expect("earlier shares with no DID must be refused");
636            assert!(
637                err.to_string().contains(OLD_SHARES_NEED_DID),
638                "unexpected error: {err}"
639            );
640        }
641        // The DID is asked for before the shares are read, so damaged
642        // shares with no DID get the same answer.
643        let err = recover_identity(&[vec![0, 1], vec![1]], None)
644            .err()
645            .unwrap();
646        assert!(err.to_string().contains(OLD_SHARES_NEED_DID));
647    }
648
649    fn mldsa_backup_key(private_key: Vec<u8>, public_key: &[u8]) -> BackupKey {
650        BackupKey {
651            id: MLDSA44_KEY_ID.into(),
652            alg: MLDSA44.into(),
653            public_key: crate::multikey::encode_mldsa44_public(public_key).unwrap(),
654            private_key,
655        }
656    }
657
658    #[test]
659    fn backup_keys_are_checked_by_recomputing_the_key() {
660        let pair = crate::pq::MlDsa44KeyPair::generate().unwrap();
661        let (pk, sk) = (pair.public_key(), pair.secret_key());
662        let seed = [4u8; ED25519_SEED_LEN];
663        let good = mldsa_backup_key(sk.to_vec(), &pk);
664        let shares = split_backup(&seed, None, &[good], 2, 3).unwrap();
665        let back = recover_backup(&shares[..2]).unwrap();
666        assert_eq!(back.keys[0].private_key, sk.to_vec());
667
668        // K (bytes 32..64) is the signing seed: any K is a working key.
669        let mut other_k = sk.to_vec();
670        other_k[32..64].fill(0xA5);
671        assert!(split_backup(&seed, None, &[mldsa_backup_key(other_k, &pk)], 2, 3).is_ok());
672
673        // A flipped bit in rho, tr, s1, s2 or t0 is refused.
674        for at in [0, 64, 128, 512, 896, 2559] {
675            let mut damaged = sk.to_vec();
676            damaged[at] ^= 0x01;
677            let err = split_backup(&seed, None, &[mldsa_backup_key(damaged, &pk)], 2, 3)
678                .expect_err("damaged key must be refused");
679            assert!(
680                err.to_string().contains("does not match its private key"),
681                "byte {at}: {err}"
682            );
683        }
684    }
685
686    #[test]
687    fn too_few_shares_gives_a_wrong_key_not_an_error() {
688        let keypair = Ed25519KeyPair::generate().unwrap();
689        let seed = keypair.seed();
690        let did = ed25519_to_did_key(&keypair.public_key()).unwrap();
691
692        let shares = split_identity(&seed, 3, 5).unwrap();
693        // Two shares when three are required: recover_identity still returns
694        // structurally, but the seed (and therefore the public key) will not
695        // match the original, since interpolation with too few points gives
696        // the wrong value.
697        let recovered = recover_identity(&shares[0..2], Some(&did)).unwrap();
698        assert_ne!(recovered.public_key, keypair.public_key());
699        assert_ne!(recovered.seed, seed);
700    }
701}