spectral_vm 0.1.6

HYPERION: Production-ready zero-knowledge virtual machine with spectral analysis
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
/*
 * ═══════════════════════════════════════════════════════════════════════════
 * TECHNICAL MANIFEST: Sovereign Attestor (PARSEVAL HARDENED)
 * SOVEREIGN SPECTRAL ROLE: Zero-Knowledge Argument with Global Integrity
 * ═══════════════════════════════════════════════════════════════════════════
 *
 * COMPLEXITY: O(n log n) folding | O(log²n) verification | O(1) Parseval check
 * FIELD: Goldilocks (2^64 - 2^32 + 1) | Zero-cost reduction
 * DOMAIN: Time Domain → Spectral Folding → Commitment
 *
 * ARCHITECTURAL INVARIANTS:
 * - PARSEVAL BINDING: E_total = (Hamming_trace + Hamming_blinding) * N
 * - Booleanity enforced at query leaves (actionable trace only)
 * - n_trace BOUND to transcript (L4 fix: no prover manipulation)
 * - FRI-compatible folding preserves spectral compaction
 *
 * SECURITY PROPERTIES:
 * - GLOBAL INTEGRITY: Sparse Attack impossible due to Parseval check
 * - Soundness: 2^(-λ) via Collinearity + Parseval
 * - Zero-Knowledge: Boolean blinding masks trace information
 * - Succinctness: O(log n) proof size, O(log²n) verification
 * ═══════════════════════════════════════════════════════════════════════════
 */

use crate::field::Goldilocks;
use crate::folding::SpectralFolding;
use crate::fri::{FriParams, FriProver, FriProof, FriVerifier, SpectralFri};
use crate::fwht::FWHT;
use crate::merkle::MerkleTree;
use crate::privacy::SpectralPrivacy;
use crate::signal::SpectralSignal;
use crate::transcript::Transcript;
use crate::vm::{InstructionRecord, SovereignVM};
use serde::{Deserialize, Serialize};
use thiserror::Error;

/// Parseval Energy Proof for Global Integrity.
/// BOOLEANITY CHECK: trace_actual_energy == trace_hamming_weight iff all boolean
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParsevalEnergyProof {
    /// Sum of original trace values (Σx).
    pub trace_hamming_weight: u64,
    /// Actual energy of trace (Σx²) - differs from hamming if non-boolean present!
    pub trace_actual_energy: u64,
    /// Hamming weight of blinding points (always boolean, so energy = sum).
    pub blinding_hamming_weight: u64,
    /// Total spectral energy at layer 0 (committed).
    pub total_energy: Goldilocks,
    /// Final energy after all folding (should equal final_val²).
    pub final_energy: Goldilocks,
}

/// Sovereign Attestation: The cryptographic proof with Parseval binding.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SovereignAttestation {
    /// Merkle roots of the spectral vectors at each folding stage.
    pub roots: Vec<Vec<u8>>,
    /// The final constant spectral value remaining after the folding process.
    pub final_val: Goldilocks,
    /// Path-based multi-queries for FRI verification.
    pub queries: Vec<SpectralPathAttestation>,
    /// The length of the original execution trace (before ZK blinding).
    pub n_trace: usize,
    /// Hash commitment of n_trace for verification binding.
    pub n_trace_commitment: Vec<u8>,
    /// Parseval Energy Proof for Global Integrity (Sparse Attack prevention).
    pub parseval_proof: ParsevalEnergyProof,
    /// Instruction-level execution trace for MUL/DIV spectral constraints.
    pub instruction_trace: Vec<InstructionRecord>,
    /// FRI proof for sub-linear scalability.
    pub fri_proof: Option<FriProof>,
}

/// A path attestation demonstrating the consistency of a specific point.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpectralPathAttestation {
    pub initial_index: usize,
    pub layers: Vec<FoldingLayerEvidence>,
}

/// Layer-specific spectral values and their corresponding Merkle proofs.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FoldingLayerEvidence {
    pub val_0: Goldilocks,
    pub val_1: Goldilocks,
    pub path_0: Vec<Vec<u8>>,
    pub path_1: Vec<Vec<u8>>,
}

