trustformers-mobile 0.1.1

Mobile deployment support for TrustformeRS (iOS, Android)
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
//! Cryptographic Protocols for Secure Federated Learning
//!
//! This module implements advanced cryptographic protocols including homomorphic
//! encryption, secure multi-party computation, zero-knowledge proofs, and
//! post-quantum cryptographic schemes for secure federated learning.

use serde::{Deserialize, Serialize};

/// Cryptographic configuration for secure protocols
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CryptographicConfig {
    /// Secure aggregation protocol
    pub aggregation_protocol: SecureAggregationProtocol,
    /// Homomorphic encryption settings
    pub homomorphic_encryption: HomomorphicEncryptionConfig,
    /// Secure multi-party computation
    pub secure_mpc: SecureMPCConfig,
    /// Digital signature scheme
    pub signature_scheme: DigitalSignatureScheme,
    /// Key exchange protocol
    pub key_exchange: KeyExchangeProtocol,
    /// Zero-knowledge proofs
    pub zero_knowledge_proofs: ZKProofConfig,
}

/// Secure aggregation protocols
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SecureAggregationProtocol {
    /// Basic secure aggregation
    BasicSecureAggregation,
    /// Federated secure aggregation
    FederatedSecureAggregation,
    /// Private federated learning
    PrivateFederatedLearning,
    /// SecAgg+ protocol
    SecAggPlus,
    /// Flamingo protocol
    Flamingo,
    /// FATE protocol
    FATE,
}

/// Homomorphic encryption configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HomomorphicEncryptionConfig {
    /// Encryption scheme
    pub scheme: HomomorphicScheme,
    /// Security level (bits)
    pub security_level: u16,
    /// Polynomial modulus degree
    pub poly_modulus_degree: u32,
    /// Coefficient modulus
    pub coeff_modulus: Vec<u64>,
    /// Plaintext modulus
    pub plaintext_modulus: u64,
    /// Optimization level
    pub optimization_level: OptimizationLevel,
}

/// Homomorphic encryption schemes
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum HomomorphicScheme {
    /// BFV scheme
    BFV,
    /// CKKS scheme
    CKKS,
    /// BGV scheme
    BGV,
    /// TFHE scheme
    TFHE,
}

/// Optimization levels for homomorphic encryption
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum OptimizationLevel {
    /// No optimization
    None,
    /// Basic optimization
    Basic,
    /// Advanced optimization
    Advanced,
    /// Maximum optimization
    Maximum,
}

/// Secure multi-party computation configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecureMPCConfig {
    /// MPC protocol
    pub protocol: MPCProtocol,
    /// Number of parties
    pub num_parties: u32,
    /// Threshold for secret sharing
    pub threshold: u32,
    /// Security parameter
    pub security_parameter: u16,
    /// Communication rounds
    pub communication_rounds: u32,
}

/// MPC protocols
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum MPCProtocol {
    /// Shamir's secret sharing
    ShamirSecretSharing,
    /// BGW protocol
    BGW,
    /// GMW protocol
    GMW,
    /// SPDZ protocol
    SPDZ,
    /// ABY protocol
    ABY,
    /// CrypTFlow protocol
    CrypTFlow,
}

/// Digital signature schemes
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum DigitalSignatureScheme {
    /// ECDSA
    ECDSA,
    /// EdDSA
    EdDSA,
    /// RSA-PSS
    RSAPSS,
    /// BLS signatures
    BLS,
    /// Ring signatures
    RingSignature,
}

/// Key exchange protocols
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum KeyExchangeProtocol {
    /// ECDH
    ECDH,
    /// X25519
    X25519,
    /// CRYSTALS-Kyber (post-quantum)
    Kyber,
    /// NTRU (post-quantum)
    NTRU,
}

/// Zero-knowledge proof configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ZKProofConfig {
    /// Proof system
    pub proof_system: ZKProofSystem,
    /// Circuit complexity
    pub circuit_complexity: u32,
    /// Proof size optimization
    pub proof_size_optimization: bool,
    /// Verification key caching
    pub verification_key_caching: bool,
}

