keep-core 0.7.5

Core library for Keep - sovereign key management for Nostr and Bitcoin
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
// SPDX-FileCopyrightText: © 2026 PrivKey LLC
// SPDX-License-Identifier: MIT
use std::collections::{BTreeMap, BTreeSet};

use frost::keys::refresh::{compute_refreshing_shares, refresh_share};
use frost::keys::{KeyPackage, PublicKeyPackage, VerifyingShare};
use frost::rand_core::OsRng;
use frost::Identifier;
use frost_secp256k1_tr as frost;
use zeroize::Zeroizing;

use crate::error::{KeepError, Result};

use super::share::{ShareMetadata, SharePackage};

fn rebuild_metadata(
    share: &SharePackage,
    threshold: u16,
    total: u16,
    group_pubkey: [u8; 32],
    name: String,
) -> ShareMetadata {
    let mut metadata = ShareMetadata::new(
        share.metadata.identifier,
        threshold,
        total,
        group_pubkey,
        name,
    );
    metadata.created_at = share.metadata.created_at;
    metadata.last_used = share.metadata.last_used;
    metadata.sign_count = share.metadata.sign_count;
    metadata
}

/// Refresh all shares, producing new shares for the same group public key.
pub fn refresh_shares(shares: &[SharePackage]) -> Result<(Vec<SharePackage>, PublicKeyPackage)> {
    if shares.is_empty() {
        return Err(KeepError::Frost("No shares provided".into()));
    }

    let threshold = shares[0].metadata.threshold;
    let total = shares[0].metadata.total_shares;
    let name = shares[0].metadata.name.clone();

    let group_pubkey = *shares[0].group_pubkey();

    for share in &shares[1..] {
        if *share.group_pubkey() != group_pubkey {
            return Err(KeepError::Frost(
                "All shares must belong to the same group".into(),
            ));
        }
        if share.metadata.threshold != threshold {
            return Err(KeepError::Frost(
                "Inconsistent threshold across shares".into(),
            ));
        }
        if share.metadata.total_shares != total {
            return Err(KeepError::Frost(
                "Inconsistent total_shares across shares".into(),
            ));
        }
    }

    let share_count: u16 = shares
        .len()
        .try_into()
        .map_err(|_| KeepError::Frost("Too many shares".into()))?;
    if share_count < threshold {
        return Err(KeepError::Frost(format!(
            "Need at least {threshold} shares to refresh, only {share_count} available"
        )));
    }
    // #586: FROST 3.0's `compute_refreshing_shares` only refreshes the
    // identifiers passed in, so a subset call (>= threshold but < total)
    // silently orphans every absent share. The refreshed shares still
    // advertise the full `total_shares` in metadata, so a holder of an
    // absent share would believe they are still part of the group when
    // they have actually been excluded. Refuse partial refresh outright;
    // callers must collect the full set or use a different protocol.
    if share_count != total {
        return Err(KeepError::Frost(format!(
            "refresh_shares requires the full set of {total} shares; got {share_count}. \
             A partial refresh would silently orphan the absent shares (#586)."
        )));
    }
    // #586: a full-cardinality call with a duplicated identifier (e.g. [A, A, B]
    // for a 3-member group) passes the count guard yet still orphans the absent
    // member, because `refreshing_by_id` collapses the duplicate. Require every
    // supplied share to carry a distinct identifier.
    let mut seen = BTreeSet::new();
    for share in shares {
        if !seen.insert(share.metadata.identifier) {
            return Err(KeepError::Frost(format!(
                "refresh_shares requires distinct identifiers; identifier {} appears more than \
                 once. A partial refresh would silently orphan the absent shares (#586).",
                share.metadata.identifier
            )));
        }
    }

    let pubkey_pkg = shares[0].pubkey_package()?;
    let pubkey_pkg = PublicKeyPackage::new(
        pubkey_pkg.verifying_shares().clone(),
        *pubkey_pkg.verifying_key(),
        Some(threshold),
    );

    let key_packages = Zeroizing::new(
        shares
            .iter()
            .map(|s| s.key_package())
            .collect::<Result<Vec<KeyPackage>>>()?,
    );

    let identifiers: Vec<Identifier> = key_packages.iter().map(|kp| *kp.identifier()).collect();

    let (refreshing_shares, new_pubkey_pkg) =
        compute_refreshing_shares(pubkey_pkg, &identifiers, &mut OsRng)
            .map_err(|e| KeepError::Frost(format!("Compute refreshing shares failed: {e}")))?;

    if refreshing_shares.len() != identifiers.len() {
        return Err(KeepError::Frost(format!(
            "Expected {} refreshing shares, got {}",
            identifiers.len(),
            refreshing_shares.len()
        )));
    }

    let refreshing_by_id: BTreeMap<Identifier, _> =
        identifiers.iter().copied().zip(refreshing_shares).collect();

    let mut new_packages = Vec::with_capacity(shares.len());

    for (share, current_kp) in shares.iter().zip(key_packages.iter()) {
        let id = *current_kp.identifier();
        let refreshing_share = refreshing_by_id.get(&id).ok_or_else(|| {
            KeepError::Frost(format!("No refreshing share for identifier {id:?}"))
        })?;

        let new_kp = refresh_share(refreshing_share.clone(), current_kp)
            .map_err(|e| KeepError::Frost(format!("Refresh share failed: {e}")))?;

        if new_kp.identifier() != &id {
            return Err(KeepError::Frost(
                "refreshing share identifier does not match target share".into(),
            ));
        }

        // Real post-refresh verification: derive this share's public verifying
        // share (g^{s_i}) from the refreshed *secret* share and require it to
        // match the value published in `new_pubkey_pkg`. This is the check that
        // proves the refresh produced correct shares; it catches a corrupted or
        // mis-assigned secret before it is ever persisted. (frost-core preserves
        // the group `verifying_key` verbatim across a refresh, so a group-key
        // comparison alone cannot detect a bad refresh.)
        let derived_vs = VerifyingShare::from(*new_kp.signing_share());
        let published_vs = new_pubkey_pkg.verifying_shares().get(&id).ok_or_else(|| {
            KeepError::Frost(format!(
                "No verifying share for identifier {id:?} in refreshed pubkey package"
            ))
        })?;
        if derived_vs != *published_vs {
            return Err(KeepError::Frost(
                "refreshed share does not match its published verifying share - aborting".into(),
            ));
        }

        let metadata = rebuild_metadata(share, threshold, total, group_pubkey, name.clone());
        new_packages.push(SharePackage::new(metadata, &new_kp, &new_pubkey_pkg)?);
    }

    // Input-consistency guard: `new_pubkey_pkg.verifying_key()` is the group key
    // frost-core carries forward unchanged across a refresh (only the verifying
    // shares change), so this confirms the input share's stored `group_pubkey`
    // agrees with its pubkey package. `SharePackage` stores the two independently
    // and does not enforce that they match, so this can still fire on an
    // inconsistent input. The per-share checks above are what verify the refresh
    // itself.
    let refreshed_group_pubkey = super::dealer::extract_group_pubkey(&new_pubkey_pkg)?;
    if refreshed_group_pubkey != group_pubkey {
        return Err(KeepError::Frost(
            "Group public key changed after refresh - aborting".into(),
        ));
    }

    Ok((new_packages, new_pubkey_pkg))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::frost::{sign_with_local_shares, ThresholdConfig, TrustedDealer};

    /// A pre-3.0 stored pubkey package decodes with `min_signers = None`, so
    /// refreshing a share loaded from disk must hit the `Some(threshold)`
    /// rebuild path before `compute_refreshing_shares`. Freshly
    /// dealt 3.0 packages already carry `Some`, so re-serialize each pubkey
    /// without `min_signers` to reproduce the legacy on-disk layout.
    #[test]
    fn test_refresh_with_legacy_pubkey_package() {
        use crate::frost::share::SharePackage;

        let dealer = TrustedDealer::new(ThresholdConfig::two_of_three());
        let (shares, _) = dealer.generate("legacy").unwrap();
        let group_pubkey = *shares[0].group_pubkey();

        let legacy: Vec<SharePackage> = shares
            .iter()
            .map(|s| {
                let pk = s.pubkey_package().unwrap();
                let old_pubkey =
                    PublicKeyPackage::new(pk.verifying_shares().clone(), *pk.verifying_key(), None)
                        .serialize()
                        .unwrap();
                SharePackage::from_bytes(
                    s.metadata.clone(),
                    s.key_package_bytes().to_vec(),
                    old_pubkey,
                )
            })
            .collect();

        assert!(legacy[0].pubkey_package().unwrap().min_signers().is_none());

        let (refreshed, _) = refresh_shares(&legacy).unwrap();
        assert_eq!(refreshed.len(), 3);
        for share in &refreshed {
            assert_eq!(*share.group_pubkey(), group_pubkey);
        }

        let sig = sign_with_local_shares(&refreshed, b"refresh after legacy load").unwrap();
        assert_eq!(sig.len(), 64);
    }

    #[test]
    fn test_refresh_shares_preserves_group_key() {
        let config = ThresholdConfig::two_of_three();
        let dealer = TrustedDealer::new(config);
        let (shares, _) = dealer.generate("test").unwrap();

        let original_group_pubkey = *shares[0].group_pubkey();

        let (refreshed, _) = refresh_shares(&shares).unwrap();

        assert_eq!(refreshed.len(), 3);
        for share in &refreshed {
            assert_eq!(*share.group_pubkey(), original_group_pubkey);
            assert_eq!(share.metadata.threshold, 2);
            assert_eq!(share.metadata.total_shares, 3);
        }
    }

    /// The group-key guard must fire when a share's stored `group_pubkey`
    /// metadata disagrees with its pubkey package. `SharePackage` keeps the two
    /// independently, so an inconsistent input must abort rather than silently
    /// emit shares under the wrong advertised key. Every metadata copy is
    /// rewritten to the same bogus value so the earlier cross-share equality
    /// check passes and execution reaches the group-key guard, which compares
    /// against the untouched pubkey package.
    #[test]
    fn test_refresh_rejects_group_pubkey_metadata_mismatch() {
        use crate::frost::share::SharePackage;

        let dealer = TrustedDealer::new(ThresholdConfig::two_of_three());
        let (shares, _) = dealer.generate("mismatch").unwrap();

        let bogus = [0xABu8; 32];
        let tampered: Vec<SharePackage> = shares
            .iter()
            .map(|s| {
                let mut md = s.metadata.clone();
                md.group_pubkey = bogus;
                SharePackage::from_bytes(
                    md,
                    s.key_package_bytes().to_vec(),
                    s.pubkey_package_bytes().to_vec(),
                )
            })
            .collect();

        let err = match refresh_shares(&tampered) {
            Ok(_) => panic!("expected refresh to abort on group pubkey mismatch"),
            Err(e) => e,
        };
        assert!(
            err.to_string()
                .contains("Group public key changed after refresh"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn test_refreshed_shares_can_sign() {
        let config = ThresholdConfig::two_of_three();
        let dealer = TrustedDealer::new(config);
        let (shares, _) = dealer.generate("test").unwrap();

        let (refreshed, _) = refresh_shares(&shares).unwrap();

        let message = b"test message after refresh";
        let sig = sign_with_local_shares(&refreshed, message).unwrap();
        assert_eq!(sig.len(), 64);
    }

    #[test]
    fn test_old_shares_incompatible_with_new() {
        let config = ThresholdConfig::two_of_three();
        let dealer = TrustedDealer::new(config);
        let (shares, _) = dealer.generate("test").unwrap();

        let (refreshed, _) = refresh_shares(&shares).unwrap();

        let old_kp = shares[0].key_package().unwrap();
        let new_kp = refreshed[0].key_package().unwrap();
        assert_ne!(
            old_kp.signing_share().serialize(),
            new_kp.signing_share().serialize()
        );
    }

    #[test]
    fn test_multiple_refreshes() {
        let config = ThresholdConfig::two_of_three();
        let dealer = TrustedDealer::new(config);
        let (shares, _) = dealer.generate("test").unwrap();

        let original_pubkey = *shares[0].group_pubkey();

        let (refreshed1, _) = refresh_shares(&shares).unwrap();
        let (refreshed2, _) = refresh_shares(&refreshed1).unwrap();

        assert_eq!(*refreshed2[0].group_pubkey(), original_pubkey);

        let message = b"after double refresh";
        let sig = sign_with_local_shares(&refreshed2, message).unwrap();
        assert_eq!(sig.len(), 64);
    }

    #[test]
    fn test_refresh_empty_shares_fails() {
        let result = refresh_shares(&[]);
        assert!(result.is_err());
    }

    /// #586: a subset call (>= threshold but < total) MUST be refused.
    /// FROST 3.0's `compute_refreshing_shares` silently drops every absent
    /// identifier, and the refreshed shares still claim the full
    /// `total_shares` in metadata, so a holder of an absent share would
    /// believe they are still part of an N-of-M group after they have been
    /// orphaned. Pin both: 2 of 3 (above threshold, below total) refused,
    /// and the error message names the gap.
    #[test]
    fn test_refresh_with_subset_below_total_is_refused() {
        let config = ThresholdConfig::two_of_three();
        let dealer = TrustedDealer::new(config);
        let (mut shares, _) = dealer.generate("test-subset").unwrap();

        // Drop the third share, leaving 2 of 3 (meets threshold = 2).
        shares.pop();
        assert_eq!(shares.len(), 2);
        assert_eq!(shares[0].metadata.threshold, 2);
        assert_eq!(shares[0].metadata.total_shares, 3);

        let err = match refresh_shares(&shares) {
            Ok(_) => panic!("subset refresh must be refused"),
            Err(e) => e,
        };
        let msg = err.to_string();
        assert!(
            msg.contains("requires the full set") && msg.contains("3 shares"),
            "expected subset-refresh rejection naming the total, got {msg}"
        );
        assert!(
            msg.contains("got 2"),
            "expected the rejection to name the observed share count, got {msg}"
        );
        assert!(
            msg.contains("#586"),
            "rejection should reference the issue for future readers, got {msg}"
        );
    }

    /// #586: a full-cardinality call with a DUPLICATED identifier (e.g.
    /// [A, A, B] for a 3-member group) passes the count guard but still
    /// orphans the genuinely-absent member, because `refreshing_by_id`
    /// collapses the duplicate. Reject it before any rotation happens, and
    /// name the offending identifier.
    #[test]
    fn test_refresh_with_duplicate_identifier_is_refused() {
        use crate::frost::share::SharePackage;

        let config = ThresholdConfig::two_of_three();
        let dealer = TrustedDealer::new(config);
        let (mut shares, _) = dealer.generate("test-dup").unwrap();

        let dup_identifier = shares[0].metadata.identifier;
        let duplicate = SharePackage::from_bytes(
            shares[0].metadata.clone(),
            shares[0].key_package_bytes().to_vec(),
            shares[0].pubkey_package_bytes().to_vec(),
        );

        // Drop the third member and replace it with a copy of the first, so
        // there are still 3 shares but only 2 distinct identifiers.
        shares.pop();
        shares.push(duplicate);
        assert_eq!(shares.len(), 3);

        let err = match refresh_shares(&shares) {
            Ok(_) => panic!("duplicate-identifier refresh must be refused"),
            Err(e) => e,
        };
        let msg = err.to_string();
        assert!(
            msg.contains("distinct identifiers") && msg.contains(&dup_identifier.to_string()),
            "expected duplicate rejection naming the identifier, got {msg}"
        );
        assert!(
            msg.contains("#586"),
            "rejection should reference the issue for future readers, got {msg}"
        );
    }

    #[test]
    fn test_refresh_three_of_five() {
        let config = ThresholdConfig::three_of_five();
        let dealer = TrustedDealer::new(config);
        let (shares, _) = dealer.generate("test-3of5").unwrap();

        let original_pubkey = *shares[0].group_pubkey();
        let (refreshed, _) = refresh_shares(&shares).unwrap();

        assert_eq!(refreshed.len(), 5);
        assert_eq!(*refreshed[0].group_pubkey(), original_pubkey);

        let message = b"3-of-5 refresh test";
        let sig = sign_with_local_shares(&refreshed, message).unwrap();
        assert_eq!(sig.len(), 64);
    }

    /// **The security property #438 names**: an attacker who compromises a
    /// pre-refresh share MUST NOT be able to combine it with post-refresh
    /// shares to produce a valid signature. Otherwise proactive secret
    /// sharing is defeated — the refresh would be cosmetic, not protective.
    ///
    /// We model the attack: keep one old share, drop the rest, accept the
    /// refreshed shares as legitimate, then attempt to sign a quorum from
    /// the union. The protocol either fails outright or produces a
    /// signature that does NOT verify against the group pubkey.
    #[test]
    fn test_mixed_old_and_new_shares_cannot_produce_valid_signature() {
        use bitcoin::secp256k1::{Message, Secp256k1, XOnlyPublicKey};

        let config = ThresholdConfig::two_of_three();
        let dealer = TrustedDealer::new(config);
        let (mut old_shares, _) = dealer.generate("test-mixed").unwrap();
        let group_pubkey = *old_shares[0].group_pubkey();

        let (mut new_shares, _) = refresh_shares(&old_shares).unwrap();

        // BIP-340 schnorr signs a 32-byte message digest, and
        // `sign_with_local_shares` passes the bytes verbatim to FROST's
        // SigningPackage. Use a 32-byte digest as the message so the
        // signer and verifier agree on what was signed.
        let message_digest: [u8; 32] = {
            use sha2::Digest;
            sha2::Sha256::digest(b"attack: mix pre-refresh and post-refresh shares").into()
        };
        let message = message_digest.as_slice();

        let secp = Secp256k1::verification_only();
        let xonly = XOnlyPublicKey::from_slice(&group_pubkey)
            .expect("group pubkey is a valid x-only point");
        let msg = Message::from_digest(message_digest);

        // Control FIRST: 2 NEW shares MUST produce a valid signature
        // against the group pubkey. Proves the refresh is healthy so
        // the mixed-failure below is genuinely the security property,
        // not a setup bug. Drain the first two new shares to avoid
        // SharePackage's no-Clone constraint.
        let new_share_a = new_shares.remove(0);
        let new_share_b = new_shares.remove(0);
        let new_quorum = [new_share_a, new_share_b];
        let good_sig = sign_with_local_shares(&new_quorum, message)
            .expect("two fresh shares must produce a valid signature");
        let bip340 = bitcoin::secp256k1::schnorr::Signature::from_slice(&good_sig)
            .expect("64-byte schnorr signature");
        secp.verify_schnorr(&bip340, &msg, &xonly)
            .expect("control: two-of-three new shares MUST verify against the group pubkey");

        // Now the attack: pull one OLD share and pair it with one
        // surviving NEW share. Models a partially-compromised group
        // where the attacker still holds one old share post-refresh.
        let old_share_1 = old_shares.remove(0);
        let surviving_new_share = new_shares.remove(0); // was original index 2
        let mixed = [old_share_1, surviving_new_share];

        // The protocol either errors out OR produces a signature that
        // fails verification. Either outcome upholds the security
        // property; pin both.
        match sign_with_local_shares(&mixed, message) {
            Ok(sig) => {
                let bip340 = bitcoin::secp256k1::schnorr::Signature::from_slice(&sig)
                    .expect("64-byte schnorr signature");
                let verified = secp.verify_schnorr(&bip340, &msg, &xonly).is_ok();
                assert!(
                    !verified,
                    "SECURITY VIOLATION: mixed old+new shares produced a signature \
                     that verifies against the group pubkey. Refresh did not actually \
                     rotate the shares."
                );
            }
            Err(_) => {
                // This is the EXPECTED path in normal operation: FROST's
                // `aggregate` verifies the signature internally and rejects
                // the cross-epoch mix before it ever returns bytes. The Ok
                // arm above is the regression tripwire for a cosmetic refresh,
                // so do not collapse this match to `unwrap_err()` even though
                // the Ok branch looks unreachable today.
            }
        }
    }
}