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