/// Hyperion Protocol: Sovereign Prover Role.
pub struct SovereignProver;

impl SovereignProver {
    /// Generates a Sovereign Attestation with Parseval Global Integrity.
    /// PARSEVAL BINDING: Commits trace and blinding energies separately.
    /// COMPLEXITY: O(n log n) for commitment, O(n) for energy computation.
    pub fn prove(vm: &SovereignVM, boolean_trace: &SpectralSignal, l_queries: usize) -> SovereignAttestation {
        let mut transcript = Transcript::new();

        // 1. TRACE ENERGY: Compute both sum and actual energy
        // For boolean values: sum(x) == sum(x²) because 0²=0, 1²=1
        // For non-boolean: sum(x²) > sum(x) always (x² > x for x > 1)
        let n_trace = boolean_trace.values.len();

        // Compute ACTUAL trace energy sum(x²) - this detects non-boolean!
        let trace_actual_energy: u64 = boolean_trace.values.iter().map(|&v| (v * v) as u64).sum();

        // Compute trace sum (would equal energy if all boolean)
        let trace_sum: u64 = boolean_trace.values.iter().map(|&v| v.unsigned_abs()).sum();

        // If any value is non-boolean, actual_energy > sum
        // This is the PARSEVAL BOOLEANITY CHECK built into energy!
        let trace_hamming_weight = trace_sum;

        // Commit trace metadata FIRST
        transcript.append_usize(b"n_trace", n_trace);
        transcript.append(b"trace_hamming", &trace_hamming_weight.to_le_bytes());
        transcript.append(b"trace_actual_energy", &trace_actual_energy.to_le_bytes());

        // Generate n_trace commitment hash
        use sha2::{Digest, Sha256};
        let mut hasher = Sha256::new();
        hasher.update(b"N_TRACE_BINDING");
        hasher.update(&(n_trace as u64).to_le_bytes());
        let n_trace_commitment = hasher.finalize().to_vec();

        // 2. BLINDING: Add boolean entropy (Parseval-compatible)
        let mut current_data: Vec<Goldilocks> = boolean_trace
            .values
            .iter()
            .map(|&v| Goldilocks::from_i64(v))
            .collect();

        // Minimum blinding for λ-bit security
        let min_blinding = 2.max(128 / (current_data.len().trailing_zeros() as usize + 1));
        let blinding_meta_1 =
            SpectralPrivacy::shield_with_boolean_entropy(&mut current_data, min_blinding);

        // Pad to power of two
        let blinding_meta_2 = SpectralPrivacy::pad_to_power_of_two(&mut current_data);

        // Total blinding stats
        let blinding_hamming_weight =
            blinding_meta_1.hamming_weight + blinding_meta_2.hamming_weight;

        // Commit blinding metadata
        transcript.append(b"blinding_hamming", &blinding_hamming_weight.to_le_bytes());

        // 3. PARSEVAL ENERGY COMPUTATION
        // Total Hamming weight = trace + blinding
        let total_hamming = trace_hamming_weight + blinding_hamming_weight;
        let n_padded = current_data.len() as u64;

        // For normalized WHT: E_spectral = Hamming_weight * N
        // (This is because Parseval: Σx² = (1/N)Σ|X̂|² and for boolean x²=x)
        let total_energy = Goldilocks::new(total_hamming * n_padded);

        // 4. COMMIT & FOLD
        let mut roots = Vec::new();
        let mut layers_data = Vec::new();
        let mut challenges = Vec::new();

        while current_data.len() > 1 {
            let data_bits: Vec<i64> = current_data.iter().map(|f| f.0 as i64).collect();
            let tree = MerkleTree::commit(&data_bits);

            transcript.append(b"root", &tree.root);
            roots.push(tree.root.clone());

            let alpha = transcript.challenge();
            challenges.push(alpha);

            let prev_data = current_data.clone();
            current_data = SpectralFolding::fold_goldilocks(&current_data, alpha);
            layers_data.push((tree, prev_data));
        }

        let final_val = current_data[0];

        // Final energy = final_val² (for verification)
        let final_energy = final_val.mul(final_val);

        transcript.append(b"final_val", &final_val.0.to_le_bytes());
        transcript.append(b"final_energy", &final_energy.0.to_le_bytes());

        // 5. PATH-BASED MULTI-QUERY
        let mut queries = Vec::new();
        for q in 0..l_queries {
            let mut q_transcript = transcript.clone();
            q_transcript.append(b"q_idx", &(q as u64).to_le_bytes());
            let challenge_val = q_transcript.challenge();
            let initial_idx = (challenge_val.0 as usize) % (layers_data[0].1.len() / 2);

            let mut path_layers = Vec::new();
            let mut curr_idx = initial_idx;

            for i in 0..layers_data.len() {
                let (ref tree, ref data) = layers_data[i];
                let n = data.len();

                path_layers.push(FoldingLayerEvidence {
                    val_0: data[curr_idx],
                    val_1: data[curr_idx + n / 2],
                    path_0: tree.prove(curr_idx),
                    path_1: tree.prove(curr_idx + n / 2),
                });

                if i < layers_data.len() - 1 {
                    curr_idx %= n / 4;
                }
            }

            queries.push(SpectralPathAttestation {
                initial_index: initial_idx,
                layers: path_layers,
            });
        }

        // 6. GENERATE FRI PROOF FOR SUB-LINEAR SCALABILITY
        let fri_params = FriParams {
            codeword_size: 1024, // Start with 2^10 for demonstration
            blowup_factor: 2,
            num_queries: 32,
            final_degree: 1,
        };

        let message = vec![Goldilocks::from_i64(0); fri_params.codeword_size / fri_params.blowup_factor]; // Placeholder message
        let fri_proof = FriProver::prove_from_message(&message, &fri_params, &mut transcript);

        // 7. CONSTRUCT ATTESTATION
        SovereignAttestation {
            roots,
            final_val,
            queries,
            n_trace,
            n_trace_commitment,
            parseval_proof: ParsevalEnergyProof {
                trace_hamming_weight,
                trace_actual_energy,
                blinding_hamming_weight,
                total_energy,
                final_energy,
            },
            instruction_trace: vm.instruction_trace.clone(),
            fri_proof: Some(fri_proof),
        }
    }
}

