ciphern 0.2.1

Enterprise-grade cryptographic library
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
// Copyright (c) 2025 Kirky.X
//
// Licensed under the MIT License
// See LICENSE file in the project root for full license information.

//! GPU/XPU 加速模块
//!
//! 支持 NVIDIA CUDA、AMD ROCm/OpenCL、Intel SYCL/oneAPI
//! 采用分层加速策略,CPU 优先,GPU 作为大数据量加速器

use crate::error::CryptoError;
use crate::types::Algorithm;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::RwLock;

#[cfg(feature = "gpu")]
#[allow(unused)]
pub mod device;
#[cfg(feature = "gpu")]
#[allow(unused)]
pub mod kernels;
#[cfg(feature = "gpu")]
#[allow(unused)]
pub mod memory;

#[cfg(feature = "gpu")]
#[allow(unused)]
pub use device::{XpuDevice, XpuManager, XpuType};
#[cfg(feature = "gpu")]
#[allow(unused)]
pub use kernels::{GpuKernel, KernelManager, KernelMetrics, KernelType};
#[cfg(feature = "gpu")]
#[allow(unused)]
pub use memory::GpuBuffer;

/// GPU 功能是否启用
pub static GPU_ENABLED: AtomicBool = AtomicBool::new(false);

/// 是否已初始化 GPU
pub static GPU_INITIALIZED: AtomicBool = AtomicBool::new(false);

/// 当前活跃的 XPU 类型
#[allow(dead_code)]
pub static ACTIVE_XPU_TYPE: AtomicBool = AtomicBool::new(false);

#[inline]
pub fn is_gpu_enabled() -> bool {
    GPU_ENABLED.load(Ordering::Relaxed)
}

#[inline]
pub fn is_gpu_initialized() -> bool {
    GPU_INITIALIZED.load(Ordering::Relaxed)
}

/// 初始化 GPU 加速
#[cfg(feature = "gpu")]
pub fn init_gpu() -> Result<(), CryptoError> {
    if GPU_INITIALIZED.load(Ordering::Relaxed) {
        return Ok(());
    }

    match XpuManager::new() {
        Ok(manager) => {
            if manager.has_available_device() {
                GPU_ENABLED.store(true, Ordering::Relaxed);
                GPU_INITIALIZED.store(true, Ordering::Relaxed);
                Ok(())
            } else {
                GPU_ENABLED.store(false, Ordering::Relaxed);
                GPU_INITIALIZED.store(false, Ordering::Relaxed);
                Err(CryptoError::HardwareAccelerationUnavailable(
                    "No GPU devices available".into(),
                ))
            }
        }
        Err(e) => {
            GPU_ENABLED.store(false, Ordering::Relaxed);
            GPU_INITIALIZED.store(false, Ordering::Relaxed);
            Err(CryptoError::HardwareAccelerationUnavailable(format!(
                "GPU initialization failed: {}",
                e
            )))
        }
    }
}

/// 初始化 GPU 加速(无 GPU 静默失败)
#[cfg(not(feature = "gpu"))]
pub fn init_gpu() -> Result<(), CryptoError> {
    Err(CryptoError::HardwareAccelerationUnavailable(
        "GPU support not enabled".into(),
    ))
}

/// GPU 加速阈值配置
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct GpuThresholdConfig {
    /// 最小数据大小(字节),超过此值才使用 GPU
    pub min_data_size: usize,
    /// 批处理阈值,超过此数量使用 GPU
    pub batch_threshold: usize,
    /// 内存池预分配大小
    pub memory_pool_size: usize,
    /// 同步等待超时(毫秒)
    pub sync_timeout_ms: u64,
}

impl Default for GpuThresholdConfig {
    fn default() -> Self {
        Self {
            min_data_size: 32 * 1024,            // 32KB
            batch_threshold: 100,                // 100 个操作
            memory_pool_size: 256 * 1024 * 1024, // 256MB
            sync_timeout_ms: 5000,               // 5秒
        }
    }
}

impl GpuThresholdConfig {
    /// 实时加密场景配置(低延迟优先)
    pub fn realtime() -> Self {
        Self {
            min_data_size: 64 * 1024, // 64KB
            batch_threshold: 10,
            memory_pool_size: 128 * 1024 * 1024,
            sync_timeout_ms: 1000,
        }
    }

    /// 批量处理场景配置(吞吐量优先)
    #[allow(dead_code)]
    pub fn batch() -> Self {
        Self {
            min_data_size: 16 * 1024, // 16KB
            batch_threshold: 1000,
            memory_pool_size: 1024 * 1024 * 1024, // 1GB
            sync_timeout_ms: 30000,
        }
    }

    /// 判断是否应该使用 GPU
    #[inline]
    pub fn should_use_gpu(&self, data_size: usize, batch_count: usize) -> bool {
        data_size >= self.min_data_size || batch_count >= self.batch_threshold
    }
}

