keep_core/frost/
dealer.rs1use frost::keys::{IdentifierList, KeyPackage, PublicKeyPackage};
6use frost::rand_core::OsRng;
7use frost_secp256k1_tr as frost;
8
9use crate::error::{KeepError, Result};
10
11use super::share::{ShareMetadata, SharePackage};
12
13#[derive(Clone, Copy)]
15pub struct ThresholdConfig {
16 pub threshold: u16,
18 pub total_shares: u16,
20}
21
22impl ThresholdConfig {
23 pub fn new(threshold: u16, total_shares: u16) -> Result<Self> {
27 if threshold < 2 {
28 return Err(KeepError::Frost("Threshold must be at least 2".into()));
29 }
30 if total_shares < threshold {
31 return Err(KeepError::Frost("Total shares must be >= threshold".into()));
32 }
33 if total_shares > 255 {
34 return Err(KeepError::Frost("Maximum 255 shares supported".into()));
35 }
36
37 Ok(Self {
38 threshold,
39 total_shares,
40 })
41 }
42
43 pub fn two_of_three() -> Self {
45 Self {
46 threshold: 2,
47 total_shares: 3,
48 }
49 }
50
51 pub fn three_of_five() -> Self {
53 Self {
54 threshold: 3,
55 total_shares: 5,
56 }
57 }
58}
59
60pub struct TrustedDealer {
70 config: ThresholdConfig,
71}
72
73impl TrustedDealer {
74 pub fn new(config: ThresholdConfig) -> Self {
76 Self { config }
77 }
78
79 pub fn generate(&self, name: &str) -> Result<(Vec<SharePackage>, PublicKeyPackage)> {
83 let (shares, pubkey_pkg) = frost::keys::generate_with_dealer(
84 self.config.total_shares,
85 self.config.threshold,
86 IdentifierList::Default,
87 OsRng,
88 )
89 .map_err(|e| KeepError::Frost(format!("Key generation failed: {e}")))?;
90
91 let group_pubkey = extract_group_pubkey(&pubkey_pkg)?;
92
93 let packages: Result<Vec<SharePackage>> = shares
94 .into_iter()
95 .enumerate()
96 .map(|(idx, (_, secret_share))| {
97 let key_package = KeyPackage::try_from(secret_share)
98 .map_err(|e| KeepError::Frost(format!("KeyPackage conversion failed: {e}")))?;
99
100 let identifier = (idx + 1) as u16;
101
102 let metadata = ShareMetadata::new(
103 identifier,
104 self.config.threshold,
105 self.config.total_shares,
106 group_pubkey,
107 name.to_string(),
108 );
109
110 SharePackage::new(metadata, &key_package, &pubkey_pkg)
111 })
112 .collect();
113
114 Ok((packages?, pubkey_pkg))
115 }
116
117 pub fn split_existing(
119 &self,
120 secret: &[u8; 32],
121 name: &str,
122 ) -> Result<(Vec<SharePackage>, PublicKeyPackage)> {
123 let signing_key = frost::SigningKey::deserialize(secret)
124 .map_err(|e| KeepError::Frost(format!("Invalid signing key: {e}")))?;
125
126 let (shares, pubkey_pkg) = frost::keys::split(
127 &signing_key,
128 self.config.total_shares,
129 self.config.threshold,
130 IdentifierList::Default,
131 &mut OsRng,
132 )
133 .map_err(|e| KeepError::Frost(format!("Key split failed: {e}")))?;
134
135 let group_pubkey = extract_group_pubkey(&pubkey_pkg)?;
136
137 let packages: Result<Vec<SharePackage>> = shares
138 .into_iter()
139 .enumerate()
140 .map(|(idx, (_, secret_share))| {
141 let key_package = KeyPackage::try_from(secret_share)
142 .map_err(|e| KeepError::Frost(format!("KeyPackage conversion failed: {e}")))?;
143
144 let identifier = (idx + 1) as u16;
145
146 let metadata = ShareMetadata::new(
147 identifier,
148 self.config.threshold,
149 self.config.total_shares,
150 group_pubkey,
151 name.to_string(),
152 );
153
154 SharePackage::new(metadata, &key_package, &pubkey_pkg)
155 })
156 .collect();
157
158 Ok((packages?, pubkey_pkg))
159 }
160}
161
162pub(super) fn extract_group_pubkey(pubkey_pkg: &PublicKeyPackage) -> Result<[u8; 32]> {
163 let verifying_key = pubkey_pkg.verifying_key();
164 let serialized = verifying_key
165 .serialize()
166 .map_err(|e| KeepError::Frost(format!("Failed to serialize verifying key: {e}")))?;
167 let bytes = serialized.as_slice();
168
169 let mut pubkey = [0u8; 32];
170 if bytes.len() == 33 {
171 pubkey.copy_from_slice(&bytes[1..33]);
172 } else if bytes.len() == 32 {
173 pubkey.copy_from_slice(&bytes[0..32]);
174 } else {
175 return Err(KeepError::Frost(format!(
176 "Invalid group pubkey length: expected 32 or 33, got {}",
177 bytes.len()
178 )));
179 }
180 Ok(pubkey)
181}
182
183#[cfg(test)]
184mod tests {
185 use super::*;
186
187 #[test]
188 fn test_generate_two_of_three() {
189 let config = ThresholdConfig::two_of_three();
190 let dealer = TrustedDealer::new(config);
191 let (shares, pubkey_pkg) = dealer.generate("test").unwrap();
192
193 assert_eq!(shares.len(), 3);
194 for share in &shares {
195 assert_eq!(share.metadata.threshold, 2);
196 assert_eq!(share.metadata.total_shares, 3);
197 assert_eq!(share.group_pubkey(), shares[0].group_pubkey());
198 }
199
200 let vk = pubkey_pkg.verifying_key();
201 let vk_bytes = vk.serialize().unwrap();
202 assert_eq!(vk_bytes.as_slice().len(), 33);
203 }
204
205 #[test]
206 fn test_split_preserves_pubkey() {
207 use crate::crypto::random_bytes;
208
209 let secret: [u8; 32] = random_bytes();
210 let config = ThresholdConfig::two_of_three();
211 let dealer = TrustedDealer::new(config);
212
213 let (shares, pubkey_pkg) = dealer.split_existing(&secret, "split").unwrap();
214
215 let expected_pubkey = pubkey_pkg.verifying_key().serialize().unwrap();
216 let expected_slice = expected_pubkey.as_slice();
217 assert_eq!(expected_slice.len(), 33);
218
219 let mut expected_bytes = [0u8; 32];
220 expected_bytes.copy_from_slice(&expected_slice[1..33]);
221
222 assert_eq!(shares[0].group_pubkey(), &expected_bytes);
223 }
224
225 #[test]
226 fn test_invalid_config() {
227 assert!(ThresholdConfig::new(1, 3).is_err());
228 assert!(ThresholdConfig::new(3, 2).is_err());
229 assert!(ThresholdConfig::new(2, 256).is_err());
230 }
231}