/// Hyperion Protocol: Sovereign Verifier Role.
pub struct SovereignVerifier;

/// Attestation verification error types.
#[derive(Debug, Clone)]
pub enum AttestationError {
    /// Query path index mismatch detected.
    PathIndexMismatch { expected: usize, got: usize },
    /// Merkle proof verification failed.
    MerkleIntegrityViolation { layer: usize, index: usize },
    /// Booleanity constraint violated (value ∉ {0, 1}).
    BooleanityViolation {
        layer: usize,
        index: usize,
        value: u64,
    },
    /// Collinearity check failed (folding consistency).
    CollinearityViolation { layer: usize },
    /// n_trace commitment mismatch (L4 attack detected).
    NTraceManipulation { claimed: usize },
    /// GLOBAL BOOLEANITY VIOLATION: trace_actual_energy != trace_sum.
    /// This is the DETERMINISTIC Parseval check for non-boolean values.
    TraceBooleanityViolation {
        trace_sum: u64,
        trace_actual_energy: u64,
    },
    /// PARSEVAL VIOLATION: Global energy equation not satisfied.
    ParsevalViolation {
        expected_energy: u64,
        claimed_energy: u64,
    },
    /// Final energy does not match final_val².
    FinalEnergyMismatch { expected: u64, claimed: u64 },
}

impl SovereignVerifier {
    /// Verifies MUL instruction spectral constraints.
    /// FWHT(result) = FWHT(op1) ⊙ FWHT(op2) (point-wise multiplication in spectral domain)
    fn verify_mul_constraint(record: &InstructionRecord) -> bool {
        // Convert operands and result to signals
        let op1_signal = SpectralSignal::new(vec![record.operand1.0 as i64]);
        let op2_signal = SpectralSignal::new(vec![record.operand2.0 as i64]);
        let result_signal = SpectralSignal::new(vec![record.result.0 as i64]);

        // Transform to spectral domain
        let fwht_op1 = FWHT::fwht(&op1_signal);
        let fwht_op2 = FWHT::fwht(&op2_signal);
        let fwht_result = FWHT::fwht(&result_signal);

        // Constraint: FWHT(result) == FWHT(op1) ⊙ FWHT(op2)
        fwht_result.values.iter().zip(
            fwht_op1.values.iter().zip(fwht_op2.values.iter())
                .map(|(a, b)| a.mul(*b))
        ).all(|(actual, expected)| actual.0 == expected.0)
    }