/// 全局 GPU 配置
pub static GPU_CONFIG: std::sync::OnceLock<RwLock<GpuThresholdConfig>> = std::sync::OnceLock::new();

#[inline]
pub fn get_gpu_config() -> std::sync::RwLockReadGuard<'static, GpuThresholdConfig> {
    GPU_CONFIG
        .get_or_init(|| RwLock::new(GpuThresholdConfig::realtime()))
        .read()
        .unwrap()
}

#[inline]
pub fn set_gpu_config(config: GpuThresholdConfig) {
    let mut config_ref = GPU_CONFIG
        .get_or_init(|| RwLock::new(GpuThresholdConfig::realtime()))
        .write()
        .unwrap();
    *config_ref = config;
}

/// GPU 加速的哈希函数
#[cfg(feature = "gpu")]
pub fn accelerated_hash_gpu(data: &[u8], algorithm: Algorithm) -> Result<Vec<u8>, CryptoError> {
    if !is_gpu_enabled() {
        return Err(CryptoError::HardwareAccelerationUnavailable(
            "GPU not enabled".into(),
        ));
    }

    let config = get_gpu_config();
    if !config.should_use_gpu(data.len(), 1) {
        return Err(CryptoError::HardwareAccelerationUnavailable(
            "Data size too small for GPU acceleration".into(),
        ));
    }

    let manager = XpuManager::get();
    if let Some(ref m) = *manager {
        let device = m.get_primary_device()?;

        let kernel = device.get_kernel(algorithm)?;
        kernel.hash(data, algorithm)
    } else {
        Err(CryptoError::HardwareAccelerationUnavailable(
            "GPU not initialized".into(),
        ))
    }
}

/// GPU 加速的 AES 加密
#[cfg(feature = "gpu")]
pub fn accelerated_aes_gpu(
    key: &[u8],
    nonce: &[u8],
    data: &[u8],
    encrypt: bool,
) -> Result<Vec<u8>, CryptoError> {
    if !is_gpu_enabled() {
        return Err(CryptoError::HardwareAccelerationUnavailable(
            "GPU not enabled".into(),
        ));
    }

    let config = get_gpu_config();
    if !config.should_use_gpu(data.len(), 1) {
        return Err(CryptoError::HardwareAccelerationUnavailable(
            "Data size too small for GPU acceleration".into(),
        ));
    }

    let manager = XpuManager::get();
    if let Some(ref m) = *manager {
        let device = m.get_primary_device()?;

        if encrypt {
            device.aes_gcm_encrypt(key, nonce, data)
        } else {
            device.aes_gcm_decrypt(key, nonce, data)
        }
    } else {
        Err(CryptoError::HardwareAccelerationUnavailable(
            "GPU not initialized".into(),
        ))
    }
}

/// GPU 加速的 ECDSA 签名
#[cfg(feature = "gpu")]
pub fn accelerated_ecdsa_sign_gpu(
    private_key: &[u8],
    data: &[u8],
    algorithm: Algorithm,
) -> Result<Vec<u8>, CryptoError> {
    if !is_gpu_enabled() {
        return Err(CryptoError::HardwareAccelerationUnavailable(
            "GPU not enabled".into(),
        ));
    }

    let config = get_gpu_config();
    if !config.should_use_gpu(data.len(), 1) {
        return Err(CryptoError::HardwareAccelerationUnavailable(
            "Data size too small for GPU acceleration".into(),
        ));
    }

    let manager = XpuManager::get();
    if let Some(ref m) = *manager {
        let device = m.get_primary_device()?;

        let kernel = device.get_kernel(algorithm)?;
        kernel.ecdsa_sign(private_key, data, algorithm)
    } else {
        Err(CryptoError::HardwareAccelerationUnavailable(
            "GPU not initialized".into(),
        ))
    }
}

/// GPU 加速的 ECDSA 验证
#[cfg(feature = "gpu")]
pub fn accelerated_ecdsa_verify_gpu(
    public_key: &[u8],
    data: &[u8],
    signature: &[u8],
    algorithm: Algorithm,
) -> Result<bool, CryptoError> {
    if !is_gpu_enabled() {
        return Err(CryptoError::HardwareAccelerationUnavailable(
            "GPU not enabled".into(),
        ));
    }

    let config = get_gpu_config();
    if !config.should_use_gpu(data.len(), 1) {
        return Err(CryptoError::HardwareAccelerationUnavailable(
            "Data size too small for GPU acceleration".into(),
        ));
    }

    let manager = XpuManager::get();
    if let Some(ref m) = *manager {
        let device = m.get_primary_device()?;

        let kernel = device.get_kernel(algorithm)?;
        kernel.ecdsa_verify(public_key, data, signature, algorithm)
    } else {
        Err(CryptoError::HardwareAccelerationUnavailable(
            "GPU not initialized".into(),
        ))
    }
}