/// Zero-knowledge proof systems
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ZKProofSystem {
    /// zk-SNARKs
    ZkSNARKs,
    /// zk-STARKs
    ZkSTARKs,
    /// Bulletproofs
    Bulletproofs,
    /// Plonk
    Plonk,
    /// Marlin
    Marlin,
}

/// Post-quantum cryptographic configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PostQuantumConfig {
    /// Key encapsulation mechanism
    pub kem: PostQuantumKEM,
    /// Digital signature scheme
    pub signature: PostQuantumSignature,
    /// Security level (NIST level 1-5)
    pub security_level: u8,
    /// Quantum-safe aggregation
    pub quantum_safe_aggregation: bool,
}

/// Post-quantum key encapsulation mechanisms
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PostQuantumKEM {
    /// CRYSTALS-Kyber
    Kyber,
    /// NTRU
    NTRU,
    /// SABER
    SABER,
    /// FrodoKEM
    FrodoKEM,
}

/// Post-quantum digital signatures
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PostQuantumSignature {
    /// CRYSTALS-Dilithium
    Dilithium,
    /// Falcon
    Falcon,
    /// SPHINCS+
    SPHINCSPlus,
    /// Rainbow
    Rainbow,
}

impl Default for CryptographicConfig {
    fn default() -> Self {
        Self {
            aggregation_protocol: SecureAggregationProtocol::SecAggPlus,
            homomorphic_encryption: HomomorphicEncryptionConfig::default(),
            secure_mpc: SecureMPCConfig::default(),
            signature_scheme: DigitalSignatureScheme::EdDSA,
            key_exchange: KeyExchangeProtocol::X25519,
            zero_knowledge_proofs: ZKProofConfig::default(),
        }
    }
}

impl Default for HomomorphicEncryptionConfig {
    fn default() -> Self {
        Self {
            scheme: HomomorphicScheme::CKKS,
            security_level: 128,
            poly_modulus_degree: 8192,
            coeff_modulus: vec![60, 40, 40, 60],
            plaintext_modulus: 40961,
            optimization_level: OptimizationLevel::Advanced,
        }
    }
}

impl Default for SecureMPCConfig {
    fn default() -> Self {
        Self {
            protocol: MPCProtocol::SPDZ,
            num_parties: 3,
            threshold: 2,
            security_parameter: 128,
            communication_rounds: 3,
        }
    }
}

impl Default for ZKProofConfig {
    fn default() -> Self {
        Self {
            proof_system: ZKProofSystem::Plonk,
            circuit_complexity: 1000000,
            proof_size_optimization: true,
            verification_key_caching: true,
        }
    }
}

impl Default for PostQuantumConfig {
    fn default() -> Self {
        Self {
            kem: PostQuantumKEM::Kyber,
            signature: PostQuantumSignature::Dilithium,
            security_level: 3, // NIST level 3
            quantum_safe_aggregation: true,
        }
    }
}

/// Cryptographic key manager for federated learning
#[derive(Debug, Clone)]
pub struct CryptographicKeyManager {
    /// Master public key
    pub master_public_key: Vec<u8>,
    /// Participant public keys
    pub participant_keys: std::collections::HashMap<String, Vec<u8>>,
    /// Symmetric encryption keys
    pub symmetric_keys: std::collections::HashMap<String, Vec<u8>>,
    /// Key rotation schedule
    pub key_rotation_interval: std::time::Duration,
    /// Last key rotation time
    pub last_rotation: std::time::SystemTime,
}

impl CryptographicKeyManager {
    /// Create new key manager
    pub fn new() -> Self {
        Self {
            master_public_key: Vec::new(),
            participant_keys: std::collections::HashMap::new(),
            symmetric_keys: std::collections::HashMap::new(),
            key_rotation_interval: std::time::Duration::from_secs(86400), // 24 hours
            last_rotation: std::time::SystemTime::now(),
        }
    }

    /// Add participant key
    pub fn add_participant_key(&mut self, participant_id: String, public_key: Vec<u8>) {
        self.participant_keys.insert(participant_id, public_key);
    }

    /// Remove participant key
    pub fn remove_participant_key(&mut self, participant_id: &str) {
        self.participant_keys.remove(participant_id);
    }