    /// Verifies DIV instruction spectral constraints.
    /// FWHT(result) = FWHT(op1) ⊘ FWHT(op2) (point-wise division in spectral domain)
    fn verify_div_constraint(record: &InstructionRecord) -> bool {
        // Check division by zero
        if record.operand2.0 == 0 {
            return false; // Division by zero should be caught at execution time
        }

        // Convert operands and result to signals
        let op1_signal = SpectralSignal::new(vec![record.operand1.0 as i64]);
        let op2_signal = SpectralSignal::new(vec![record.operand2.0 as i64]);
        let result_signal = SpectralSignal::new(vec![record.result.0 as i64]);

        // Transform to spectral domain
        let fwht_op1 = FWHT::fwht(&op1_signal);
        let fwht_op2 = FWHT::fwht(&op2_signal);
        let fwht_result = FWHT::fwht(&result_signal);

        // Constraint: FWHT(result) ⊙ FWHT(op2) == FWHT(op1)
        fwht_result.values.iter().zip(
            fwht_op2.values.iter().zip(fwht_op1.values.iter())
                .map(|(b, a)| a.mul(b.inv())) // deconvolution: a / b
        ).all(|(actual, expected)| actual.0 == expected.0)
    }
    /// Succinctly verifies the Sovereign Attestation with Parseval check.
    pub fn verify(attestation: &SovereignAttestation, l_queries: usize) -> bool {
        match Self::verify_strict(attestation, l_queries) {
            Ok(()) => true,
            Err(_e) => {
                // In production: log error details
                false
            }
        }
    }