/// GPU 加速的 ECDSA 批量验证
#[cfg(feature = "gpu")]
pub fn accelerated_ecdsa_verify_batch_gpu(
    public_keys: &[&[u8]],
    data: &[&[u8]],
    signatures: &[&[u8]],
    algorithm: Algorithm,
) -> Result<Vec<bool>, CryptoError> {
    if !is_gpu_enabled() {
        return Err(CryptoError::HardwareAccelerationUnavailable(
            "GPU not enabled".into(),
        ));
    }

    let config = get_gpu_config();
    let batch_count = public_keys.len();
    if !config.should_use_gpu(0, batch_count) {
        return Err(CryptoError::HardwareAccelerationUnavailable(
            "Batch size too small for GPU acceleration".into(),
        ));
    }

    let manager = XpuManager::get();
    if let Some(ref m) = *manager {
        let device = m.get_primary_device()?;

        let kernel = device.get_kernel(algorithm)?;
        kernel.ecdsa_verify_batch(public_keys, data, signatures, algorithm)
    } else {
        Err(CryptoError::HardwareAccelerationUnavailable(
            "GPU not initialized".into(),
        ))
    }
}

/// GPU 加速的 Ed25519 签名
#[cfg(feature = "gpu")]
pub fn accelerated_ed25519_sign_gpu(
    private_key: &[u8],
    data: &[u8],
) -> Result<Vec<u8>, CryptoError> {
    if !is_gpu_enabled() {
        return Err(CryptoError::HardwareAccelerationUnavailable(
            "GPU not enabled".into(),
        ));
    }

    let config = get_gpu_config();
    if !config.should_use_gpu(data.len(), 1) {
        return Err(CryptoError::HardwareAccelerationUnavailable(
            "Data size too small for GPU acceleration".into(),
        ));
    }

    let manager = XpuManager::get();
    if let Some(ref m) = *manager {
        let device = m.get_primary_device()?;

        let kernel = device.get_kernel(Algorithm::Ed25519)?;
        kernel.ed25519_sign(private_key, data)
    } else {
        Err(CryptoError::HardwareAccelerationUnavailable(
            "GPU not initialized".into(),
        ))
    }
}

/// GPU 加速的 Ed25519 验证
#[cfg(feature = "gpu")]
pub fn accelerated_ed25519_verify_gpu(
    public_key: &[u8],
    data: &[u8],
    signature: &[u8],
) -> Result<bool, CryptoError> {
    if !is_gpu_enabled() {
        return Err(CryptoError::HardwareAccelerationUnavailable(
            "GPU not enabled".into(),
        ));
    }

    let config = get_gpu_config();
    if !config.should_use_gpu(data.len(), 1) {
        return Err(CryptoError::HardwareAccelerationUnavailable(
            "Data size too small for GPU acceleration".into(),
        ));
    }

    let manager = XpuManager::get();
    if let Some(ref m) = *manager {
        let device = m.get_primary_device()?;

        let kernel = device.get_kernel(Algorithm::Ed25519)?;
        kernel.ed25519_verify(public_key, data, signature)
    } else {
        Err(CryptoError::HardwareAccelerationUnavailable(
            "GPU not initialized".into(),
        ))
    }
}

/// 关闭 GPU 加速,释放资源
#[cfg(feature = "gpu")]
pub fn shutdown_gpu() -> Result<(), CryptoError> {
    if !GPU_INITIALIZED.load(Ordering::Relaxed) {
        return Ok(());
    }

    let mut manager = XpuManager::get();
    if let Some(ref mut m) = *manager {
        m.shutdown_all_devices()?;
    }

    GPU_ENABLED.store(false, Ordering::Relaxed);
    GPU_INITIALIZED.store(false, Ordering::Relaxed);

    Ok(())
}

/// 关闭 GPU 加速(无 GPU 静默失败)
#[cfg(not(feature = "gpu"))]
pub fn shutdown_gpu() -> Result<(), CryptoError> {
    Ok(())
}

#[cfg(test)]
mod tests {
    #[cfg(feature = "gpu")]
    mod gpu_tests {
        use super::super::*;

        #[test]
        fn test_gpu_threshold_config() {
            let config = GpuThresholdConfig::default();
            assert!(!config.should_use_gpu(1024, 1));
            assert!(config.should_use_gpu(1024 * 1024, 1));
            assert!(config.should_use_gpu(1024, 200));
        }

        #[test]
        fn test_realtime_config() {
            let config = GpuThresholdConfig::realtime();
            assert!(config.min_data_size > GpuThresholdConfig::default().min_data_size);
            assert!(config.batch_threshold < GpuThresholdConfig::default().batch_threshold);
        }

        #[test]
        fn test_batch_config() {
            let config = GpuThresholdConfig::batch();
            assert!(config.min_data_size < GpuThresholdConfig::default().min_data_size);
            assert!(config.batch_threshold > GpuThresholdConfig::default().batch_threshold);
        }
    }

    #[cfg(not(feature = "gpu"))]
    mod cpu_only_tests {
        #[test]
        fn test_gpu_not_enabled() {
            let result = init_gpu();
            assert!(result.is_err());
        }
    }
}