    /// Check if key rotation is needed
    pub fn needs_key_rotation(&self) -> bool {
        std::time::SystemTime::now()
            .duration_since(self.last_rotation)
            .unwrap_or_default() > self.key_rotation_interval
    }

    /// Rotate keys
    pub fn rotate_keys(&mut self) -> Result<(), String> {
        // In practice, this would generate new keys and distribute them
        self.last_rotation = std::time::SystemTime::now();
        Ok(())
    }

    /// Get participant count
    pub fn participant_count(&self) -> usize {
        self.participant_keys.len()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_cryptographic_config_default() {
        let config = CryptographicConfig::default();
        assert_eq!(config.aggregation_protocol, SecureAggregationProtocol::SecAggPlus);
        assert_eq!(config.signature_scheme, DigitalSignatureScheme::EdDSA);
        assert_eq!(config.key_exchange, KeyExchangeProtocol::X25519);
    }

    #[test]
    fn test_homomorphic_encryption_config() {
        let config = HomomorphicEncryptionConfig::default();
        assert_eq!(config.scheme, HomomorphicScheme::CKKS);
        assert_eq!(config.security_level, 128);
        assert_eq!(config.poly_modulus_degree, 8192);
        assert_eq!(config.optimization_level, OptimizationLevel::Advanced);
    }

    #[test]
    fn test_mpc_config() {
        let config = SecureMPCConfig::default();
        assert_eq!(config.protocol, MPCProtocol::SPDZ);
        assert_eq!(config.num_parties, 3);
        assert_eq!(config.threshold, 2);
        assert_eq!(config.security_parameter, 128);
    }

    #[test]
    fn test_post_quantum_config() {
        let config = PostQuantumConfig::default();
        assert_eq!(config.kem, PostQuantumKEM::Kyber);
        assert_eq!(config.signature, PostQuantumSignature::Dilithium);
        assert_eq!(config.security_level, 3);
        assert!(config.quantum_safe_aggregation);
    }

    #[test]
    fn test_key_manager() {
        let mut manager = CryptographicKeyManager::new();
        assert_eq!(manager.participant_count(), 0);

        manager.add_participant_key("participant1".to_string(), vec![1, 2, 3, 4]);
        manager.add_participant_key("participant2".to_string(), vec![5, 6, 7, 8]);
        assert_eq!(manager.participant_count(), 2);

        manager.remove_participant_key("participant1");
        assert_eq!(manager.participant_count(), 1);

        assert!(manager.rotate_keys().is_ok());
    }

    #[test]
    fn test_zk_proof_systems() {
        let systems = [
            ZKProofSystem::ZkSNARKs,
            ZKProofSystem::ZkSTARKs,
            ZKProofSystem::Bulletproofs,
            ZKProofSystem::Plonk,
            ZKProofSystem::Marlin,
        ];

        for system in &systems {
            let serialized = serde_json::to_string(system).expect("Operation failed");
            let deserialized: ZKProofSystem = serde_json::from_str(&serialized).expect("Operation failed");
            assert_eq!(*system, deserialized);
        }
    }

    #[test]
    fn test_homomorphic_schemes() {
        let schemes = [
            HomomorphicScheme::BFV,
            HomomorphicScheme::CKKS,
            HomomorphicScheme::BGV,
            HomomorphicScheme::TFHE,
        ];

        for scheme in &schemes {
            let serialized = serde_json::to_string(scheme).expect("Operation failed");
            let deserialized: HomomorphicScheme = serde_json::from_str(&serialized).expect("Operation failed");
            assert_eq!(*scheme, deserialized);
        }
    }

    #[test]
    fn test_mpc_protocols() {
        let protocols = [
            MPCProtocol::ShamirSecretSharing,
            MPCProtocol::BGW,
            MPCProtocol::GMW,
            MPCProtocol::SPDZ,
            MPCProtocol::ABY,
            MPCProtocol::CrypTFlow,
        ];

        for protocol in &protocols {
            let serialized = serde_json::to_string(protocol).expect("Operation failed");
            let deserialized: MPCProtocol = serde_json::from_str(&serialized).expect("Operation failed");
            assert_eq!(*protocol, deserialized);
        }
    }
}