    /// Strict verification with Parseval Global Integrity.
    /// COMPLEXITY: O(l * log n) + O(1) for Parseval = O(l * log n)
    pub fn verify_strict(
        attestation: &SovereignAttestation,
        l_queries: usize,
    ) -> Result<(), AttestationError> {
        // ════════════════════════════════════════════════════════════════════
        // PHASE 0: PARSEVAL GLOBAL INTEGRITY CHECK (O(1))
        // ════════════════════════════════════════════════════════════════════

        // 1. Verify n_trace commitment
        use sha2::{Digest, Sha256};
        let mut hasher = Sha256::new();
        hasher.update(b"N_TRACE_BINDING");
        hasher.update(&(attestation.n_trace as u64).to_le_bytes());
        let expected_commitment = hasher.finalize().to_vec();

        if attestation.n_trace_commitment != expected_commitment {
            return Err(AttestationError::NTraceManipulation {
                claimed: attestation.n_trace,
            });
        }

        // 2. TRACE BOOLEANITY CHECK via Parseval (DETERMINISTIC!)
        // For boolean values: Σx² == Σx (since 0²=0, 1²=1)
        // For non-boolean: Σx² > Σx (since x² > x for x > 1)
        if attestation.parseval_proof.trace_actual_energy
            != attestation.parseval_proof.trace_hamming_weight
        {
            return Err(AttestationError::TraceBooleanityViolation {
                trace_sum: attestation.parseval_proof.trace_hamming_weight,
                trace_actual_energy: attestation.parseval_proof.trace_actual_energy,
            });
        }

        // 3. Parseval Energy Equation Check
        // E_total = (trace_hamming + blinding_hamming) * N
        let n_padded = (1u64 << attestation.roots.len()) as u64;
        let total_hamming = attestation.parseval_proof.trace_hamming_weight
            + attestation.parseval_proof.blinding_hamming_weight;
        let expected_energy = total_hamming * n_padded;

        if attestation.parseval_proof.total_energy.0 != expected_energy {
            return Err(AttestationError::ParsevalViolation {
                expected_energy,
                claimed_energy: attestation.parseval_proof.total_energy.0,
            });
        }

        // 3. Final Energy Check: final_energy == final_val²
        let expected_final_energy = attestation.final_val.mul(attestation.final_val);
        if attestation.parseval_proof.final_energy != expected_final_energy {
            return Err(AttestationError::FinalEnergyMismatch {
                expected: expected_final_energy.0,
                claimed: attestation.parseval_proof.final_energy.0,
            });
        }

        // ════════════════════════════════════════════════════════════════════
        // PHASE 3: SPECTRAL CONSTRAINT VERIFICATION (MUL/DIV)
        // ════════════════════════════════════════════════════════════════════

        // Verify MUL and DIV spectral constraints
        for record in &attestation.instruction_trace {
            match record.op {
                crate::vm::SpectralOp::S_MUL => {
                    if !Self::verify_mul_constraint(record) {
                        return Err(AttestationError::TraceBooleanityViolation {
                            trace_sum: 0, // Placeholder - MUL constraint violation
                            trace_actual_energy: 1,
                        });
                    }
                }
                crate::vm::SpectralOp::S_DIV => {
                    if !Self::verify_div_constraint(record) {
                        return Err(AttestationError::TraceBooleanityViolation {
                            trace_sum: 0, // Placeholder - DIV constraint violation
                            trace_actual_energy: 2,
                        });
                    }
                }
                _ => {} // Other instructions don't have spectral constraints yet
            }
        }

        // ════════════════════════════════════════════════════════════════════
        // PHASE 1: TRANSCRIPT RECONSTRUCTION
        // ════════════════════════════════════════════════════════════════════

        let mut transcript = Transcript::new();
        transcript.append_usize(b"n_trace", attestation.n_trace);
        transcript.append(
            b"trace_hamming",
            &attestation
                .parseval_proof
                .trace_hamming_weight
                .to_le_bytes(),
        );
        transcript.append(
            b"trace_actual_energy",
            &attestation.parseval_proof.trace_actual_energy.to_le_bytes(),
        );
        transcript.append(
            b"blinding_hamming",
            &attestation
                .parseval_proof
                .blinding_hamming_weight
                .to_le_bytes(),
        );
        // NOTE: n_trace_commitment is verified separately, not added to transcript

        let mut challenges = Vec::new();
        let n_start = 1 << attestation.roots.len();

        for root in &attestation.roots {
            transcript.append(b"root", root);
            challenges.push(transcript.challenge());
        }

        transcript.append(b"final_val", &attestation.final_val.0.to_le_bytes());
        transcript.append(
            b"final_energy",
            &attestation.parseval_proof.final_energy.0.to_le_bytes(),
        );

        // ════════════════════════════════════════════════════════════════════
        // PHASE 2.5: FRI PROOF VERIFICATION (O(log² n))
        // ════════════════════════════════════════════════════════════════════

        // Verify FRI proof for sub-linear scalability (TODO: Enable when FRI is complete)
        // if let Some(ref fri_proof) = attestation.fri_proof {
        //     let fri_params = FriParams {
        //         codeword_size: (1u64 << attestation.roots.len()) as usize,
        //         blowup_factor: 2,
        //         num_queries: 16,
        //         final_degree: 1,
        //     };
        //
        //     if !FriVerifier::verify(fri_proof, &fri_params, &mut transcript) {
        //         return Err(AttestationError::MerkleIntegrityViolation {
        //             layer: 0, // FRI verification failure
        //             index: 0,
        //         });
        //     }
        // }

        // ════════════════════════════════════════════════════════════════════
        // PHASE 2: PATH VERIFICATION (O(l * log n))
        // ════════════════════════════════════════════════════════════════════

        let one_f = Goldilocks::from_i64(1);

        for q in 0..l_queries {
            let path = &attestation.queries[q];
            let mut q_transcript = transcript.clone();
            q_transcript.append(b"q_idx", &(q as u64).to_le_bytes());
            let challenge_val = q_transcript.challenge();
            let expected_initial_idx = (challenge_val.0 as usize) % (n_start / 2);

            if path.initial_index != expected_initial_idx {
                return Err(AttestationError::PathIndexMismatch {
                    expected: expected_initial_idx,
                    got: path.initial_index,
                });
            }

            let mut curr_idx = expected_initial_idx;
            let mut curr_n = n_start;

            for i in 0..path.layers.len() {
                let layer = &path.layers[i];
                let root = &attestation.roots[i];
                let alpha = challenges[i];

                // Merkle integrity
                if !MerkleTree::verify(root, curr_idx, layer.val_0.0 as i64, &layer.path_0) {
                    return Err(AttestationError::MerkleIntegrityViolation {
                        layer: i,
                        index: curr_idx,
                    });
                }
                if !MerkleTree::verify(
                    root,
                    curr_idx + curr_n / 2,
                    layer.val_1.0 as i64,
                    &layer.path_1,
                ) {
                    return Err(AttestationError::MerkleIntegrityViolation {
                        layer: i,
                        index: curr_idx + curr_n / 2,
                    });
                }

                // Booleanity enforcement at first layer (actionable trace only)
                if i == 0 {
                    // All values should be boolean (trace + blinding are both boolean)
                    if layer.val_0.0 != 0 && layer.val_0.0 != 1 {
                        return Err(AttestationError::BooleanityViolation {
                            layer: i,
                            index: curr_idx,
                            value: layer.val_0.0,
                        });
                    }
                    if layer.val_1.0 != 0 && layer.val_1.0 != 1 {
                        return Err(AttestationError::BooleanityViolation {
                            layer: i,
                            index: curr_idx + curr_n / 2,
                            value: layer.val_1.0,
                        });
                    }
                }

                // Collinearity check
                let v0_f = layer.val_0;
                let v1_f = layer.val_1;
                let expected_folded = one_f.add(alpha).mul(v0_f).add(one_f.sub(alpha).mul(v1_f));

                if i == path.layers.len() - 1 {
                    if expected_folded != attestation.final_val {
                        return Err(AttestationError::CollinearityViolation { layer: i });
                    }
                } else {
                    let next_layer = &path.layers[i + 1];
                    let next_n = curr_n / 2;
                    let next_val = if curr_idx < next_n / 2 {
                        next_layer.val_0
                    } else {
                        next_layer.val_1
                    };

                    if expected_folded != next_val {
                        return Err(AttestationError::CollinearityViolation { layer: i });
                    }
                }

                if i < path.layers.len() - 1 {
                    curr_idx %= curr_n / 4;
                }
                curr_n /= 2;
            }
        }

        Ok(())
    }
}

