Skip to main content

privacy/
types.rs

1//! Shared types across the PQCPrivacy crate.
2//!
3//! These types form the common vocabulary of the framework — from
4//! five-dimensional manifold coordinates to privacy proofs, icosuples,
5//! and telemetry structs.
6
7extern crate alloc;
8use alloc::{string::String, vec::Vec};
9
10use serde::{Deserialize, Serialize};
11use zeroize::{Zeroize, ZeroizeOnDrop};
12
13// ── Five-Dimensional Manifold Coordinates ─────────────────────
14
15/// The five dimensions of the 5D-EZPH hypergraph vertex.
16///
17/// - `spatial`:      position embedding in the anonymity mesh
18/// - `temporal`:     expiry clock (Unix ms)
19/// - `probabilistic`: differential privacy noise distribution parameter
20/// - `quantum`:      phase angle for Bell-state analog modulation
21/// - `chaotic`:      Chua/Rössler attractor trajectory coordinate
22#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
23pub struct FiveDimCoord {
24    pub spatial:      f64,
25    pub temporal:     f64,
26    pub probabilistic: f64,
27    pub quantum:      f64,
28    pub chaotic:      f64,
29}
30
31impl FiveDimCoord {
32    pub fn zero() -> Self {
33        Self { spatial: 0.0, temporal: 0.0, probabilistic: 0.0, quantum: 0.0, chaotic: 0.0 }
34    }
35}
36
37/// A hypergraph vertex — a 5-qubit tensor product state.
38#[derive(Debug, Clone, Serialize, Deserialize)]
39pub struct HypergraphVertex {
40    pub id:    String,
41    pub coord: FiveDimCoord,
42    /// Serialized proof commitment (base64url)
43    pub commitment: String,
44    /// Expiry timestamp (Unix ms); 0 = no expiry
45    pub expiry_ms: u64,
46}
47
48/// A hyperedge connecting ≥2 vertices via Bell-state channel.
49#[derive(Debug, Clone, Serialize, Deserialize)]
50pub struct Hyperedge {
51    pub id:       String,
52    pub vertices: Vec<String>,
53    /// Kaluza-Klein metric perturbation factor
54    pub kk_metric: f64,
55    /// Simulated CHSH correlation value
56    pub chsh_value: f64,
57}
58
59// ── Zero-Knowledge Proof Types ───────────────────────
60
61/// Proof system selector for the hybrid ZK layer.
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
63pub enum ProofScheme {
64    /// zk-SNARK (Groth16/Halo2) — compact, trusted-setup
65    Snark,
66    /// zk-STARK — transparent, post-quantum, larger proofs
67    Stark,
68    /// Hybrid: SNARK for succinctness + STARK for transparency
69    Hybrid,
70    /// Bulletproofs+ — for range proofs (genomic traits)
71    Bulletproofs,
72}
73
74/// A privacy-preserving zero-knowledge proof.
75#[derive(Debug, Clone, Serialize, Deserialize)]
76pub struct PrivacyProof {
77    /// Serialized proof bytes (base64url)
78    pub proof_bytes:   String,
79    /// Public inputs (hex-encoded)
80    pub public_inputs: String,
81    /// Proof scheme used
82    pub scheme:        ProofScheme,
83    /// Security level in bits
84    pub security_bits: u32,
85    /// Approximate proof size in bytes
86    pub proof_size:    usize,
87    /// Simulated CHSH correlation (for entangled proofs)
88    pub chsh_value:    f64,
89    /// Lyapunov exponent of chaos perturbation applied
90    pub lyapunov:      f64,
91}
92
93impl PrivacyProof {
94    /// Returns `true` if the proof achieves non-local soundness (CHSH > 2.8).
95    pub fn is_non_local(&self) -> bool {
96        self.chsh_value > 2.8
97    }
98}
99
100// ── Chaos Telemetry ──────────────────────────────────
101
102/// Telemetry emitted by chaos attractor modules.
103#[derive(Debug, Clone, Serialize, Deserialize)]
104pub struct ChaosTelemetry {
105    pub lyapunov:  f64,
106    pub h_min:     f64,
107    pub passed:    bool,
108    pub attractor: AttractorKind,
109}
110
111/// Which chaos attractor is active.
112#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
113pub enum AttractorKind {
114    /// Chua double-scroll (primary)
115    Chua,
116    /// Rössler 3D flow (backup)
117    Rossler,
118}
119
120// ── Differential Privacy ─────────────────────────────────────
121
122/// Noise mechanism for differential privacy.
123#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
124pub enum DpMechanism {
125    Laplace,
126    Gaussian,
127}
128
129/// A DP noise frame exported by the DPE-RB engine.
130#[derive(Debug, Clone, Serialize, Deserialize)]
131pub struct DpNoiseFrame {
132    pub renyi_alpha: u32,
133    pub bound:       f64,
134    pub mechanism:   DpMechanism,
135    /// Epsilon consumed by this frame
136    pub epsilon:     f64,
137    /// Chaos-modulated noise scale
138    pub noise_scale: f64,
139}
140
141// ── TupleChain Five-Tuple ─────────────────────────────────────
142
143/// The five-tuple semantic ledger entry.
144///
145/// `(subject, predicate, object, proof, expiry)`
146#[derive(Debug, Clone, Serialize, Deserialize)]
147pub struct PrivacyTuple {
148    pub subject:   String,
149    pub predicate: String,
150    /// Serialized object value (may be FHE ciphertext)
151    pub object:    Vec<u8>,
152    /// Embedded ZK proof
153    pub proof:     PrivacyProof,
154    /// Expiry timestamp (Unix ms) with Laplace noise applied
155    pub expiry_ms: u64,
156    /// Wyqcc L1 anchor hash (hex)
157    pub anchor:    Option<String>,
158}
159
160impl PrivacyTuple {
161    /// Returns `true` if the tuple has expired.
162    pub fn is_expired(&self, now_ms: u64) -> bool {
163        self.expiry_ms > 0 && now_ms > self.expiry_ms
164    }
165}
166
167// ── QFKH Key Material ─────────────────────────────────────────
168
169/// An ephemeral QFKH session key — zeroized on drop.
170#[derive(Debug, Clone, Zeroize, ZeroizeOnDrop)]
171pub struct EphemeralKey {
172    /// ML-KEM encapsulated shared secret (32 bytes)
173    pub shared_secret: [u8; 32],
174    /// Chain key for ratchet derivation
175    pub chain_key:     [u8; 32],
176    /// Creation timestamp (Unix ms)
177    pub created_ms:    u64,
178    /// Expiry interval (ms); default ≤1 ms
179    pub expiry_ms:     u64,
180}
181
182impl EphemeralKey {
183    pub fn is_expired(&self, now_ms: u64) -> bool {
184        now_ms.saturating_sub(self.created_ms) >= self.expiry_ms
185    }
186}
187
188// ── Genomic Token ────────────────────────────────────────
189
190/// A nano-tokenized genomic allele commitment.
191#[derive(Debug, Clone, Serialize, Deserialize)]
192pub struct GenomicToken {
193    /// Pedersen commitment to 2–4 bit allele encoding
194    pub commitment:  String,
195    /// ZK proof of trait (Bulletproofs+)
196    pub trait_proof: PrivacyProof,
197    /// Expiry-bound tuple ID on Wyqcc L1
198    pub tuple_id:    String,
199    /// DP noise parameter applied (ε)
200    pub dp_epsilon:  f64,
201}
202
203// ── Mesh Node Types ──────────────────────────────────────────
204
205/// DW3B mesh node type selector.
206#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
207pub enum NodeKind {
208    /// Mixnet/Tor with Sphinx packets
209    Mixnet,
210    /// Query nodes with Bloom filters
211    Query,
212    /// Stake anonymity nodes
213    Stake,
214    /// Index nodes with Merkle Patricia Tries
215    Index,
216    /// CDN nodes with iced caching
217    Cdn,
218    /// Governance nodes for ZKP-voting
219    Governance,
220    /// Key management nodes
221    KeyManagement,
222    /// Physical/virtual micro-nodes for entropy
223    Micro,
224}
225
226/// A DW3B mesh node descriptor.
227#[derive(Debug, Clone, Serialize, Deserialize)]
228pub struct MeshNode {
229    pub id:       String,
230    pub kind:     NodeKind,
231    pub endpoint: String,
232    /// Stake weight (for sybil resistance)
233    pub stake:    u64,
234    /// PQC public key (hex)
235    pub pubkey:   String,
236}
237
238// ── Sphinx Packet ────────────────────────────────────────────
239
240/// A layered Sphinx packet for anonymous routing.
241#[derive(Debug, Clone, Serialize, Deserialize)]
242pub struct SphinxPacket {
243    /// Layered-encrypted payload
244    pub payload:   Vec<u8>,
245    /// Number of hops (5–9)
246    pub hops:      u8,
247    /// Poisson decoy flag
248    pub is_decoy:  bool,
249    /// Chaos perturbation seed (hex)
250    pub chaos_seed: String,
251}
252
253// ── Privacy Icosuple ─────────────────────────────────────────
254
255/// An 8192-byte privacy icosuple — the canonical serialization unit.
256#[derive(Debug, Clone, Serialize, Deserialize)]
257pub struct PrivacyIcosuple {
258    /// Serialized 5D manifold vertex (tensor representation)
259    pub manifold_tensor: Vec<u8>,
260    /// Embedded ZK proof bundle
261    pub proof_bundle:    Vec<u8>,
262    /// Chaos attractor state snapshot
263    pub chaos_state:     Vec<u8>,
264    /// Whether the serialized payload is compressed. The algorithm is fixed by the
265    /// serialization format version (version 1 = DEFLATE), not carried per-frame.
266    pub compressed:      bool,
267    /// PQC signature over the icosuple (hex)
268    pub signature:       String,
269}
270
271impl PrivacyIcosuple {
272    /// Maximum serialized size in bytes.
273    pub const MAX_BYTES: usize = 8192;
274}
275
276// ── Capability Advertisement ──────────────────────────────────
277
278/// A JSON-LD capability descriptor for UNI advertisement.
279#[derive(Debug, Clone, Serialize, Deserialize)]
280pub struct CapabilityDescriptor {
281    pub node_id:      String,
282    pub capabilities: Vec<PrivacyCapability>,
283    /// Chaos-perturbed freshness nonce
284    pub nonce:        String,
285    /// PQC signature (hex)
286    pub signature:    String,
287}
288
289/// A single privacy capability offered by a UNI node.
290#[derive(Debug, Clone, Serialize, Deserialize)]
291pub struct PrivacyCapability {
292    pub kind:           CapabilityKind,
293    pub scheme:         String,
294    pub security_level: u32,
295    pub recursion:      bool,
296}
297
298/// Capability type for UNI advertisement.
299#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
300pub enum CapabilityKind {
301    Fhe,
302    Zk,
303    Dp,
304    Mpc,
305}
306
307// ── Governance Vote ──────────────────────────────────────────
308
309/// An encrypted governance ballot.
310#[derive(Debug, Clone, Serialize, Deserialize)]
311pub struct EncryptedBallot {
312    pub voter_commitment: String,
313    pub encrypted_vote:   Vec<u8>,
314    pub zk_proof:         PrivacyProof,
315    pub stake_weight:     u64,
316    pub timestamp_ms:     u64,
317}
318
319/// Outcome of a governance vote.
320#[derive(Debug, Clone, Serialize, Deserialize)]
321pub struct VoteOutcome {
322    pub proposal_id: String,
323    pub passed:      bool,
324    pub tally:       u64,
325    pub total_stake: u64,
326    pub proof:       PrivacyProof,
327}
328
329// ── Entropy Frame ────────────────────────────────────────────
330
331/// An entropy frame from physical/virtual micro-nodes.
332#[derive(Debug, Clone, Serialize, Deserialize)]
333pub struct EntropyFrame {
334    /// Raw entropy bytes (≥256 bits)
335    pub bytes:     Vec<u8>,
336    /// 5Dqeh hash of the frame (hex)
337    pub hash_5dqeh: String,
338    /// Min-entropy estimate
339    pub h_min:     f64,
340    /// Source kind
341    pub source:    EntropySource,
342    /// ZKP proof of quality
343    pub proof:     PrivacyProof,
344}
345
346/// Source label for an entropy frame. Neither variant is backed by a real hardware entropy
347/// source or true randomness in this crate today — see [`crate::mesh::micro`] and the crate
348/// README's "What runs today vs. what is designed". `PhysicalQrng` is a label a caller can
349/// select, not a driver for actual QRNG hardware; `VirtualChaos` reflects the deterministic
350/// Chua/Rössler simulation in [`crate::chaos`].
351#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
352pub enum EntropySource {
353    /// Label only — no physical QRNG hardware integration exists in this crate
354    PhysicalQrng,
355    /// Deterministic Chua/Rössler simulation (see [`crate::chaos`]), not true randomness
356    VirtualChaos,
357}
358
359// ── Poset Event ───────────────────────────────────────────────
360
361/// A causal event in the Hypergraph Chronosync poset.
362#[derive(Debug, Clone, Serialize, Deserialize)]
363pub struct PosetEvent {
364    pub id:           String,
365    pub dependencies: Vec<String>,
366    pub payload_hash: String,
367    pub timestamp_ms: u64,
368    pub zk_merge:     Option<PrivacyProof>,
369}
370
371// ── Utility ───────────────────────────────────────────────────────────────────
372
373/// Returns the current Unix timestamp in milliseconds.
374/// In no_std environments, callers must provide this via injection.
375#[cfg(feature = "std")]
376pub fn unix_now_ms() -> u64 {
377    use std::time::{SystemTime, UNIX_EPOCH};
378    SystemTime::now()
379        .duration_since(UNIX_EPOCH)
380        .map(|d| d.as_millis() as u64)
381        .unwrap_or(0)
382}
383
384#[cfg(not(feature = "std"))]
385pub fn unix_now_ms() -> u64 {
386    0 // caller must inject time in no_std
387}