1use super::*;
2
3#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
5pub enum NoiseMechanism {
6 Laplace,
7 Gaussian,
8 Exponential,
9 Geometric,
10 Custom(String),
11}
12
13pub struct PrivacyAccountant {
15 pub total_epsilon_spent: f64,
16 pub total_delta_spent: f64,
17 pub composition_method: CompositionMethod,
18 pub remaining_budget: PrivacyBudget,
19}
20
21#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
23pub enum CompositionMethod {
24 BasicComposition,
25 AdvancedComposition,
26 RDPComposition,
27 GaussianDP,
28 Custom(String),
29}
30
31#[derive(Debug, Clone)]
33pub struct SensitivityFunction {
34 pub function_id: String,
35 pub sensitivity: f64,
36 pub computation_method: SensitivityMethod,
37}
38
39#[derive(Debug, Clone, PartialEq)]
41pub enum SensitivityMethod {
42 Global,
43 Local,
44 Smooth,
45 Approximate,
46}
47
48pub struct SecureAggregation {
50 aggregation_protocols: Vec<AggregationProtocol>,
51 encryption_schemes: Vec<EncryptionScheme>,
52 integrity_checks: Vec<IntegrityCheck>,
53}
54
55#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
57pub enum AggregationProtocol {
58 SecureSum,
59 SecureMean,
60 SecureMin,
61 SecureMax,
62 SecureMedian,
63 Custom(String),
64}
65
66#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
68pub enum EncryptionScheme {
69 Homomorphic,
70 SecretSharing,
71 Threshold,
72 Oblivious,
73 Custom(String),
74}
75
76#[derive(Debug, Clone)]
78pub struct IntegrityCheck {
79 pub check_id: String,
80 pub check_type: IntegrityCheckType,
81 pub verification_method: VerificationMethod,
82}
83
84#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
86pub enum IntegrityCheckType {
87 Hash,
88 MAC,
89 DigitalSignature,
90 ZeroKnowledge,
91}
92
93#[derive(Debug, Clone, PartialEq)]
95pub enum VerificationMethod {
96 Deterministic,
97 Probabilistic,
98 Interactive,
99 NonInteractive,
100}
101
102pub struct PrivacyBudget {
104 pub epsilon: f64,
105 pub delta: f64,
106 pub remaining_epsilon: f64,
107 pub remaining_delta: f64,
108 pub budget_period: u64,
109 pub last_reset: u64,
110}
111
112impl StatisticalPrivacyEngine {
113 pub fn new() -> Self {
115 Self {
116 fiduciary_crypto: Arc::new(Mutex::new(FiduciaryCrypto::new())),
117 zk_proofs: Arc::new(Mutex::new(ZkProofSystem::new())),
118 differential_privacy: DifferentialPrivacy::new(),
119 secure_aggregation: SecureAggregation::new(),
120 privacy_budget: PrivacyBudget {
121 epsilon: 1.0,
122 delta: 1e-6,
123 remaining_epsilon: 1.0,
124 remaining_delta: 1e-6,
125 budget_period: 86400, last_reset: 0,
127 },
128 }
129 }
130
131 pub fn initialize(&mut self) -> Result<(), StatisticalError> {
133 self.differential_privacy.initialize()?;
134 self.secure_aggregation.initialize()?;
135 Ok(())
136 }
137
138 pub fn add_laplace_noise(
140 &mut self,
141 value: f64,
142 sensitivity: f64,
143 ) -> Result<(f64, f64), StatisticalError> {
144 let epsilon = 1.0;
145 let scale = sensitivity / epsilon;
146
147 let noise = self.generate_laplace_noise(scale)?;
148 let noisy_value = value + noise;
149
150 self.privacy_budget.remaining_epsilon -= epsilon;
152
153 Ok((noisy_value, epsilon))
154 }
155
156 pub fn add_histogram_noise(
158 &mut self,
159 counts: &[u32],
160 ) -> Result<(Vec<u32>, f64), StatisticalError> {
161 let epsilon = 1.0;
162 let sensitivity = 1.0;
163 let scale = sensitivity / epsilon;
164
165 let mut noisy_counts = Vec::with_capacity(counts.len());
166 for &count in counts {
167 let noise = self.generate_laplace_noise(scale)?;
168 let noisy_count = (count as f64 + noise).max(0.0) as u32;
169 noisy_counts.push(noisy_count);
170 }
171
172 self.privacy_budget.remaining_epsilon -= epsilon;
174
175 Ok((noisy_counts, epsilon))
176 }
177
178 fn generate_laplace_noise(&self, scale: f64) -> Result<f64, StatisticalError> {
195 let mut bytes = [0u8; 8];
196 getrandom::fill(&mut bytes).map_err(|e| {
197 StatisticalError::PrivacyError(format!(
198 "no OS entropy for differential-privacy noise: {e}"
199 ))
200 })?;
201 let x = u64::from_le_bytes(bytes) as f64;
204 let r = (x + 0.5) / (u64::MAX as f64 + 1.0);
205 let u = r - 0.5;
208 Ok(-scale * u.signum() * (1.0 - 2.0 * u.abs()).ln())
209 }
210
211 pub fn encrypt_result(&self, data: &[u8]) -> Result<Vec<u8>, StatisticalError> {
220 let mut crypto = self
221 .fiduciary_crypto
222 .lock()
223 .map_err(|e| StatisticalError::PrivacyError(e.to_string()))?;
224
225 const STAT_KEY_ID: &str = "statistical_results";
226 if !crypto.list_keys().iter().any(|k| k == STAT_KEY_ID) {
227 crypto
228 .generate_key(STAT_KEY_ID.to_string())
229 .map_err(|e| StatisticalError::PrivacyError(e.to_string()))?;
230 }
231
232 let signature = crypto
233 .sign(
234 data,
235 Some(STAT_KEY_ID),
236 "statistical_computing".to_string(),
237 "result_encryption".to_string(),
238 )
239 .map_err(|e| StatisticalError::PrivacyError(e.to_string()))?;
240
241 Ok(signature.sig_bytes)
242 }
243
244 pub fn verify_result(&self, data: &[u8], signature: &[u8]) -> Result<bool, StatisticalError> {
249 let crypto = self
250 .fiduciary_crypto
251 .lock()
252 .map_err(|e| StatisticalError::PrivacyError(e.to_string()))?;
253
254 const STAT_KEY_ID: &str = "statistical_results";
255 let sig = MlDsaSignature {
256 sig_bytes: signature.to_vec(),
257 };
258 crypto
259 .verify(
260 data,
261 &sig,
262 Some(STAT_KEY_ID),
263 "statistical_computing".to_string(),
264 "result_encryption".to_string(),
265 )
266 .map_err(|e| StatisticalError::PrivacyError(e.to_string()))
267 }
268
269 pub fn prove_computation(
281 &self,
282 computation_id: &str,
283 inputs: &[Vec<u8>],
284 outputs: &[Vec<u8>],
285 ) -> Result<Vec<u8>, StatisticalError> {
286 let mut zk = self
287 .zk_proofs
288 .lock()
289 .map_err(|e| StatisticalError::PrivacyError(e.to_string()))?;
290
291 let mut hasher = Sha256::new();
293 for chunk in inputs {
294 hasher.update(chunk);
295 }
296 for chunk in outputs {
297 hasher.update(chunk);
298 }
299 let digest = hasher.finalize();
300 let mut commitment = [0u8; 32];
301 commitment.copy_from_slice(&digest);
302
303 let circuit_id = format!("stat_comp_{}", computation_id);
304 zk.create_circuit(circuit_id.clone())
305 .map_err(|e| StatisticalError::PrivacyError(e.to_string()))?;
306
307 zk.add_variable(&circuit_id, "commitment".to_string(), VariableType::Public)
309 .map_err(|e| StatisticalError::PrivacyError(e.to_string()))?;
310 zk.add_variable(&circuit_id, "one".to_string(), VariableType::Private)
312 .map_err(|e| StatisticalError::PrivacyError(e.to_string()))?;
313 zk.add_variable(&circuit_id, "in_commit".to_string(), VariableType::Private)
314 .map_err(|e| StatisticalError::PrivacyError(e.to_string()))?;
315
316 zk.add_constraint(
318 &circuit_id,
319 CircuitExpression::Variable("one".to_string()),
320 CircuitExpression::Variable("in_commit".to_string()),
321 CircuitExpression::Variable("commitment".to_string()),
322 )
323 .map_err(|e| StatisticalError::PrivacyError(e.to_string()))?;
324
325 zk.generate_keys(&circuit_id)
326 .map_err(|e| StatisticalError::PrivacyError(e.to_string()))?;
327
328 let mut one_val = [0u8; 32];
330 one_val[0] = 1;
331
332 let mut witness = HashMap::new();
333 witness.insert("one".to_string(), FieldElement { value: one_val });
334 witness.insert("in_commit".to_string(), FieldElement { value: commitment });
335 witness.insert("commitment".to_string(), FieldElement { value: commitment });
336
337 let public_inputs = vec![FieldElement { value: commitment }];
338
339 let proof = zk
340 .generate_proof(&circuit_id, witness, public_inputs)
341 .map_err(|e| StatisticalError::PrivacyError(e.to_string()))?;
342
343 serde_json::to_vec(&proof).map_err(|e| StatisticalError::PrivacyError(e.to_string()))
344 }
345
346 pub fn verify_computation(
353 &self,
354 proof: &[u8],
355 public_inputs: &[Vec<u8>],
356 ) -> Result<bool, StatisticalError> {
357 let zk_proof: ZkProof = serde_json::from_slice(proof)
358 .map_err(|e| StatisticalError::PrivacyError(e.to_string()))?;
359
360 if !public_inputs.is_empty() {
363 if public_inputs.len() != zk_proof.public_inputs.len() {
364 return Ok(false);
365 }
366 for (expected, actual) in public_inputs.iter().zip(&zk_proof.public_inputs) {
367 let mut expected_arr = [0u8; 32];
368 let len = expected.len().min(32);
369 expected_arr[..len].copy_from_slice(&expected[..len]);
370 if expected_arr != actual.value {
371 return Ok(false);
372 }
373 }
374 }
375
376 let mut zk = self
377 .zk_proofs
378 .lock()
379 .map_err(|e| StatisticalError::PrivacyError(e.to_string()))?;
380
381 let result = zk
382 .verify_proof(&zk_proof)
383 .map_err(|e| StatisticalError::PrivacyError(e.to_string()))?;
384
385 Ok(result.is_valid)
386 }
387}
388
389impl DifferentialPrivacy {
390 pub fn new() -> Self {
392 Self {
393 noise_mechanisms: vec![NoiseMechanism::Laplace, NoiseMechanism::Gaussian],
394 privacy_accountant: PrivacyAccountant {
395 total_epsilon_spent: 0.0,
396 total_delta_spent: 0.0,
397 composition_method: CompositionMethod::AdvancedComposition,
398 remaining_budget: PrivacyBudget {
399 epsilon: 1.0,
400 delta: 1e-6,
401 remaining_epsilon: 1.0,
402 remaining_delta: 1e-6,
403 budget_period: 86400,
404 last_reset: 0,
405 },
406 },
407 sensitivity_analyzer: SensitivityAnalyzer::new(),
408 }
409 }
410
411 pub fn initialize(&mut self) -> Result<(), StatisticalError> {
413 self.sensitivity_analyzer.initialize()?;
414 Ok(())
415 }
416
417 pub fn noise_mechanisms(&self) -> &[NoiseMechanism] {
419 &self.noise_mechanisms
420 }
421
422 pub fn add_noise_mechanism(&mut self, mechanism: NoiseMechanism) {
424 if !self.noise_mechanisms.contains(&mechanism) {
425 self.noise_mechanisms.push(mechanism);
426 }
427 }
428
429 pub fn supports_noise_mechanism(&self, mechanism: &NoiseMechanism) -> bool {
431 self.noise_mechanisms.contains(mechanism)
432 }
433
434 pub fn privacy_accountant(&self) -> &PrivacyAccountant {
436 &self.privacy_accountant
437 }
438
439 pub fn privacy_accountant_mut(&mut self) -> &mut PrivacyAccountant {
441 &mut self.privacy_accountant
442 }
443
444 pub fn spend_budget(&mut self, epsilon: f64, delta: f64) -> Result<(), StatisticalError> {
448 let remaining = &self.privacy_accountant.remaining_budget;
449 if remaining.remaining_epsilon < epsilon || remaining.remaining_delta < delta {
450 return Err(StatisticalError::PrivacyError(
451 "Insufficient privacy budget".to_string(),
452 ));
453 }
454 self.privacy_accountant.remaining_budget.remaining_epsilon -= epsilon;
455 self.privacy_accountant.remaining_budget.remaining_delta -= delta;
456 self.privacy_accountant.total_epsilon_spent += epsilon;
457 self.privacy_accountant.total_delta_spent += delta;
458 Ok(())
459 }
460}
461
462impl SensitivityAnalyzer {
463 pub fn new() -> Self {
465 Self {
466 sensitivity_functions: HashMap::new(),
467 sensitivity_cache: HashMap::new(),
468 }
469 }
470
471 pub fn initialize(&mut self) -> Result<(), StatisticalError> {
473 Ok(())
474 }
475
476 pub fn register_function(&mut self, name: &str, func: SensitivityFunction) {
479 self.sensitivity_functions.insert(name.to_string(), func);
480 }
481
482 pub fn compute_sensitivity(
499 &mut self,
500 operation: &str,
501 data: &[f64],
502 ) -> Result<f64, StatisticalError> {
503 if let Some(func) = self.sensitivity_functions.get(operation) {
505 self.sensitivity_cache
506 .insert(operation.to_string(), func.sensitivity);
507 return Ok(func.sensitivity);
508 }
509
510 if data.is_empty() {
511 return Err(StatisticalError::InvalidData(
512 "Cannot compute sensitivity over empty data".to_string(),
513 ));
514 }
515
516 let n = data.len() as f64;
517 let sensitivity = match operation {
518 "mean" => 1.0 / n,
519 "sum" => 1.0,
520 "count" => 1.0,
521 "histogram" => 1.0,
522 "median" => {
523 let min = data.iter().cloned().fold(f64::INFINITY, f64::min);
524 let max = data.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
525 (max - min) / n
526 }
527 "variance" => {
528 let min = data.iter().cloned().fold(f64::INFINITY, f64::min);
529 let max = data.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
530 let range = max - min;
531 (range * range) / n
532 }
533 other => {
534 return Err(StatisticalError::InvalidOperation(format!(
535 "Unknown sensitivity operation '{}'",
536 other
537 )))
538 }
539 };
540
541 self.sensitivity_cache
542 .insert(operation.to_string(), sensitivity);
543 Ok(sensitivity)
544 }
545
546 pub fn get_sensitivity(
549 &mut self,
550 operation: &str,
551 data: &[f64],
552 ) -> Result<f64, StatisticalError> {
553 if let Some(cached) = self.sensitivity_cache.get(operation) {
554 return Ok(*cached);
555 }
556 self.compute_sensitivity(operation, data)
557 }
558}
559
560impl SecureAggregation {
561 pub fn new() -> Self {
563 Self {
564 aggregation_protocols: vec![
565 AggregationProtocol::SecureSum,
566 AggregationProtocol::SecureMean,
567 ],
568 encryption_schemes: vec![
569 EncryptionScheme::Homomorphic,
570 EncryptionScheme::SecretSharing,
571 ],
572 integrity_checks: Vec::new(),
573 }
574 }
575
576 pub fn initialize(&mut self) -> Result<(), StatisticalError> {
578 Ok(())
579 }
580
581 pub fn aggregation_protocols(&self) -> &[AggregationProtocol] {
583 &self.aggregation_protocols
584 }
585
586 pub fn add_aggregation_protocol(&mut self, protocol: AggregationProtocol) {
588 if !self.aggregation_protocols.contains(&protocol) {
589 self.aggregation_protocols.push(protocol);
590 }
591 }
592
593 pub fn encryption_schemes(&self) -> &[EncryptionScheme] {
595 &self.encryption_schemes
596 }
597
598 pub fn add_encryption_scheme(&mut self, scheme: EncryptionScheme) {
600 if !self.encryption_schemes.contains(&scheme) {
601 self.encryption_schemes.push(scheme);
602 }
603 }
604
605 pub fn add_integrity_check(&mut self, check: IntegrityCheck) {
607 self.integrity_checks.push(check);
608 }
609
610 pub fn integrity_checks(&self) -> &[IntegrityCheck] {
612 &self.integrity_checks
613 }
614
615 pub fn get_integrity_check(&self, check_id: &str) -> Option<&IntegrityCheck> {
617 self.integrity_checks
618 .iter()
619 .find(|c| c.check_id == check_id)
620 }
621
622 pub fn integrity_check_count(&self) -> usize {
624 self.integrity_checks.len()
625 }
626}