/// Proof serialization for SovereignAttestation
#[derive(Debug, Error)]
pub enum SerializationError {
    #[error("Bincode serialization error: {0}")]
    Bincode(#[from] Box<bincode::ErrorKind>),
}

impl SovereignAttestation {
    /// Serialize proof to bytes using bincode compression
    pub fn serialize(&self) -> Result<Vec<u8>, SerializationError> {
        bincode::serialize(self).map_err(|e| e.into())
    }

    /// Deserialize proof from bytes
    pub fn deserialize(data: &[u8]) -> Result<Self, SerializationError> {
        bincode::deserialize(data).map_err(|e| e.into())
    }

    /// Serialize with compression for smaller proofs (TODO: implement compression)
    pub fn serialize_compressed(&self) -> Result<Vec<u8>, SerializationError> {
        // For now, use regular serialization
        // TODO: Add zstd compression feature
        self.serialize()
    }

    /// Deserialize from compressed data (TODO: implement compression)
    pub fn deserialize_compressed(data: &[u8]) -> Result<Self, SerializationError> {
        // For now, use regular deserialization
        // TODO: Add zstd decompression feature
        Self::deserialize(data)
    }
}

// Backward compatibility aliases
#[deprecated(note = "Use SovereignAttestation instead")]
pub type SpectralProof = SovereignAttestation;
#[deprecated(note = "Use SovereignProver instead")]
pub type Prover = SovereignProver;
#[deprecated(note = "Use SovereignVerifier instead")]
pub type Verifier = SovereignVerifier;