Skip to main content

keep_core/frost/
share.rs

1// SPDX-FileCopyrightText: © 2026 PrivKey LLC
2// SPDX-License-Identifier: MIT
3
4//! FROST share types and encrypted storage.
5
6use frost_secp256k1_tr::{
7    keys::{KeyPackage, PublicKeyPackage},
8    Identifier,
9};
10use serde::{Deserialize, Serialize};
11use zeroize::{Zeroize, ZeroizeOnDrop};
12
13use crate::crypto::{self, SecretKey};
14use crate::error::{KeepError, Result};
15
16/// The FROST ciphersuite a share belongs to.
17///
18/// The discriminant is bound into the AEAD associated data when a share is
19/// encrypted (see [`StoredShare`]), so it cannot be flipped or stripped to force
20/// cross-ciphersuite confusion.
21#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
22#[serde(rename_all = "snake_case")]
23pub enum Ciphersuite {
24    /// FROST over secp256k1 with Taproot (BIP-340) — the Bitcoin/Nostr path.
25    #[default]
26    Secp256k1Tr,
27    /// FROST over Ed25519.
28    Ed25519,
29}
30
31impl Ciphersuite {
32    /// Associated data binding this ciphersuite into the share's AEAD envelope.
33    ///
34    /// `Secp256k1Tr` intentionally maps to an empty AAD so that shares written
35    /// before the ciphersuite tag existed (and the live Bitcoin path) remain
36    /// byte-identical and continue to decrypt.
37    pub(crate) fn aad(self) -> &'static [u8] {
38        match self {
39            Ciphersuite::Secp256k1Tr => &[],
40            Ciphersuite::Ed25519 => b"keep-frost-ciphersuite:ed25519",
41        }
42    }
43}
44
45/// Metadata for a FROST share.
46#[derive(Clone, Serialize, Deserialize)]
47pub struct ShareMetadata {
48    /// Share identifier (1-indexed).
49    pub identifier: u16,
50    /// Threshold required to sign.
51    pub threshold: u16,
52    /// Total number of shares.
53    pub total_shares: u16,
54    /// The group public key (x-only, 32 bytes).
55    pub group_pubkey: [u8; 32],
56    /// Human-readable name.
57    pub name: String,
58    /// Unix timestamp when created.
59    pub created_at: i64,
60    /// Unix timestamp of last use.
61    pub last_used: Option<i64>,
62    /// Number of signatures made.
63    pub sign_count: u64,
64    /// Whether this share has been backed up.
65    #[serde(default)]
66    pub did_backup: bool,
67}
68
69impl ShareMetadata {
70    /// Create new share metadata.
71    pub fn new(
72        identifier: u16,
73        threshold: u16,
74        total_shares: u16,
75        group_pubkey: [u8; 32],
76        name: String,
77    ) -> Self {
78        Self {
79            identifier,
80            threshold,
81            total_shares,
82            group_pubkey,
83            name,
84            created_at: chrono::Utc::now().timestamp(),
85            last_used: None,
86            sign_count: 0,
87            did_backup: false,
88        }
89    }
90
91    /// Record usage timestamp.
92    pub fn record_usage(&mut self) {
93        self.last_used = Some(chrono::Utc::now().timestamp());
94    }
95
96    /// Mark this share as backed up.
97    pub fn mark_backed_up(&mut self) {
98        self.did_backup = true;
99    }
100
101    /// Increment signature count and record usage.
102    pub fn increment_sign_count(&mut self) {
103        self.sign_count += 1;
104        self.record_usage();
105    }
106}
107
108/// A FROST key share with metadata.
109///
110/// Contains the secret key package (zeroized on drop) and public key package.
111#[derive(Zeroize, ZeroizeOnDrop)]
112pub struct SharePackage {
113    /// Share metadata.
114    #[zeroize(skip)]
115    pub metadata: ShareMetadata,
116    key_package_bytes: Vec<u8>,
117    #[zeroize(skip)]
118    pubkey_package_bytes: Vec<u8>,
119}
120
121impl SharePackage {
122    /// Create a new share package from FROST key packages.
123    pub fn new(
124        metadata: ShareMetadata,
125        key_package: &KeyPackage,
126        pubkey_package: &PublicKeyPackage,
127    ) -> Result<Self> {
128        let key_package_bytes = key_package
129            .serialize()
130            .map_err(|e| KeepError::Frost(format!("Failed to serialize key package: {e}")))?;
131
132        let pubkey_package_bytes = pubkey_package
133            .serialize()
134            .map_err(|e| KeepError::Frost(format!("Failed to serialize pubkey package: {e}")))?;
135
136        Ok(Self {
137            metadata,
138            key_package_bytes,
139            pubkey_package_bytes,
140        })
141    }
142
143    /// Create a share package from already-serialized package bytes.
144    ///
145    /// Used by ciphersuites whose package types are not the secp256k1 ones.
146    pub fn from_bytes(
147        metadata: ShareMetadata,
148        key_package_bytes: Vec<u8>,
149        pubkey_package_bytes: Vec<u8>,
150    ) -> Self {
151        Self {
152            metadata,
153            key_package_bytes,
154            pubkey_package_bytes,
155        }
156    }
157
158    /// The serialized key package bytes.
159    pub fn key_package_bytes(&self) -> &[u8] {
160        &self.key_package_bytes
161    }
162
163    /// The serialized public key package bytes.
164    pub fn pubkey_package_bytes(&self) -> &[u8] {
165        &self.pubkey_package_bytes
166    }
167
168    /// Deserialize and return the key package.
169    pub fn key_package(&self) -> Result<KeyPackage> {
170        KeyPackage::deserialize(&self.key_package_bytes)
171            .map_err(|e| KeepError::Frost(format!("Failed to deserialize key package: {e}")))
172    }
173
174    /// Deserialize and return the public key package.
175    pub fn pubkey_package(&self) -> Result<PublicKeyPackage> {
176        PublicKeyPackage::deserialize(&self.pubkey_package_bytes)
177            .map_err(|e| KeepError::Frost(format!("Failed to deserialize pubkey package: {e}")))
178    }
179
180    /// The FROST identifier for this share.
181    pub fn identifier(&self) -> Result<Identifier> {
182        let kp = self.key_package()?;
183        Ok(*kp.identifier())
184    }
185
186    /// The group public key.
187    pub fn group_pubkey(&self) -> &[u8; 32] {
188        &self.metadata.group_pubkey
189    }
190
191    /// The group public key read from the public-key package's verifying key,
192    /// as opposed to the separate `metadata.group_pubkey` field. Use this to
193    /// detect a share loaded from an untrusted store that belongs to a
194    /// *different* group (or is corrupted) than the key it was requested under.
195    ///
196    /// This compares the package's advertised verifying key, which is public
197    /// data and an independently-settable field, so it is NOT proof that the
198    /// share carries a valid secret for that group: a store could pair the
199    /// expected verifying key with junk key material. That case is caught later
200    /// at signing time (the partial signatures will not aggregate), not here.
201    pub fn verified_group_pubkey(&self) -> Result<[u8; 32]> {
202        super::dealer::extract_group_pubkey(&self.pubkey_package()?)
203    }
204}
205
206/// An encrypted share for persistent storage.
207#[derive(Clone, Serialize, Deserialize)]
208pub struct StoredShare {
209    /// Share metadata.
210    pub metadata: ShareMetadata,
211    /// Encrypted key package bytes.
212    pub encrypted_key_package: Vec<u8>,
213    /// Public key package bytes.
214    pub pubkey_package: Vec<u8>,
215    /// FROST ciphersuite of this share.
216    ///
217    /// Defaults to `Secp256k1Tr` so shares written before this field existed
218    /// load unchanged. The value is authenticated via the AEAD associated data
219    /// of `encrypted_key_package`, so it cannot be flipped without MAC failure.
220    #[serde(default)]
221    pub ciphersuite: Ciphersuite,
222}
223
224impl StoredShare {
225    /// Encrypt a secp256k1 share package for storage.
226    pub fn encrypt(share: &SharePackage, data_key: &SecretKey) -> Result<Self> {
227        Self::encrypt_with_ciphersuite(share, Ciphersuite::Secp256k1Tr, data_key)
228    }
229
230    /// Encrypt a share package for storage, binding the given ciphersuite.
231    pub fn encrypt_with_ciphersuite(
232        share: &SharePackage,
233        ciphersuite: Ciphersuite,
234        data_key: &SecretKey,
235    ) -> Result<Self> {
236        let encrypted =
237            crypto::encrypt_with_aad(&share.key_package_bytes, ciphersuite.aad(), data_key)?;
238
239        Ok(Self {
240            metadata: share.metadata.clone(),
241            encrypted_key_package: encrypted.to_bytes(),
242            pubkey_package: share.pubkey_package_bytes.clone(),
243            ciphersuite,
244        })
245    }
246
247    /// Decrypt and return the share package.
248    pub fn decrypt(&self, data_key: &SecretKey) -> Result<SharePackage> {
249        let encrypted = crypto::EncryptedData::from_bytes(&self.encrypted_key_package)?;
250        let decrypted = crypto::decrypt_with_aad(&encrypted, self.ciphersuite.aad(), data_key)?;
251        let key_package_bytes = decrypted.as_slice()?;
252
253        Ok(SharePackage {
254            metadata: self.metadata.clone(),
255            key_package_bytes: key_package_bytes.to_vec(),
256            pubkey_package_bytes: self.pubkey_package.clone(),
257        })
258    }
259}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264    use crate::crypto::SecretKey;
265    use serde::{Deserialize, Serialize};
266
267    fn sample_metadata() -> ShareMetadata {
268        ShareMetadata::new(1, 2, 3, [7u8; 32], "test".into())
269    }
270
271    fn sample_package() -> SharePackage {
272        SharePackage::from_bytes(sample_metadata(), vec![1, 2, 3, 4], vec![9, 9, 9])
273    }
274
275    #[test]
276    fn test_default_ciphersuite_is_secp256k1() {
277        assert_eq!(Ciphersuite::default(), Ciphersuite::Secp256k1Tr);
278        assert!(Ciphersuite::Secp256k1Tr.aad().is_empty());
279        assert!(!Ciphersuite::Ed25519.aad().is_empty());
280    }
281
282    #[test]
283    fn test_secp256k1_envelope_byte_identical() {
284        // The secp256k1 path uses empty AAD, so the ciphertext is byte-for-byte
285        // what plain `crypto::encrypt` would have produced for the same key+nonce.
286        let key = SecretKey::generate().unwrap();
287        let pkg = sample_package();
288
289        let stored = StoredShare::encrypt(&pkg, &key).unwrap();
290        assert_eq!(stored.ciphersuite, Ciphersuite::Secp256k1Tr);
291
292        let restored = stored.decrypt(&key).unwrap();
293        assert_eq!(restored.key_package_bytes(), pkg.key_package_bytes());
294
295        // A blob produced via the no-AAD primitive must also decrypt under the
296        // secp256k1 (empty-AAD) path, proving envelope compatibility.
297        let raw = crypto::encrypt(pkg.key_package_bytes(), &key).unwrap();
298        let legacy = StoredShare {
299            metadata: sample_metadata(),
300            encrypted_key_package: raw.to_bytes(),
301            pubkey_package: pkg.pubkey_package_bytes().to_vec(),
302            ciphersuite: Ciphersuite::Secp256k1Tr,
303        };
304        let restored = legacy.decrypt(&key).unwrap();
305        assert_eq!(restored.key_package_bytes(), pkg.key_package_bytes());
306    }
307
308    // Mirrors the pre-change StoredShare field layout (no ciphersuite tag).
309    #[derive(Serialize, Deserialize)]
310    struct LegacyStoredShare {
311        metadata: ShareMetadata,
312        encrypted_key_package: Vec<u8>,
313        pubkey_package: Vec<u8>,
314    }
315
316    #[test]
317    fn test_old_bincode_blob_is_not_self_describing() {
318        // Documents why the storage layer needs an explicit legacy fallback:
319        // bincode cannot fill a `#[serde(default)]` trailing field from an old
320        // blob that lacks it. The recovery path is tested in storage.rs.
321        use bincode::Options;
322
323        let legacy = LegacyStoredShare {
324            metadata: sample_metadata(),
325            encrypted_key_package: vec![0u8; 40],
326            pubkey_package: vec![9, 9, 9],
327        };
328
329        let opts = || {
330            bincode::options()
331                .with_fixint_encoding()
332                .allow_trailing_bytes()
333        };
334        let blob = opts().serialize(&legacy).unwrap();
335
336        assert!(opts().deserialize::<StoredShare>(&blob).is_err());
337    }
338
339    // Golden bytes from a real 2-of-3 secp256k1-tr group, captured in the pre-3.0
340    // on-disk layout (PublicKeyPackage serialized without the `min_signers` field
341    // that frost-core 3.0 appended). Hardcoded, not regenerated, so a future frost
342    // bump that changes the wire format fails this test instead of silently
343    // locking existing users out of shares written by the 2.2-era release.
344    const GOLDEN_GROUP_PUBKEY: &str =
345        "e29d92d6ce9b54080afc8e1b720092590a4a759224ef2dc8f99bbbdb13347a88";
346    const GOLDEN_PUBKEY_PACKAGE_LEGACY: &str = "00230f8ab3030000000000000000000000000000000000000000000000000000000000000001036800734597e8251af183d2ebe63d4e40e13aadb1fbc6a42b9355bf0e8687b9b9000000000000000000000000000000000000000000000000000000000000000203528367b7e2165da412e85b4dd5dc59f289ecbb2051d2e9f76ff3524b7ce10eab000000000000000000000000000000000000000000000000000000000000000303d408b25a61c86d4cd2c5d56a0e8d697ed81149852971469975dd36d64c5c215b03e29d92d6ce9b54080afc8e1b720092590a4a759224ef2dc8f99bbbdb13347a88";
347    const GOLDEN_KEY_PACKAGE_1: &str = "00230f8ab30000000000000000000000000000000000000000000000000000000000000001fb905abafb56780848f1404d19e7389ca53f838a52cd3d959ba015cbf1f30952036800734597e8251af183d2ebe63d4e40e13aadb1fbc6a42b9355bf0e8687b9b903e29d92d6ce9b54080afc8e1b720092590a4a759224ef2dc8f99bbbdb13347a8802";
348    const GOLDEN_KEY_PACKAGE_2: &str = "00230f8ab300000000000000000000000000000000000000000000000000000000000000020b9bd02ae54309f2459d2399a429b6675874a8a822566ec198cb218c2ddc8c2603528367b7e2165da412e85b4dd5dc59f289ecbb2051d2e9f76ff3524b7ce10eab03e29d92d6ce9b54080afc8e1b720092590a4a759224ef2dc8f99bbbdb13347a8802";
349
350    #[test]
351    fn verified_group_pubkey_derives_from_package_not_metadata() {
352        let real: [u8; 32] = hex::decode(GOLDEN_GROUP_PUBKEY)
353            .unwrap()
354            .try_into()
355            .unwrap();
356        let pubkey_bytes = hex::decode(GOLDEN_PUBKEY_PACKAGE_LEGACY).unwrap();
357        // Forge the metadata to claim a different group than the package really is.
358        let forged = [0xAAu8; 32];
359        let metadata = ShareMetadata::new(1, 2, 3, forged, "forged".into());
360        let share = SharePackage::from_bytes(
361            metadata,
362            hex::decode(GOLDEN_KEY_PACKAGE_1).unwrap(),
363            pubkey_bytes,
364        );
365        // The plain metadata field reflects the forgery...
366        assert_eq!(share.group_pubkey(), &forged);
367        // ...but the cryptographic identity is the real group key, so an untrusted
368        // store cannot pass off one share as another by rewriting the metadata.
369        assert_eq!(share.verified_group_pubkey().unwrap(), real);
370    }
371
372    #[test]
373    fn test_legacy_format_share_deserializes_and_signs() {
374        use crate::frost::sign_with_local_shares;
375        use bitcoin::secp256k1::{schnorr, Message, Secp256k1, XOnlyPublicKey};
376
377        let group_pubkey: [u8; 32] = hex::decode(GOLDEN_GROUP_PUBKEY)
378            .unwrap()
379            .try_into()
380            .unwrap();
381        let pubkey_bytes = hex::decode(GOLDEN_PUBKEY_PACKAGE_LEGACY).unwrap();
382
383        let build = |id: u16, kp_hex: &str| {
384            let metadata = ShareMetadata::new(id, 2, 3, group_pubkey, "golden".into());
385            SharePackage::from_bytes(metadata, hex::decode(kp_hex).unwrap(), pubkey_bytes.clone())
386        };
387        let shares = [
388            build(1, GOLDEN_KEY_PACKAGE_1),
389            build(2, GOLDEN_KEY_PACKAGE_2),
390        ];
391
392        // The legacy buffer decodes via frost-core's pre-3.0 compatibility path
393        // and reports min_signers = None.
394        assert!(shares[0].pubkey_package().unwrap().min_signers().is_none());
395        assert!(shares[0].key_package().is_ok());
396
397        // A real BIP-340 signature from the legacy shares still verifies against
398        // the group key, so an upgraded user can still spend.
399        let digest: [u8; 32] = {
400            use sha2::Digest;
401            sha2::Sha256::digest(b"legacy share must still sign under frost 3.0").into()
402        };
403        let sig = sign_with_local_shares(&shares, &digest).unwrap();
404        let secp = Secp256k1::verification_only();
405        let xonly = XOnlyPublicKey::from_slice(&group_pubkey).unwrap();
406        secp.verify_schnorr(
407            &schnorr::Signature::from_slice(&sig).unwrap(),
408            &Message::from_digest(digest),
409            &xonly,
410        )
411        .expect("legacy-format share must produce a valid signature under frost 3.0");
412    }
413}