Skip to main content

keep_core/frost/
transport.rs

1// SPDX-FileCopyrightText: © 2026 PrivKey LLC
2// SPDX-License-Identifier: MIT
3
4//! Transport formats for FROST shares and messages.
5use bech32::{Bech32m, Hrp};
6use serde::{Deserialize, Serialize};
7
8use crate::crypto;
9use crate::error::{KeepError, Result};
10
11use super::share::{Ciphersuite, SharePackage};
12
13const SHARE_HRP: &str = "kshare";
14const MAX_FRAME_COUNT: usize = 100;
15const MAX_ASSEMBLED_SIZE: usize = 64 * 1024;
16
17/// An encrypted share export for backup and transfer.
18#[derive(Serialize, Deserialize)]
19pub struct ShareExport {
20    /// Format version.
21    pub version: u8,
22    /// Threshold required to sign.
23    pub threshold: u16,
24    /// Total number of shares.
25    pub total: u16,
26    /// Share identifier.
27    pub identifier: u16,
28    /// Group public key (hex).
29    pub group_pubkey: String,
30    /// Encrypted share data (hex).
31    pub encrypted_share: String,
32    /// Encryption nonce (hex).
33    pub nonce: String,
34    /// Key derivation salt (hex).
35    pub salt: String,
36    /// FROST ciphersuite of this share.
37    ///
38    /// Defaults to `Secp256k1Tr` so exports written before this field existed
39    /// parse unchanged. Authenticated via the AEAD associated data of
40    /// `encrypted_share`, so it cannot be flipped without decryption failure.
41    #[serde(default)]
42    pub ciphersuite: Ciphersuite,
43}
44
45impl ShareExport {
46    /// Create an encrypted secp256k1 export from a share package.
47    pub fn from_share(share: &SharePackage, passphrase: &str) -> Result<Self> {
48        Self::from_share_with_ciphersuite(share, Ciphersuite::Secp256k1Tr, passphrase)
49    }
50
51    /// Create an encrypted export from a share package, binding the ciphersuite.
52    pub fn from_share_with_ciphersuite(
53        share: &SharePackage,
54        ciphersuite: Ciphersuite,
55        passphrase: &str,
56    ) -> Result<Self> {
57        let salt: [u8; 32] = crypto::try_random_bytes()?;
58        let key = crypto::derive_key(passphrase.as_bytes(), &salt, crypto::Argon2Params::DEFAULT)?;
59
60        let key_bytes = share.key_package_bytes().to_vec();
61
62        let encrypted = crypto::encrypt_with_aad(&key_bytes, ciphersuite.aad(), &key)?;
63
64        Ok(Self {
65            version: 1,
66            threshold: share.metadata.threshold,
67            total: share.metadata.total_shares,
68            identifier: share.metadata.identifier,
69            group_pubkey: hex::encode(share.metadata.group_pubkey),
70            encrypted_share: hex::encode(&encrypted.ciphertext),
71            nonce: hex::encode(encrypted.nonce),
72            salt: hex::encode(salt),
73            ciphersuite,
74        })
75    }
76
77    /// Decrypt and restore the share package.
78    pub fn to_share(&self, passphrase: &str, name: &str) -> Result<SharePackage> {
79        const INVALID_SHARE: &str = "Invalid or corrupted share data";
80
81        if self.version != 1 {
82            return Err(KeepError::Frost(format!(
83                "Unsupported version: {}",
84                self.version
85            )));
86        }
87
88        let salt_bytes =
89            hex::decode(&self.salt).map_err(|_| KeepError::Frost(INVALID_SHARE.into()))?;
90        if salt_bytes.len() != 32 {
91            return Err(KeepError::Frost(INVALID_SHARE.into()));
92        }
93        let mut salt = [0u8; 32];
94        salt.copy_from_slice(&salt_bytes);
95
96        let key = crypto::derive_key(passphrase.as_bytes(), &salt, crypto::Argon2Params::DEFAULT)?;
97
98        let nonce_bytes =
99            hex::decode(&self.nonce).map_err(|_| KeepError::Frost(INVALID_SHARE.into()))?;
100        if nonce_bytes.len() != 24 {
101            return Err(KeepError::Frost(INVALID_SHARE.into()));
102        }
103        let mut nonce = [0u8; 24];
104        nonce.copy_from_slice(&nonce_bytes);
105
106        let ciphertext = hex::decode(&self.encrypted_share)
107            .map_err(|_| KeepError::Frost(INVALID_SHARE.into()))?;
108
109        let encrypted = crypto::EncryptedData { ciphertext, nonce };
110        let decrypted = crypto::decrypt_with_aad(&encrypted, self.ciphersuite.aad(), &key)?;
111        let key_bytes = decrypted.as_slice()?;
112
113        let group_pubkey_bytes =
114            hex::decode(&self.group_pubkey).map_err(|_| KeepError::Frost(INVALID_SHARE.into()))?;
115        if group_pubkey_bytes.len() != 32 {
116            return Err(KeepError::Frost(INVALID_SHARE.into()));
117        }
118        let mut group_pubkey = [0u8; 32];
119        group_pubkey.copy_from_slice(&group_pubkey_bytes);
120
121        let metadata = super::share::ShareMetadata::new(
122            self.identifier,
123            self.threshold,
124            self.total,
125            group_pubkey,
126            name.to_string(),
127        );
128
129        match self.ciphersuite {
130            Ciphersuite::Secp256k1Tr => {
131                let key_package = frost_secp256k1_tr::keys::KeyPackage::deserialize(&key_bytes)
132                    .map_err(|e| {
133                        KeepError::Frost(format!("Failed to deserialize key package: {e}"))
134                    })?;
135                let pubkey_package = derive_pubkey_package(&key_package)?;
136                SharePackage::new(metadata, &key_package, &pubkey_package)
137            }
138            Ciphersuite::Ed25519 => import_ed25519_share(metadata, &key_bytes),
139        }
140    }
141
142    /// Serialize to JSON.
143    ///
144    /// # Errors
145    ///
146    /// Returns an error if serialization fails.
147    pub fn to_json(&self) -> Result<String> {
148        serde_json::to_string(self)
149            .map_err(|e| KeepError::Frost(format!("JSON serialization failed: {e}")))
150    }
151
152    /// Deserialize from JSON.
153    pub fn from_json(json: &str) -> Result<Self> {
154        serde_json::from_str(json)
155            .map_err(|e| KeepError::Frost(format!("JSON deserialization failed: {e}")))
156    }
157
158    /// Parse from either bech32 or JSON format, auto-detecting based on prefix.
159    pub fn parse(input: &str) -> Result<Self> {
160        let input = input.trim();
161        let is_bech32 = input
162            .find('1')
163            .map(|sep| input[..sep].eq_ignore_ascii_case(SHARE_HRP))
164            .unwrap_or(false);
165        if is_bech32 {
166            Self::from_bech32(input)
167        } else {
168            Self::from_json(input)
169        }
170    }
171
172    /// Encode as a bech32 string with `kshare` prefix.
173    pub fn to_bech32(&self) -> Result<String> {
174        let json = self.to_json()?;
175        let hrp =
176            Hrp::parse(SHARE_HRP).map_err(|e| KeepError::Frost(format!("Invalid HRP: {e}")))?;
177        bech32::encode::<Bech32m>(hrp, json.as_bytes())
178            .map_err(|e| KeepError::Frost(format!("Bech32 encoding failed: {e}")))
179    }
180
181    /// Decode from a bech32 string.
182    pub fn from_bech32(encoded: &str) -> Result<Self> {
183        let (hrp, data) = bech32::decode(encoded)
184            .map_err(|e| KeepError::Frost(format!("Bech32 decoding failed: {e}")))?;
185
186        if !hrp.as_str().eq_ignore_ascii_case(SHARE_HRP) {
187            return Err(KeepError::Frost(format!(
188                "Invalid prefix: expected {}, got {}",
189                SHARE_HRP,
190                hrp.as_str()
191            )));
192        }
193
194        let json = String::from_utf8(data)
195            .map_err(|_| KeepError::Frost("Invalid UTF-8 in share".into()))?;
196
197        Self::from_json(&json)
198    }
199}
200
201#[cfg(feature = "ed25519")]
202fn import_ed25519_share(
203    metadata: super::share::ShareMetadata,
204    key_bytes: &[u8],
205) -> Result<SharePackage> {
206    use frost_ed25519 as frost;
207    use std::collections::BTreeMap;
208
209    let key_package = frost::keys::KeyPackage::deserialize(key_bytes)
210        .map_err(|e| KeepError::Frost(format!("Failed to deserialize key package: {e}")))?;
211
212    let mut verifying_shares = BTreeMap::new();
213    verifying_shares.insert(*key_package.identifier(), *key_package.verifying_share());
214    let pubkey_package = frost::keys::PublicKeyPackage::new(
215        verifying_shares,
216        *key_package.verifying_key(),
217        Some(*key_package.min_signers()),
218    );
219
220    let key_package_bytes = key_package
221        .serialize()
222        .map_err(|e| KeepError::Frost(format!("Failed to serialize key package: {e}")))?;
223    let pubkey_package_bytes = pubkey_package
224        .serialize()
225        .map_err(|e| KeepError::Frost(format!("Failed to serialize pubkey package: {e}")))?;
226
227    Ok(SharePackage::from_bytes(
228        metadata,
229        key_package_bytes,
230        pubkey_package_bytes,
231    ))
232}
233
234#[cfg(not(feature = "ed25519"))]
235fn import_ed25519_share(
236    _metadata: super::share::ShareMetadata,
237    _key_bytes: &[u8],
238) -> Result<SharePackage> {
239    Err(KeepError::Frost(
240        "Ed25519 share import requires the ed25519 feature".into(),
241    ))
242}
243
244fn derive_pubkey_package(
245    key_package: &frost_secp256k1_tr::keys::KeyPackage,
246) -> Result<frost_secp256k1_tr::keys::PublicKeyPackage> {
247    use frost_secp256k1_tr::keys::PublicKeyPackage;
248    use std::collections::BTreeMap;
249
250    let verifying_share = key_package.verifying_share();
251    let verifying_key = key_package.verifying_key();
252
253    let mut verifying_shares = BTreeMap::new();
254    verifying_shares.insert(*key_package.identifier(), *verifying_share);
255
256    Ok(PublicKeyPackage::new(
257        verifying_shares,
258        *verifying_key,
259        Some(*key_package.min_signers()),
260    ))
261}
262
263/// A FROST protocol message for network transport.
264#[derive(Serialize, Deserialize)]
265pub struct FrostMessage {
266    /// Message type (commitment or share).
267    #[serde(rename = "type")]
268    pub msg_type: FrostMessageType,
269    /// Session identifier (hex).
270    pub session_id: String,
271    /// Participant identifier.
272    pub identifier: u16,
273    /// Message payload (hex).
274    pub payload: String,
275}
276
277/// Type of FROST protocol message.
278#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
279#[serde(rename_all = "snake_case")]
280pub enum FrostMessageType {
281    /// Round 1 commitment.
282    Round1Commitment,
283    /// Round 2 signature share.
284    Round2Share,
285}
286
287impl FrostMessage {
288    /// Create a round 1 commitment message.
289    pub fn commitment(session_id: &[u8; 32], identifier: u16, commitment_bytes: &[u8]) -> Self {
290        Self {
291            msg_type: FrostMessageType::Round1Commitment,
292            session_id: hex::encode(session_id),
293            identifier,
294            payload: hex::encode(commitment_bytes),
295        }
296    }
297
298    /// Create a round 2 signature share message.
299    pub fn signature_share(session_id: &[u8; 32], identifier: u16, share_bytes: &[u8]) -> Self {
300        Self {
301            msg_type: FrostMessageType::Round2Share,
302            session_id: hex::encode(session_id),
303            identifier,
304            payload: hex::encode(share_bytes),
305        }
306    }
307
308    /// Serialize to JSON.
309    pub fn to_json(&self) -> Result<String> {
310        serde_json::to_string(self)
311            .map_err(|e| KeepError::Frost(format!("JSON encode failed: {e}")))
312    }
313
314    /// Deserialize from JSON.
315    pub fn from_json(json: &str) -> Result<Self> {
316        serde_json::from_str(json).map_err(|e| KeepError::Frost(format!("JSON decode failed: {e}")))
317    }
318
319    /// Decode the payload from hex.
320    pub fn payload_bytes(&self) -> Result<Vec<u8>> {
321        hex::decode(&self.payload).map_err(|_| KeepError::Frost("Invalid payload hex".into()))
322    }
323
324    /// Decode the session ID from hex.
325    pub fn session_id_bytes(&self) -> Result<[u8; 32]> {
326        let bytes = hex::decode(&self.session_id)
327            .map_err(|_| KeepError::Frost("Invalid session_id hex".into()))?;
328        if bytes.len() != 32 {
329            return Err(KeepError::Frost("Invalid session_id length".into()));
330        }
331        let mut arr = [0u8; 32];
332        arr.copy_from_slice(&bytes);
333        Ok(arr)
334    }
335}
336
337impl ShareExport {
338    /// Split into animated QR code frames.
339    pub fn to_animated_frames(&self, max_bytes: usize) -> Result<Vec<String>> {
340        let full = self.to_json()?;
341
342        if full.len() <= max_bytes {
343            return Ok(vec![full]);
344        }
345
346        let total_frames = full.len().div_ceil(max_bytes);
347        let frames: Vec<String> = full
348            .as_bytes()
349            .chunks(max_bytes)
350            .enumerate()
351            .map(|(i, chunk)| {
352                let chunk_hex = hex::encode(chunk);
353                format!("{{\"f\":{i},\"t\":{total_frames},\"d\":\"{chunk_hex}\"}}")
354            })
355            .collect();
356
357        Ok(frames)
358    }
359
360    /// Reassemble from animated QR code frames.
361    pub fn from_animated_frames(frames: &[String]) -> Result<Self> {
362        if frames.is_empty() {
363            return Err(KeepError::Frost("No frames provided".into()));
364        }
365
366        if frames.len() > MAX_FRAME_COUNT {
367            return Err(KeepError::Frost("Too many frames".into()));
368        }
369
370        if frames.len() == 1 {
371            if let Ok(export) = Self::from_json(&frames[0]) {
372                return Ok(export);
373            }
374        }
375
376        let mut sorted: Vec<(usize, Vec<u8>)> = Vec::new();
377        let mut total_size = 0usize;
378        let mut seen_indices = std::collections::HashSet::new();
379
380        for frame in frames {
381            let parsed: serde_json::Value = serde_json::from_str(frame)
382                .map_err(|e| KeepError::Frost(format!("Invalid frame JSON: {e}")))?;
383
384            let idx = parsed["f"]
385                .as_u64()
386                .ok_or_else(|| KeepError::Frost("Missing frame index".into()))?
387                as usize;
388
389            if idx >= MAX_FRAME_COUNT {
390                return Err(KeepError::Frost("Frame index out of range".into()));
391            }
392
393            if !seen_indices.insert(idx) {
394                return Err(KeepError::Frost("Duplicate frame index".into()));
395            }
396
397            let data_hex = parsed["d"]
398                .as_str()
399                .ok_or_else(|| KeepError::Frost("Missing frame data".into()))?;
400            let data = hex::decode(data_hex)
401                .map_err(|_| KeepError::Frost("Invalid frame data hex".into()))?;
402
403            total_size = total_size
404                .checked_add(data.len())
405                .ok_or_else(|| KeepError::Frost("Total size overflow".into()))?;
406
407            if total_size > MAX_ASSEMBLED_SIZE {
408                return Err(KeepError::Frost("Assembled data too large".into()));
409            }
410
411            sorted.push((idx, data));
412        }
413
414        sorted.sort_by_key(|(idx, _)| *idx);
415
416        let full_bytes: Vec<u8> = sorted.into_iter().flat_map(|(_, data)| data).collect();
417        let full_str = String::from_utf8(full_bytes)
418            .map_err(|_| KeepError::Frost("Invalid UTF-8 in assembled frames".into()))?;
419
420        Self::from_json(&full_str).or_else(|_| Self::from_bech32(&full_str))
421    }
422}
423
424#[cfg(test)]
425mod tests {
426    use super::*;
427    use crate::frost::{ThresholdConfig, TrustedDealer};
428
429    #[test]
430    fn test_share_export_roundtrip() {
431        let config = ThresholdConfig::two_of_three();
432        let dealer = TrustedDealer::new(config);
433        let (shares, _) = dealer.generate("test").unwrap();
434
435        let passphrase = "test passphrase";
436        let export = ShareExport::from_share(&shares[0], passphrase).unwrap();
437
438        let json = export.to_json().unwrap();
439        let reimported = ShareExport::from_json(&json).unwrap();
440        let share = reimported.to_share(passphrase, "imported").unwrap();
441
442        assert_eq!(share.metadata.threshold, shares[0].metadata.threshold);
443        assert_eq!(share.metadata.identifier, shares[0].metadata.identifier);
444        assert_eq!(share.group_pubkey(), shares[0].group_pubkey());
445    }
446
447    #[test]
448    fn test_bech32_roundtrip() {
449        let config = ThresholdConfig::two_of_three();
450        let dealer = TrustedDealer::new(config);
451        let (shares, _) = dealer.generate("test").unwrap();
452
453        let export = ShareExport::from_share(&shares[0], "pass").unwrap();
454        let encoded = export.to_bech32().unwrap();
455
456        assert!(encoded.starts_with(SHARE_HRP));
457
458        let decoded = ShareExport::from_bech32(&encoded).unwrap();
459        assert_eq!(decoded.identifier, export.identifier);
460        assert_eq!(decoded.threshold, export.threshold);
461    }
462
463    #[test]
464    fn test_wrong_passphrase_fails() {
465        let config = ThresholdConfig::two_of_three();
466        let dealer = TrustedDealer::new(config);
467        let (shares, _) = dealer.generate("test").unwrap();
468
469        let export = ShareExport::from_share(&shares[0], "correct").unwrap();
470        let result = export.to_share("wrong", "imported");
471
472        assert!(result.is_err());
473    }
474
475    #[test]
476    fn test_animated_frames_roundtrip() {
477        let config = ThresholdConfig::two_of_three();
478        let dealer = TrustedDealer::new(config);
479        let (shares, _) = dealer.generate("test").unwrap();
480
481        let export = ShareExport::from_share(&shares[0], "pass").unwrap();
482
483        let frames = export.to_animated_frames(100).unwrap();
484        assert!(frames.len() > 1);
485
486        let reconstructed = ShareExport::from_animated_frames(&frames).unwrap();
487        assert_eq!(reconstructed.identifier, export.identifier);
488        assert_eq!(reconstructed.threshold, export.threshold);
489        assert_eq!(reconstructed.group_pubkey, export.group_pubkey);
490    }
491
492    #[test]
493    fn test_animated_frames_single() {
494        let config = ThresholdConfig::two_of_three();
495        let dealer = TrustedDealer::new(config);
496        let (shares, _) = dealer.generate("test").unwrap();
497
498        let export = ShareExport::from_share(&shares[0], "pass").unwrap();
499
500        let frames = export.to_animated_frames(10000).unwrap();
501        assert_eq!(frames.len(), 1);
502
503        let reconstructed = ShareExport::from_animated_frames(&frames).unwrap();
504        assert_eq!(reconstructed.identifier, export.identifier);
505    }
506
507    #[test]
508    fn test_frost_message_roundtrip() {
509        let session_id = [42u8; 32];
510        let commitment_data = vec![1, 2, 3, 4, 5];
511
512        let msg = FrostMessage::commitment(&session_id, 1, &commitment_data);
513        assert_eq!(msg.msg_type, FrostMessageType::Round1Commitment);
514        assert_eq!(msg.identifier, 1);
515
516        let json = msg.to_json().unwrap();
517        let parsed = FrostMessage::from_json(&json).unwrap();
518
519        assert_eq!(parsed.msg_type, FrostMessageType::Round1Commitment);
520        assert_eq!(parsed.identifier, 1);
521        assert_eq!(parsed.payload_bytes().unwrap(), commitment_data);
522        assert_eq!(parsed.session_id_bytes().unwrap(), session_id);
523    }
524
525    #[cfg(feature = "ed25519")]
526    #[test]
527    fn test_ed25519_share_export_roundtrip() {
528        use crate::frost::ed25519::TrustedDealer as Ed25519Dealer;
529
530        let dealer = Ed25519Dealer::new(ThresholdConfig::two_of_three());
531        let (shares, _) = dealer.generate("ed-test").unwrap();
532
533        let passphrase = "ed pass";
534        let export =
535            ShareExport::from_share_with_ciphersuite(&shares[0], Ciphersuite::Ed25519, passphrase)
536                .unwrap();
537        assert_eq!(export.ciphersuite, Ciphersuite::Ed25519);
538
539        let json = export.to_json().unwrap();
540        let reimported = ShareExport::from_json(&json).unwrap();
541        let restored = reimported.to_share(passphrase, "imported").unwrap();
542
543        assert_eq!(restored.group_pubkey(), shares[0].group_pubkey());
544        assert_eq!(restored.key_package_bytes(), shares[0].key_package_bytes());
545    }
546
547    #[test]
548    fn test_frost_message_signature_share() {
549        let session_id = [99u8; 32];
550        let share_data = vec![10, 20, 30];
551
552        let msg = FrostMessage::signature_share(&session_id, 2, &share_data);
553        assert_eq!(msg.msg_type, FrostMessageType::Round2Share);
554        assert_eq!(msg.identifier, 2);
555
556        let json = msg.to_json().unwrap();
557        assert!(json.contains("round2_share"));
558    }
559
560    // === #440: FrostMessage rejection coverage for interactive sign ===
561
562    /// `FrostMessage::from_json` is the parse boundary the interactive
563    /// signer pastes into. Malformed input MUST surface a clean error
564    /// rather than panic. Pin three classes: complete garbage, valid JSON
565    /// with wrong shape, and an empty string.
566    #[test]
567    fn test_frost_message_from_json_rejects_malformed_input() {
568        assert!(FrostMessage::from_json("not-json").is_err());
569        assert!(FrostMessage::from_json("").is_err());
570        // Valid JSON but missing required fields:
571        assert!(FrostMessage::from_json(r#"{"foo": "bar"}"#).is_err());
572    }
573
574    /// The interactive signer compares the parsed `session_id` hex against
575    /// its own session digest to defend against cross-session reuse. The
576    /// `session_id_bytes()` accessor MUST refuse hex that doesn't decode
577    /// to exactly 32 bytes, otherwise the gate could be bypassed by a
578    /// short prefix that happens to match.
579    #[test]
580    fn test_frost_message_session_id_bytes_rejects_wrong_length_hex() {
581        let session_id = [7u8; 32];
582        let payload = vec![1, 2, 3];
583        let mut msg = FrostMessage::commitment(&session_id, 1, &payload);
584
585        // 31-byte hex (62 chars): refused.
586        msg.session_id = "aa".repeat(31);
587        assert!(
588            msg.session_id_bytes().is_err(),
589            "31-byte session_id hex must be refused"
590        );
591
592        // 33-byte hex (66 chars): refused.
593        msg.session_id = "bb".repeat(33);
594        assert!(
595            msg.session_id_bytes().is_err(),
596            "33-byte session_id hex must be refused"
597        );
598
599        // Non-hex characters: refused.
600        msg.session_id = "z".repeat(64);
601        assert!(
602            msg.session_id_bytes().is_err(),
603            "non-hex session_id must be refused"
604        );
605
606        // Exactly 32 bytes (64 hex chars) of valid hex: accepted, and
607        // round-trips to the same bytes.
608        msg.session_id = "cc".repeat(32);
609        let bytes = msg.session_id_bytes().expect("32-byte hex must parse");
610        assert_eq!(bytes, [0xCCu8; 32]);
611    }
612}