Skip to main content

tenzro_types/
tee.rs

1//! Trusted Execution Environment (TEE) types for Tenzro Network
2//!
3//! This module defines types for TEE attestation, provider management,
4//! and secure computation on the network.
5
6use crate::primitives::{Address, Timestamp};
7use serde::{Deserialize, Serialize};
8
9/// Supported TEE vendors on Tenzro Network
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
11#[serde(rename_all = "PascalCase")]
12pub enum TeeVendor {
13    /// Intel SGX (Software Guard Extensions)
14    IntelSGX,
15    /// Intel TDX (Trust Domain Extensions)
16    IntelTdx,
17    /// AMD SEV (Secure Encrypted Virtualization)
18    AMDSEV,
19    /// AMD SEV-SNP (Secure Encrypted Virtualization - Secure Nested Paging)
20    AmdSevSnp,
21    /// ARM TrustZone
22    ARMTrustZone,
23    /// AWS Nitro Enclaves
24    AWSNitro,
25    /// AWS Nitro (alternative naming)
26    AwsNitro,
27    /// NVIDIA GPU Confidential Computing (H100/H200/Blackwell)
28    NvidiaGpu,
29    /// Generic/Other TEE implementation
30    #[default]
31    Generic,
32}
33
34impl TeeVendor {
35    /// Returns the vendor name as a string
36    pub fn as_str(&self) -> &str {
37        match self {
38            Self::IntelSGX => "Intel SGX",
39            Self::IntelTdx => "Intel TDX",
40            Self::AMDSEV => "AMD SEV",
41            Self::AmdSevSnp => "AMD SEV-SNP",
42            Self::ARMTrustZone => "ARM TrustZone",
43            Self::AWSNitro => "AWS Nitro",
44            Self::AwsNitro => "AWS Nitro",
45            Self::NvidiaGpu => "NVIDIA GPU CC",
46            Self::Generic => "Generic",
47        }
48    }
49}
50
51/// A TEE attestation report
52///
53/// Contains cryptographic evidence that code is running in a trusted
54/// execution environment.
55#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
56#[serde(default)]
57pub struct AttestationReport {
58    /// Report ID
59    pub id: uuid::Uuid,
60    /// TEE vendor
61    pub vendor: TeeVendor,
62    /// Application-specific user data included in the report
63    pub user_data: Vec<u8>,
64    /// Raw attestation data
65    pub attestation_data: Vec<u8>,
66    /// Certificate chain for verification
67    pub certificates: Vec<Vec<u8>>,
68    /// Report timestamp
69    pub timestamp: Timestamp,
70    /// Additional vendor-specific metadata
71    pub metadata: std::collections::HashMap<String, String>,
72    /// Quote/evidence from the TEE    #[serde(default)]
73    pub quote: Vec<u8>,
74    /// Measurement/hash of the running code    #[serde(default)]
75    pub measurement: Vec<u8>,
76    /// Report signature    #[serde(default)]
77    pub signature: Vec<u8>,
78    /// Additional vendor-specific data    #[serde(default)]
79    pub vendor_data: Vec<u8>,
80}
81
82impl Default for AttestationReport {
83    fn default() -> Self {
84        Self {
85            id: uuid::Uuid::nil(),
86            vendor: TeeVendor::default(),
87            user_data: Vec::new(),
88            attestation_data: Vec::new(),
89            certificates: Vec::new(),
90            timestamp: Timestamp::default(),
91            metadata: std::collections::HashMap::new(),
92            quote: Vec::new(),
93            measurement: Vec::new(),
94            signature: Vec::new(),
95            vendor_data: Vec::new(),
96        }
97    }
98}
99
100impl AttestationReport {
101    /// Creates a new attestation report
102    pub fn new(
103        vendor: TeeVendor,
104        attestation_data: Vec<u8>,
105        quote: Vec<u8>,
106        measurement: Vec<u8>,
107    ) -> Self {
108        Self {
109            id: uuid::Uuid::new_v4(),
110            vendor,
111            user_data: Vec::new(),
112            attestation_data,
113            certificates: Vec::new(),
114            timestamp: Timestamp::now(),
115            metadata: std::collections::HashMap::new(),
116            quote,
117            measurement,
118            signature: Vec::new(),
119            vendor_data: Vec::new(),
120        }
121    }
122
123    /// Adds a signature to the report
124    pub fn with_signature(mut self, signature: Vec<u8>) -> Self {
125        self.signature = signature;
126        self
127    }
128
129    /// Adds vendor-specific data
130    pub fn with_vendor_data(mut self, data: Vec<u8>) -> Self {
131        self.vendor_data = data;
132        self
133    }
134}
135
136/// A measurement from a TEE attestation
137#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
138pub struct Measurement {
139    /// Index of the measurement register (e.g., PCR index, RTMR index)
140    #[serde(default)]
141    pub index: u32,
142    /// Hash algorithm used (e.g., "SHA384", "SHA256")
143    #[serde(default)]
144    pub algorithm: String,
145    /// Measurement value (hash)
146    #[serde(default)]
147    pub value: Vec<u8>,
148    /// Measurement type/register    #[serde(default)]
149    pub register: String,
150    /// Measurement description    #[serde(default)]
151    pub description: Option<String>,
152}
153
154/// Result of attestation verification
155#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
156pub struct AttestationResult {
157    /// Whether the attestation is valid
158    #[serde(default)]
159    pub valid: bool,
160    /// Verification timestamp
161    #[serde(default)]
162    pub verified_at: Timestamp,
163    /// TEE vendor
164    #[serde(default)]
165    pub vendor: TeeVendor,
166    /// TCB (Trusted Computing Base) version string
167    #[serde(default)]
168    pub tcb_version: String,
169    /// Measurements extracted from the attestation
170    #[serde(default)]
171    pub measurements: Vec<Measurement>,
172    /// Whether the certificate chain is valid
173    #[serde(default)]
174    pub cert_chain_valid: bool,
175    /// Additional verification details
176    #[serde(default)]
177    pub details: std::collections::HashMap<String, String>,
178    /// Code measurement that was verified    #[serde(default)]
179    pub verified_measurement: Vec<u8>,
180    /// Error message if verification failed    #[serde(default)]
181    pub error: Option<String>,
182    /// Additional verification metadata    #[serde(default)]
183    pub metadata: AttestationMetadata,
184}
185
186impl Default for AttestationResult {
187    fn default() -> Self {
188        Self {
189            valid: false,
190            verified_at: Timestamp::now(),
191            vendor: TeeVendor::Generic,
192            tcb_version: String::new(),
193            measurements: Vec::new(),
194            cert_chain_valid: false,
195            details: std::collections::HashMap::new(),
196            verified_measurement: Vec::new(),
197            error: None,
198            metadata: AttestationMetadata::default(),
199        }
200    }
201}
202
203impl AttestationResult {
204    /// Creates a successful attestation result
205    pub fn success(vendor: TeeVendor, measurement: Vec<u8>) -> Self {
206        Self {
207            valid: true,
208            verified_at: Timestamp::now(),
209            vendor,
210            tcb_version: String::new(),
211            measurements: Vec::new(),
212            cert_chain_valid: true,
213            details: std::collections::HashMap::new(),
214            verified_measurement: measurement,
215            error: None,
216            metadata: AttestationMetadata::default(),
217        }
218    }
219
220    /// Creates a failed attestation result
221    pub fn failure(vendor: TeeVendor, error: String) -> Self {
222        Self {
223            valid: false,
224            verified_at: Timestamp::now(),
225            vendor,
226            tcb_version: String::new(),
227            measurements: Vec::new(),
228            cert_chain_valid: false,
229            details: std::collections::HashMap::new(),
230            verified_measurement: Vec::new(),
231            error: Some(error),
232            metadata: AttestationMetadata::default(),
233        }
234    }
235}
236
237/// Additional metadata for attestation verification
238#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
239pub struct AttestationMetadata {
240    /// TEE firmware version
241    pub firmware_version: Option<String>,
242    /// Security patch level
243    pub security_patch_level: Option<String>,
244    /// Debug mode enabled
245    pub debug_mode: bool,
246    /// Production environment
247    pub production: bool,
248}
249
250/// TEE provider capacity information
251#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
252pub struct TeeCapacity {
253    /// Maximum concurrent jobs
254    pub max_concurrent_jobs: u32,
255    /// Current active jobs
256    pub active_jobs: u32,
257    /// Maximum concurrent operations
258    pub max_operations: u32,
259    /// Current active operations
260    pub current_operations: u32,
261    /// Total memory available (bytes)
262    pub total_memory: u64,
263    /// Available memory (bytes)
264    pub available_memory: u64,
265    /// Total CPU cores
266    pub total_cpu_cores: u32,
267    /// Available CPU cores
268    pub available_cpu_cores: u32,
269    /// Supported TEE vendors
270    pub supported_vendors: Vec<TeeVendor>,
271}
272
273impl TeeCapacity {
274    /// Creates a new TEE capacity
275    pub fn new(max_concurrent_jobs: u32, total_memory: u64, total_cpu_cores: u32) -> Self {
276        Self {
277            max_concurrent_jobs,
278            active_jobs: 0,
279            max_operations: max_concurrent_jobs,
280            current_operations: 0,
281            total_memory,
282            available_memory: total_memory,
283            total_cpu_cores,
284            available_cpu_cores: total_cpu_cores,
285            supported_vendors: Vec::new(),
286        }
287    }
288
289    /// Checks if capacity is available for a new job
290    pub fn has_capacity(&self) -> bool {
291        self.active_jobs < self.max_concurrent_jobs
292            && self.available_memory > 0
293            && self.available_cpu_cores > 0
294    }
295
296    /// Returns the utilization percentage (0-100)
297    pub fn utilization(&self) -> u8 {
298        if self.max_concurrent_jobs == 0 {
299            0
300        } else {
301            ((self.active_jobs as f64 / self.max_concurrent_jobs as f64) * 100.0) as u8
302        }
303    }
304}
305
306/// Information about a TEE provider
307#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
308pub struct TeeProviderInfo {
309    /// Provider ID
310    pub id: uuid::Uuid,
311    /// TEE vendor
312    pub vendor: TeeVendor,
313    /// Provider's network address
314    pub address: String,
315    /// Provider's public key
316    pub public_key: Vec<u8>,
317    /// Provider's attestation report
318    pub attestation: AttestationReport,
319    /// Registration timestamp
320    pub registered_at: Timestamp,
321    /// Last heartbeat timestamp
322    pub last_heartbeat: Timestamp,
323    /// Provider capacity
324    pub capacity: TeeCapacity,
325    /// Provider status
326    pub status: TeeProviderStatus,
327    /// Attestation verification result    #[serde(default)]
328    pub attestation_result: Option<AttestationResult>,
329    /// Pricing configuration    #[serde(default)]
330    pub pricing: TeeProviderPricing,
331    /// Provider reputation    #[serde(default)]
332    pub reputation: u64,
333    /// Total jobs completed    #[serde(default)]
334    pub total_jobs_completed: u64,
335    /// Last attestation update    #[serde(default)]
336    pub last_attestation_update: Timestamp,
337}
338
339impl TeeProviderInfo {
340    /// Creates a new TEE provider info
341    pub fn new(address: Address, attestation: AttestationReport, capacity: TeeCapacity) -> Self {
342        let now = Timestamp::now();
343        Self {
344            id: uuid::Uuid::new_v4(),
345            vendor: attestation.vendor,
346            address: address.to_base58(),
347            public_key: Vec::new(),
348            attestation,
349            registered_at: now,
350            last_heartbeat: now,
351            capacity,
352            status: TeeProviderStatus::Pending,
353            attestation_result: None,
354            pricing: TeeProviderPricing::default(),
355            reputation: 0,
356            total_jobs_completed: 0,
357            last_attestation_update: now,
358        }
359    }
360
361    /// Checks if the provider is active and has capacity
362    pub fn is_available(&self) -> bool {
363        self.status == TeeProviderStatus::Active && self.capacity.has_capacity()
364    }
365}
366
367/// TEE provider pricing configuration
368#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
369pub struct TeeProviderPricing {
370    /// Price per compute unit (in smallest TNZO unit)
371    pub price_per_compute_unit: u64,
372    /// Price per memory GB-hour (in smallest TNZO unit)
373    pub price_per_memory_gb_hour: u64,
374    /// Minimum job price (in smallest TNZO unit)
375    pub minimum_job_price: u64,
376}
377
378impl Default for TeeProviderPricing {
379    fn default() -> Self {
380        Self {
381            price_per_compute_unit: 1000,
382            price_per_memory_gb_hour: 5000,
383            minimum_job_price: 100,
384        }
385    }
386}
387
388/// TEE provider operational status
389#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
390pub enum TeeProviderStatus {
391    /// Registration pending verification
392    Pending,
393    /// Active and accepting jobs
394    Active,
395    /// Temporarily inactive
396    Inactive,
397    /// Draining existing jobs, not accepting new ones
398    Draining,
399    /// Offline (no recent heartbeat)
400    Offline,
401    /// Untrusted (failed attestation verification)
402    Untrusted,
403    /// Suspended due to violations
404    Suspended,
405    /// Attestation expired, needs renewal
406    AttestationExpired,
407}
408
409/// Request to execute an operation inside a TEE enclave
410#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
411pub struct EnclaveRequest {
412    /// Unique request ID
413    pub id: uuid::Uuid,
414    /// The operation to perform
415    pub operation: String,
416    /// Operation parameters
417    pub params: Vec<u8>,
418    /// Whether to include attestation in response
419    pub include_attestation: bool,
420}
421
422impl EnclaveRequest {
423    /// Creates a new enclave request
424    pub fn new(operation: String, params: Vec<u8>) -> Self {
425        Self {
426            id: uuid::Uuid::new_v4(),
427            operation,
428            params,
429            include_attestation: false,
430        }
431    }
432}
433
434/// Response from a TEE enclave operation
435#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
436pub struct EnclaveResponse {
437    /// ID of the request this responds to
438    pub request_id: uuid::Uuid,
439    /// Whether the operation succeeded
440    pub success: bool,
441    /// Response data
442    pub data: Vec<u8>,
443    /// Error message if operation failed
444    pub error: Option<String>,
445    /// Optional attestation proving the response came from a TEE
446    pub attestation: Option<AttestationReport>,
447}
448
449/// Parameters for generating a key inside a TEE enclave
450#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
451pub struct KeyGenParams {
452    /// Cryptographic algorithm to use
453    pub algorithm: KeyAlgorithm,
454    /// Purpose of the key
455    pub purpose: KeyPurpose,
456    /// Whether the key can be exported
457    pub exportable: bool,
458    /// Additional algorithm-specific parameters
459    pub params: std::collections::HashMap<String, String>,
460}
461
462/// Cryptographic algorithms supported for enclave key generation
463#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
464pub enum KeyAlgorithm {
465    /// Ed25519 signature algorithm
466    Ed25519,
467    /// ECDSA with secp256k1 curve
468    Secp256k1,
469    /// AES-256-GCM encryption
470    Aes256Gcm,
471}
472
473/// Purpose of a cryptographic key
474#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
475pub enum KeyPurpose {
476    /// For signing operations
477    Signing,
478    /// For encryption/decryption
479    Encryption,
480    /// For key agreement/derivation
481    KeyAgreement,
482}
483
484/// Handle to a cryptographic key stored inside a TEE enclave
485#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
486pub struct EnclaveKeyHandle {
487    /// Unique key ID
488    pub id: uuid::Uuid,
489    /// Algorithm of the key
490    pub algorithm: KeyAlgorithm,
491    /// Public key (if applicable), None for symmetric keys
492    pub public_key: Option<Vec<u8>>,
493    /// Timestamp when key was created
494    pub created_at: Timestamp,
495    /// Optional attestation proving the key was generated in a TEE
496    pub attestation: Option<AttestationReport>,
497}