exochain-proofs 0.2.0-beta

EXOCHAIN zero-knowledge proof skeleton -- UNAUDITED, pedagogical only. See crate README.
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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
// Copyright 2026 Exochain Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

//! Zero-knowledge ML verification.
//!
//! Verifies that a given output was produced by a committed model on a
//! committed input, without revealing the model weights or input data.
//!
//! # Provenance extensions (LEG-007)
//!
//! `InferenceProof` carries optional provenance fields required for FRE 702
//! / Daubert admissibility:
//!
//! - `prompt_hash` — distinct from `input_hash`; captures the system/user
//!   prompt separately from the contextual input data.
//! - `human_attestation` — a signed record of whether the reviewing human
//!   adopted, modified, or rejected the AI output.
//! - `ai_delta` — records the divergence between AI recommendation and final
//!   human decision.
//! - `daubert_checklist` — structured metadata for FRE 702 admissibility.
//!
//! All new fields are `Option<T>` with `#[serde(default)]` so that existing
//! serialized `InferenceProof` values continue to deserialize correctly
//! (Architecture panel backward-compat requirement).

use exo_core::{
    hash::hash_structured,
    types::{Hash256, PublicKey, Signature},
};
use serde::{Deserialize, Serialize};

use crate::error::{ProofError, Result};

// ---------------------------------------------------------------------------
// ModelCommitment
// ---------------------------------------------------------------------------

/// A commitment to a machine learning model.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ModelCommitment {
    /// Hash of the model architecture description.
    pub architecture_hash: Hash256,
    /// Hash of the model weights.
    pub weights_hash: Hash256,
    /// Model version identifier.
    pub version: u64,
}

impl ModelCommitment {
    /// Create a new model commitment.
    #[must_use]
    pub fn new(architecture: &[u8], weights: &[u8], version: u64) -> Self {
        Self {
            architecture_hash: Hash256::digest(architecture),
            weights_hash: Hash256::digest(weights),
            version,
        }
    }

    /// Compute the canonical commitment hash.
    #[must_use]
    pub fn commitment_hash(&self) -> Hash256 {
        let mut hasher = blake3::Hasher::new();
        hasher.update(b"zkml:model:");
        hasher.update(self.architecture_hash.as_bytes());
        hasher.update(self.weights_hash.as_bytes());
        hasher.update(&self.version.to_le_bytes());
        Hash256::from_bytes(*hasher.finalize().as_bytes())
    }
}

// ---------------------------------------------------------------------------
// Provenance types (LEG-007)
// ---------------------------------------------------------------------------

/// Whether the reviewing human adopted, modified, or rejected the AI output.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum AttestationDecision {
    /// Human accepted the AI output verbatim.
    Adopted,
    /// Human modified the AI output before finalising.
    Modified,
    /// Human rejected the AI output and decided independently.
    Rejected,
}

/// Signed human attestation over an AI inference.
///
/// Required for FRE 702 / Daubert admissibility: the attestation proves that
/// a qualified human reviewed the AI output and made an independent decision.
///
/// The `signature` field is an Ed25519 signature over the canonical message:
/// `b"zkml:attestation:" || reviewer_did_len_le_u64 || reviewer_did_bytes || ai_recommendation_hash || final_decision_hash || decision_variant_byte`
///
/// Daubert admissibility requires the stronger inference-bound message from
/// [`HumanAttestation::signing_message_for_inference`], which binds the
/// reviewer decision to the prompt hash, input hash, output hash, model
/// commitment, proof, and verification tag.
///
/// Callers must verify the signature against the reviewer's `public_key` before
/// relying on the attestation for evidentiary purposes.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HumanAttestation {
    /// DID of the reviewing human.
    pub reviewer_did: String,
    /// Public key of the reviewer (for signature verification).
    pub reviewer_public_key: PublicKey,
    /// What the AI system recommended.
    pub ai_recommendation_hash: Hash256,
    /// What the human ultimately decided.
    pub final_decision_hash: Hash256,
    /// Whether the human adopted, modified, or rejected the AI output.
    pub decision: AttestationDecision,
    /// Ed25519 signature over the attestation payload.
    pub signature: Signature,
}

impl HumanAttestation {
    /// Compute the canonical message that must be signed by the reviewer.
    ///
    /// The reviewer DID length is part of the signed frame. If it cannot be
    /// represented exactly, the message is rejected instead of being encoded
    /// with a saturated sentinel length.
    pub fn signing_message(
        reviewer_did: &str,
        ai_recommendation_hash: &Hash256,
        final_decision_hash: &Hash256,
        decision: &AttestationDecision,
    ) -> Result<Vec<u8>> {
        let decision_byte: u8 = match decision {
            AttestationDecision::Adopted => 0x01,
            AttestationDecision::Modified => 0x02,
            AttestationDecision::Rejected => 0x03,
        };
        let reviewer_did_bytes = reviewer_did.as_bytes();
        let reviewer_did_len = u64::try_from(reviewer_did_bytes.len()).map_err(|_| {
            ProofError::InvalidProofFormat(format!(
                "reviewer DID length {} cannot be represented in canonical attestation frame",
                reviewer_did_bytes.len()
            ))
        })?;
        let mut msg = b"zkml:attestation:".to_vec();
        msg.extend_from_slice(&reviewer_did_len.to_le_bytes());
        msg.extend_from_slice(reviewer_did_bytes);
        msg.extend_from_slice(ai_recommendation_hash.as_bytes());
        msg.extend_from_slice(final_decision_hash.as_bytes());
        msg.push(decision_byte);
        Ok(msg)
    }

    /// Verify the Ed25519 signature on this attestation.
    #[must_use]
    pub fn verify_signature(&self) -> bool {
        let Ok(msg) = Self::signing_message(
            &self.reviewer_did,
            &self.ai_recommendation_hash,
            &self.final_decision_hash,
            &self.decision,
        ) else {
            return false;
        };
        exo_core::crypto::verify(&msg, &self.signature, &self.reviewer_public_key)
    }

    /// Compute the canonical inference-bound message that must be signed when
    /// the attestation is used for Daubert admissibility.
    pub fn signing_message_for_inference(
        reviewer_did: &str,
        ai_recommendation_hash: &Hash256,
        final_decision_hash: &Hash256,
        decision: &AttestationDecision,
        inference: &InferenceProof,
    ) -> Result<Vec<u8>> {
        let Some(prompt_hash) = inference.prompt_hash else {
            return Err(ProofError::InvalidProofFormat(
                "prompt_hash is required for inference-bound human attestation".into(),
            ));
        };
        let payload = HumanAttestationInferenceSigningPayload {
            domain: "exo.zkml.human_attestation.v2",
            reviewer_did,
            ai_recommendation_hash: *ai_recommendation_hash,
            final_decision_hash: *final_decision_hash,
            decision,
            model_hash: inference.model_commitment.commitment_hash(),
            input_hash: inference.input_hash,
            output_hash: inference.output_hash,
            proof: inference.proof,
            verification_tag: inference.verification_tag,
            prompt_hash,
        };
        canonical_cbor_message(&payload, "human attestation inference signing payload")
    }

    /// Verify this attestation against a concrete inference proof and its
    /// provenance fields.
    #[must_use]
    pub fn verify_for_inference(&self, inference: &InferenceProof) -> bool {
        let Ok(msg) = Self::signing_message_for_inference(
            &self.reviewer_did,
            &self.ai_recommendation_hash,
            &self.final_decision_hash,
            &self.decision,
            inference,
        ) else {
            return false;
        };
        exo_core::crypto::verify(&msg, &self.signature, &self.reviewer_public_key)
    }
}

#[derive(Serialize)]
struct HumanAttestationInferenceSigningPayload<'a> {
    domain: &'static str,
    reviewer_did: &'a str,
    ai_recommendation_hash: Hash256,
    final_decision_hash: Hash256,
    decision: &'a AttestationDecision,
    model_hash: Hash256,
    input_hash: Hash256,
    output_hash: Hash256,
    proof: Hash256,
    verification_tag: Hash256,
    prompt_hash: Hash256,
}

/// Captures divergence between AI recommendation and final human decision.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AiDelta {
    /// Hash of what the AI recommended.
    pub ai_output_hash: Hash256,
    /// Hash of the final human decision.
    pub human_output_hash: Hash256,
    /// True when the AI and human outputs differ.
    pub divergence_detected: bool,
}

impl AiDelta {
    /// Compute an AiDelta, setting `divergence_detected` automatically.
    #[must_use]
    pub fn new(ai_output: &[u8], human_output: &[u8]) -> Self {
        let ai_output_hash = Hash256::digest(ai_output);
        let human_output_hash = Hash256::digest(human_output);
        let divergence_detected = ai_output_hash != human_output_hash;
        Self {
            ai_output_hash,
            human_output_hash,
            divergence_detected,
        }
    }
}

/// Structured metadata for FRE 702 / Daubert admissibility.
///
/// An AI inference without a completed Daubert checklist should be treated as
/// `AdmissibilityStatus::Inadmissible` pending review.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DaubertChecklist {
    /// The AI methodology is documented and reproducible.
    pub methodology_documented: bool,
    /// The methodology has been subjected to peer review or publication.
    pub peer_reviewable: bool,
    /// The known or potential error rate of the technique (None = unknown).
    pub known_error_rate: Option<String>,
    /// The technique is generally accepted in the relevant scientific community.
    pub generally_accepted: bool,
}

impl DaubertChecklist {
    /// Returns true if all required Daubert elements are satisfied.
    #[must_use]
    pub fn is_complete(&self) -> bool {
        self.methodology_documented
            && self.peer_reviewable
            && self
                .known_error_rate
                .as_ref()
                .is_some_and(|error_rate| !error_rate.trim().is_empty())
            && self.generally_accepted
    }
}

/// Fail-closed Daubert admissibility decision for an inference proof.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum DaubertAdmissibility {
    /// All provenance required for Daubert/FRE 702 review is present.
    Admissible,
    /// Required provenance is missing or invalid.
    Inadmissible { reason: String },
}

// ---------------------------------------------------------------------------
// InferenceProof
// ---------------------------------------------------------------------------

/// Proof that an inference was correctly executed.
///
/// The core fields (`model_commitment`, `input_hash`, `output_hash`, `proof`,
/// `verification_tag`) are always present and backward-compatible with
/// existing serialized proofs.
///
/// The provenance fields (`prompt_hash`, `human_attestation`, `ai_delta`,
/// `daubert_checklist`) are `Option<T>` with `serde(default)` so that
/// pre-existing serialized proofs continue to deserialize.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InferenceProof {
    /// The model commitment.
    pub model_commitment: ModelCommitment,
    /// Hash of the contextual input data (context window / user message).
    pub input_hash: Hash256,
    /// Hash of the output data.
    pub output_hash: Hash256,
    /// The cryptographic proof binding input -> model -> output.
    pub proof: Hash256,
    /// Auxiliary verification data.
    pub verification_tag: Hash256,

    // ---- LEG-007 provenance extensions (backward-compatible) ----
    /// Hash of the system/user prompt (distinct from `input_hash`).
    ///
    /// Separating prompt from context allows courts to assess whether the
    /// AI was directed toward a particular outcome.
    #[serde(default)]
    pub prompt_hash: Option<Hash256>,

    /// Signed human attestation: did the reviewer adopt, modify, or reject?
    #[serde(default)]
    pub human_attestation: Option<HumanAttestation>,

    /// Divergence record comparing AI recommendation to final human decision.
    #[serde(default)]
    pub ai_delta: Option<AiDelta>,

    /// Daubert admissibility checklist for FRE 702 compliance.
    #[serde(default)]
    pub daubert_checklist: Option<DaubertChecklist>,
}

impl InferenceProof {
    /// Return the fail-closed Daubert admissibility status for this proof.
    #[must_use]
    pub fn daubert_admissibility_status(&self) -> DaubertAdmissibility {
        if let Err(err) = crate::guard_unaudited("zkml::daubert_admissibility_status") {
            return DaubertAdmissibility::Inadmissible {
                reason: err.to_string(),
            };
        }

        if self.prompt_hash.is_none() {
            return DaubertAdmissibility::Inadmissible {
                reason: "prompt_hash is required for Daubert admissibility".into(),
            };
        }

        if !self.proof_integrity_valid() {
            return DaubertAdmissibility::Inadmissible {
                reason: "proof integrity check failed".into(),
            };
        }

        let Some(attestation) = &self.human_attestation else {
            return DaubertAdmissibility::Inadmissible {
                reason: "human_attestation is required for Daubert admissibility".into(),
            };
        };

        if !attestation.verify_for_inference(self) {
            return DaubertAdmissibility::Inadmissible {
                reason: "human_attestation signature failed verification".into(),
            };
        }

        if attestation.ai_recommendation_hash != self.output_hash {
            return DaubertAdmissibility::Inadmissible {
                reason: "human_attestation AI recommendation does not match proof output_hash"
                    .into(),
            };
        }

        let Some(ai_delta) = &self.ai_delta else {
            return DaubertAdmissibility::Inadmissible {
                reason: "ai_delta is required for Daubert admissibility".into(),
            };
        };

        if ai_delta.ai_output_hash != attestation.ai_recommendation_hash
            || ai_delta.human_output_hash != attestation.final_decision_hash
        {
            return DaubertAdmissibility::Inadmissible {
                reason: "ai_delta does not match human_attestation hashes".into(),
            };
        }

        let Some(checklist) = &self.daubert_checklist else {
            return DaubertAdmissibility::Inadmissible {
                reason: "daubert_checklist is required for Daubert admissibility".into(),
            };
        };

        if !checklist.is_complete() {
            return DaubertAdmissibility::Inadmissible {
                reason: "daubert_checklist is incomplete".into(),
            };
        }

        DaubertAdmissibility::Admissible
    }

    fn proof_integrity_valid(&self) -> bool {
        let model_hash = self.model_commitment.commitment_hash();
        let expected_proof =
            compute_inference_proof(&model_hash, &self.input_hash, &self.output_hash);
        let Ok(expected_tag) = compute_verification_tag(
            &model_hash,
            &self.input_hash,
            &self.output_hash,
            &self.proof,
            self.prompt_hash.as_ref(),
        ) else {
            return false;
        };

        constant_time_hash256_eq(&expected_proof, &self.proof)
            & constant_time_hash256_eq(&expected_tag, &self.verification_tag)
    }
}

// ---------------------------------------------------------------------------
// Prove
// ---------------------------------------------------------------------------

/// Generate a basic proof (backward-compatible, no provenance fields).
///
/// Equivalent to the previous API.  New callers should prefer
/// `prove_inference_with_provenance()`.
///
/// **Unaudited** — gated behind the `unaudited-pedagogical-proofs` feature.
pub fn prove_inference(
    model: &ModelCommitment,
    input: &[u8],
    output: &[u8],
) -> Result<InferenceProof> {
    crate::guard_unaudited("zkml::prove_inference")?;
    let input_hash = Hash256::digest(input);
    let output_hash = Hash256::digest(output);
    let model_hash = model.commitment_hash();

    // Compute the proof: a deterministic binding of model + input + output.
    // NOTE: In a production ZKML system this would execute the model inside a
    // ZK circuit (R1CS or STARK).  This hash-based binding is the MVP
    // implementation and is documented as such for Daubert disclosure purposes.
    let proof = compute_inference_proof(&model_hash, &input_hash, &output_hash);

    let verification_tag =
        compute_verification_tag(&model_hash, &input_hash, &output_hash, &proof, None)?;

    Ok(InferenceProof {
        model_commitment: model.clone(),
        input_hash,
        output_hash,
        proof,
        verification_tag,
        prompt_hash: None,
        human_attestation: None,
        ai_delta: None,
        daubert_checklist: None,
    })
}

/// Generate a proof with full LEG-007 provenance.
///
/// `prompt` is the system/user prompt (separate from `input` context data).
/// The resulting proof carries a distinct `prompt_hash` for Daubert disclosure.
///
/// **Unaudited** — gated behind the `unaudited-pedagogical-proofs` feature.
pub fn prove_inference_with_provenance(
    model: &ModelCommitment,
    prompt: &[u8],
    input: &[u8],
    output: &[u8],
) -> Result<InferenceProof> {
    // guard applied via the inner call
    let mut proof = prove_inference(model, input, output)?;
    let prompt_hash = Hash256::digest(prompt);
    proof.prompt_hash = Some(prompt_hash);
    let model_hash = model.commitment_hash();
    proof.verification_tag = compute_verification_tag(
        &model_hash,
        &proof.input_hash,
        &proof.output_hash,
        &proof.proof,
        Some(&prompt_hash),
    )?;
    Ok(proof)
}

/// Verify that an inference proof is valid.
///
/// This checks that the proof correctly binds the model commitment, input hash,
/// and output hash without needing the actual model or input.
///
/// **Unaudited** — gated behind the `unaudited-pedagogical-proofs` feature.
/// Returns `Err(UnauditedImplementation)` when the feature is disabled.
pub fn verify_inference(proof: &InferenceProof) -> Result<bool> {
    crate::guard_unaudited("zkml::verify_inference")?;
    let model_hash = proof.model_commitment.commitment_hash();

    // Recompute the expected proof
    let expected_proof =
        compute_inference_proof(&model_hash, &proof.input_hash, &proof.output_hash);

    let proof_ok = constant_time_hash256_eq(&expected_proof, &proof.proof);

    // Recompute and check the verification tag
    let expected_tag = compute_verification_tag(
        &model_hash,
        &proof.input_hash,
        &proof.output_hash,
        &proof.proof,
        proof.prompt_hash.as_ref(),
    )?;

    let tag_ok = constant_time_hash256_eq(&expected_tag, &proof.verification_tag);

    Ok(proof_ok & tag_ok)
}

// ---------------------------------------------------------------------------
// Internals
// ---------------------------------------------------------------------------

fn compute_inference_proof(
    model_hash: &Hash256,
    input_hash: &Hash256,
    output_hash: &Hash256,
) -> Hash256 {
    let mut hasher = blake3::Hasher::new();
    hasher.update(b"zkml:proof:");
    hasher.update(model_hash.as_bytes());
    hasher.update(input_hash.as_bytes());
    hasher.update(output_hash.as_bytes());
    Hash256::from_bytes(*hasher.finalize().as_bytes())
}

fn compute_verification_tag(
    model_hash: &Hash256,
    input_hash: &Hash256,
    output_hash: &Hash256,
    proof: &Hash256,
    prompt_hash: Option<&Hash256>,
) -> Result<Hash256> {
    if let Some(prompt_hash) = prompt_hash {
        let payload = InferenceVerificationTagPayload {
            domain: "exo.zkml.verification_tag.v2",
            model_hash: *model_hash,
            input_hash: *input_hash,
            output_hash: *output_hash,
            proof: *proof,
            prompt_hash: *prompt_hash,
        };
        return hash_structured(&payload).map_err(|err| {
            ProofError::InvalidProofFormat(format!(
                "zkML verification tag canonical encoding failed: {err}"
            ))
        });
    }

    let mut hasher = blake3::Hasher::new();
    hasher.update(b"zkml:verify:");
    hasher.update(model_hash.as_bytes());
    hasher.update(input_hash.as_bytes());
    hasher.update(output_hash.as_bytes());
    hasher.update(proof.as_bytes());
    Ok(Hash256::from_bytes(*hasher.finalize().as_bytes()))
}

#[derive(Serialize)]
struct InferenceVerificationTagPayload {
    domain: &'static str,
    model_hash: Hash256,
    input_hash: Hash256,
    output_hash: Hash256,
    proof: Hash256,
    prompt_hash: Hash256,
}

fn canonical_cbor_message<T: Serialize>(value: &T, label: &str) -> Result<Vec<u8>> {
    let mut encoded = Vec::new();
    ciborium::into_writer(value, &mut encoded).map_err(|err| {
        ProofError::InvalidProofFormat(format!("{label} canonical CBOR encoding failed: {err}"))
    })?;
    Ok(encoded)
}

fn constant_time_hash256_eq(left: &Hash256, right: &Hash256) -> bool {
    let mut diff = 0u8;
    for idx in 0..32 {
        diff |= left.as_bytes()[idx] ^ right.as_bytes()[idx];
    }
    diff == 0
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(all(test, feature = "unaudited-pedagogical-proofs"))]
mod tests {
    use exo_core::crypto;

    use super::*;

    fn make_model() -> ModelCommitment {
        ModelCommitment::new(b"transformer-v1", b"weights-blob-1234", 1)
    }

    // ---- original tests (backward compat) ----

    #[test]
    fn model_commitment_deterministic() {
        let m1 = ModelCommitment::new(b"arch", b"weights", 1);
        let m2 = ModelCommitment::new(b"arch", b"weights", 1);
        assert_eq!(m1, m2);
        assert_eq!(m1.commitment_hash(), m2.commitment_hash());
    }

    #[test]
    fn different_models_different_hashes() {
        let m1 = ModelCommitment::new(b"arch1", b"weights1", 1);
        let m2 = ModelCommitment::new(b"arch2", b"weights2", 1);
        assert_ne!(m1.commitment_hash(), m2.commitment_hash());
    }

    #[test]
    fn different_versions_different_hashes() {
        let m1 = ModelCommitment::new(b"arch", b"weights", 1);
        let m2 = ModelCommitment::new(b"arch", b"weights", 2);
        assert_ne!(m1.commitment_hash(), m2.commitment_hash());
    }

    #[test]
    fn prove_and_verify() {
        let model = make_model();
        let proof =
            prove_inference(&model, b"classify this image", b"cat: 0.95, dog: 0.05").unwrap();
        assert!(verify_inference(&proof).unwrap());
    }

    #[test]
    fn verify_fails_tampered_model() {
        let model = make_model();
        let mut tampered = prove_inference(&model, b"input", b"output").unwrap();
        tampered.model_commitment = ModelCommitment::new(b"evil-arch", b"evil-weights", 99);
        assert!(!verify_inference(&tampered).unwrap());
    }

    #[test]
    fn verify_fails_tampered_input() {
        let model = make_model();
        let mut tampered = prove_inference(&model, b"input", b"output").unwrap();
        tampered.input_hash = Hash256::digest(b"different-input");
        assert!(!verify_inference(&tampered).unwrap());
    }

    #[test]
    fn verify_fails_tampered_output() {
        let model = make_model();
        let mut tampered = prove_inference(&model, b"input", b"output").unwrap();
        tampered.output_hash = Hash256::digest(b"different-output");
        assert!(!verify_inference(&tampered).unwrap());
    }

    #[test]
    fn verify_fails_tampered_proof_field() {
        let model = make_model();
        let mut tampered = prove_inference(&model, b"input", b"output").unwrap();
        tampered.proof = Hash256::ZERO;
        assert!(!verify_inference(&tampered).unwrap());
    }

    #[test]
    fn verify_fails_tampered_tag() {
        let model = make_model();
        let mut tampered = prove_inference(&model, b"input", b"output").unwrap();
        tampered.verification_tag = Hash256::ZERO;
        assert!(!verify_inference(&tampered).unwrap());
    }

    #[test]
    fn verify_inference_uses_constant_time_hash_comparisons() {
        let source = include_str!("zkml.rs");
        let Some(verify_start) = source.find("pub fn verify_inference") else {
            panic!("verify_inference must exist");
        };
        let Some(internals_start) = source.find("// Internals") else {
            panic!("internals marker must exist");
        };
        let verify_source = &source[verify_start..internals_start];

        assert!(
            verify_source.contains("constant_time_hash256_eq"),
            "verify_inference must use the constant-time Hash256 comparator"
        );
        assert!(
            !verify_source.contains("expected_proof != proof.proof"),
            "proof comparison must not use variable-time PartialEq"
        );
        assert!(
            !verify_source.contains("expected_tag == proof.verification_tag"),
            "verification tag comparison must not use variable-time PartialEq"
        );
    }

    #[test]
    fn different_inputs_different_proofs() {
        let model = make_model();
        let p1 = prove_inference(&model, b"input1", b"output1").unwrap();
        let p2 = prove_inference(&model, b"input2", b"output2").unwrap();
        assert_ne!(p1.proof, p2.proof);
    }

    #[test]
    fn same_inputs_same_proof() {
        let model = make_model();
        let p1 = prove_inference(&model, b"input", b"output").unwrap();
        let p2 = prove_inference(&model, b"input", b"output").unwrap();
        assert_eq!(p1, p2);
    }

    #[test]
    fn proof_hides_model_input() {
        let model = make_model();
        let proof = prove_inference(&model, b"secret input", b"secret output").unwrap();
        assert_eq!(proof.input_hash, Hash256::digest(b"secret input"));
        assert_eq!(proof.output_hash, Hash256::digest(b"secret output"));
        assert_eq!(
            proof.model_commitment.architecture_hash,
            Hash256::digest(b"transformer-v1")
        );
    }

    #[test]
    fn empty_input_output() {
        let model = make_model();
        assert!(verify_inference(&prove_inference(&model, b"", b"").unwrap()).unwrap());
    }

    #[test]
    fn large_input_output() {
        let model = make_model();
        let proof = prove_inference(&model, &vec![0xABu8; 10_000], &vec![0xCDu8; 5_000]).unwrap();
        assert!(verify_inference(&proof).unwrap());
    }

    // ---- backward compat: old proofs (no Option fields) still deserialize ----

    #[test]
    fn backward_compat_deserialize_without_provenance_fields() {
        // A serialized proof without the new Option fields must deserialize with
        // all provenance fields set to None.
        let model = make_model();
        let proof = prove_inference(&model, b"input", b"output").unwrap();
        let json = serde_json::to_string(&proof).unwrap();
        let restored: InferenceProof = serde_json::from_str(&json).unwrap();
        assert!(restored.prompt_hash.is_none());
        assert!(restored.human_attestation.is_none());
        assert!(restored.ai_delta.is_none());
        assert!(restored.daubert_checklist.is_none());
    }

    // ---- LEG-007: prompt_hash distinct from input_hash ----

    #[test]
    fn zkml_proof_binds_model_and_prompt() {
        let model = make_model();
        let prompt = b"You are a board advisor. Recommend yes or no.";
        let context = b"Q4 revenue declined 15%.";
        let output = b"Recommend: reject the acquisition.";

        let proof = prove_inference_with_provenance(&model, prompt, context, output).unwrap();

        assert!(verify_inference(&proof).unwrap());
        assert!(proof.prompt_hash.is_some(), "prompt_hash must be present");
        // prompt_hash and input_hash must differ when prompt != context
        assert_ne!(
            proof.prompt_hash.unwrap(),
            proof.input_hash,
            "prompt_hash must be distinct from input_hash"
        );
        assert_eq!(proof.prompt_hash, Some(Hash256::digest(prompt)));
        assert_eq!(proof.input_hash, Hash256::digest(context));
    }

    #[test]
    fn prove_inference_with_provenance_verifies() {
        let model = make_model();
        let proof =
            prove_inference_with_provenance(&model, b"prompt", b"context", b"output").unwrap();
        assert!(verify_inference(&proof).unwrap());
    }

    #[test]
    fn verify_inference_rejects_swapped_prompt_provenance() {
        let model = make_model();
        let mut proof =
            prove_inference_with_provenance(&model, b"prompt", b"context", b"output").unwrap();

        proof.prompt_hash = Some(Hash256::digest(b"different prompt"));

        assert!(
            !verify_inference(&proof).unwrap(),
            "prompt provenance must be bound to the inference verification tag"
        );
    }

    // ---- LEG-007: HumanAttestation with Ed25519 signature ----

    fn make_attestation(
        decision: AttestationDecision,
    ) -> (HumanAttestation, exo_core::types::SecretKey) {
        let (public_key, secret_key) = crypto::generate_keypair();
        let reviewer_did = "did:exo:reviewer-alice".to_string();
        let ai_rec = Hash256::digest(b"ai says: approve");
        let final_dec = Hash256::digest(b"human says: reject");

        let msg = HumanAttestation::signing_message(&reviewer_did, &ai_rec, &final_dec, &decision)
            .unwrap();
        let signature = crypto::sign(&msg, &secret_key);

        let att = HumanAttestation {
            reviewer_did,
            reviewer_public_key: public_key,
            ai_recommendation_hash: ai_rec,
            final_decision_hash: final_dec,
            decision,
            signature,
        };
        (att, secret_key)
    }

    fn make_inference_attestation(
        proof: &InferenceProof,
        final_decision_hash: Hash256,
        decision: AttestationDecision,
    ) -> (HumanAttestation, exo_core::types::SecretKey) {
        let (public_key, secret_key) = crypto::generate_keypair();
        let reviewer_did = "did:exo:reviewer-alice".to_string();
        let msg = HumanAttestation::signing_message_for_inference(
            &reviewer_did,
            &proof.output_hash,
            &final_decision_hash,
            &decision,
            proof,
        )
        .unwrap();
        let signature = crypto::sign(&msg, &secret_key);

        let att = HumanAttestation {
            reviewer_did,
            reviewer_public_key: public_key,
            ai_recommendation_hash: proof.output_hash,
            final_decision_hash,
            decision,
            signature,
        };
        (att, secret_key)
    }

    #[test]
    fn human_attestation_signature_verifies() {
        let (att, _) = make_attestation(AttestationDecision::Rejected);
        assert!(
            att.verify_signature(),
            "Valid Ed25519 attestation must verify"
        );
    }

    #[test]
    fn human_attestation_signing_message_frames_reviewer_did() {
        let reviewer_did = "did:exo:reviewer-alice";
        let ai_rec = Hash256::digest(b"ai recommendation");
        let final_dec = Hash256::digest(b"final decision");

        let msg = HumanAttestation::signing_message(
            reviewer_did,
            &ai_rec,
            &final_dec,
            &AttestationDecision::Modified,
        )
        .unwrap();

        let domain = b"zkml:attestation:";
        assert!(msg.starts_with(domain));
        let did_len_start = domain.len();
        let did_len_end = did_len_start + 8;
        let did_len_bytes: [u8; 8] = match msg[did_len_start..did_len_end].try_into() {
            Ok(bytes) => bytes,
            Err(_) => panic!("DID length prefix must be eight bytes"),
        };
        let expected_len = match u64::try_from(reviewer_did.len()) {
            Ok(len) => len,
            Err(_) => panic!("reviewer DID length must fit in u64"),
        };
        assert_eq!(u64::from_le_bytes(did_len_bytes), expected_len);
        assert_eq!(
            &msg[did_len_end..did_len_end + reviewer_did.len()],
            reviewer_did.as_bytes()
        );

        let mut legacy = domain.to_vec();
        legacy.extend_from_slice(reviewer_did.as_bytes());
        legacy.extend_from_slice(ai_rec.as_bytes());
        legacy.extend_from_slice(final_dec.as_bytes());
        legacy.push(0x02);
        assert_ne!(msg, legacy, "new attestations must not use legacy framing");
    }

    #[test]
    fn human_attestation_signing_message_does_not_saturate_reviewer_did_length() {
        let production = include_str!("zkml.rs");
        let signing_message_section = production
            .split("pub fn signing_message")
            .nth(1)
            .expect("signing_message function must exist")
            .split("pub fn verify_signature")
            .next()
            .expect("verify_signature function must follow signing_message");

        assert!(
            !signing_message_section.contains("unwrap_or(u64::MAX)"),
            "canonical attestation framing must fail closed instead of saturating reviewer DID length"
        );
    }

    #[test]
    fn human_attestation_rejects_legacy_unframed_signature() {
        let (public_key, secret_key) = crypto::generate_keypair();
        let reviewer_did = "did:exo:reviewer-alice".to_string();
        let ai_rec = Hash256::digest(b"ai says: approve");
        let final_dec = Hash256::digest(b"human says: reject");

        let mut legacy = b"zkml:attestation:".to_vec();
        legacy.extend_from_slice(reviewer_did.as_bytes());
        legacy.extend_from_slice(ai_rec.as_bytes());
        legacy.extend_from_slice(final_dec.as_bytes());
        legacy.push(0x03);

        let signature = crypto::sign(&legacy, &secret_key);
        let att = HumanAttestation {
            reviewer_did,
            reviewer_public_key: public_key,
            ai_recommendation_hash: ai_rec,
            final_decision_hash: final_dec,
            decision: AttestationDecision::Rejected,
            signature,
        };

        assert!(
            !att.verify_signature(),
            "legacy unframed attestations must not verify"
        );
    }

    #[test]
    fn human_attestation_tampered_decision_fails() {
        let (mut att, _) = make_attestation(AttestationDecision::Rejected);
        // Swap the decision after signing — signature must fail.
        att.decision = AttestationDecision::Adopted;
        assert!(
            !att.verify_signature(),
            "Tampered decision must fail verification"
        );
    }

    #[test]
    fn human_attestation_tampered_recommendation_fails() {
        let (mut att, _) = make_attestation(AttestationDecision::Adopted);
        att.ai_recommendation_hash = Hash256::digest(b"different");
        assert!(!att.verify_signature());
    }

    #[test]
    fn human_attestation_required_for_ai_output() {
        // A proof without human_attestation is flagged as lacking oversight.
        let model = make_model();
        let proof = prove_inference(&model, b"input", b"output").unwrap();
        assert!(
            proof.human_attestation.is_none(),
            "Basic prove_inference must not fabricate attestation"
        );
        // Caller must explicitly attach an attestation; absence = no oversight record.
    }

    // ---- LEG-007: AiDelta ----

    #[test]
    fn ai_delta_detects_divergence() {
        let delta = AiDelta::new(b"ai says approve", b"human says reject");
        assert!(delta.divergence_detected);
        assert_ne!(delta.ai_output_hash, delta.human_output_hash);
    }

    #[test]
    fn ai_delta_no_divergence_when_same() {
        let delta = AiDelta::new(b"approve", b"approve");
        assert!(!delta.divergence_detected);
        assert_eq!(delta.ai_output_hash, delta.human_output_hash);
    }

    // ---- LEG-007: DaubertChecklist ----

    #[test]
    fn daubert_checklist_complete_when_all_satisfied() {
        let checklist = DaubertChecklist {
            methodology_documented: true,
            peer_reviewable: true,
            known_error_rate: Some("< 2%".into()),
            generally_accepted: true,
        };
        assert!(checklist.is_complete());
    }

    #[test]
    fn daubert_checklist_incomplete_without_methodology() {
        let checklist = DaubertChecklist {
            methodology_documented: false,
            peer_reviewable: true,
            known_error_rate: None,
            generally_accepted: true,
        };
        assert!(!checklist.is_complete());
    }

    #[test]
    fn daubert_checklist_incomplete_without_known_error_rate() {
        let checklist = DaubertChecklist {
            methodology_documented: true,
            peer_reviewable: true,
            known_error_rate: None,
            generally_accepted: true,
        };

        assert!(
            !checklist.is_complete(),
            "Daubert admissibility requires a known or potential error rate"
        );
    }

    #[test]
    fn daubert_checklist_completeness_all_fields_required() {
        // Each false flag independently makes the checklist incomplete.
        for (doc, peer, accepted) in [
            (false, true, true),
            (true, false, true),
            (true, true, false),
        ] {
            let c = DaubertChecklist {
                methodology_documented: doc,
                peer_reviewable: peer,
                known_error_rate: None,
                generally_accepted: accepted,
            };
            assert!(!c.is_complete(), "Incomplete checklist must not pass");
        }
    }

    #[test]
    fn zkml_source_exposes_fail_closed_daubert_admissibility_status() {
        let source = include_str!("zkml.rs");
        let production = source
            .split("// ---------------------------------------------------------------------------\n// Tests")
            .next()
            .expect("production section exists");

        assert!(
            production.contains("pub enum DaubertAdmissibility"),
            "InferenceProof needs a typed Daubert admissibility decision"
        );
        assert!(
            production.contains("pub fn daubert_admissibility_status(&self)"),
            "InferenceProof callers need a fail-closed admissibility status API"
        );
    }

    fn complete_daubert_checklist() -> DaubertChecklist {
        DaubertChecklist {
            methodology_documented: true,
            peer_reviewable: true,
            known_error_rate: Some("< 2%".into()),
            generally_accepted: true,
        }
    }

    fn admissible_inference_proof() -> InferenceProof {
        let model = make_model();
        let ai_output = b"ai says: approve";
        let human_output = b"human says: reject";
        let mut proof = prove_inference_with_provenance(
            &model,
            b"constitutionally bounded prompt",
            b"case context",
            ai_output,
        )
        .unwrap();
        let human_output_hash = Hash256::digest(human_output);
        let (attestation, _) =
            make_inference_attestation(&proof, human_output_hash, AttestationDecision::Rejected);
        proof.human_attestation = Some(attestation);
        proof.ai_delta = Some(AiDelta::new(ai_output, human_output));
        proof.daubert_checklist = Some(complete_daubert_checklist());
        proof
    }

    #[test]
    fn daubert_admissibility_accepts_complete_verified_provenance() {
        let proof = admissible_inference_proof();

        assert!(verify_inference(&proof).unwrap());
        assert_eq!(
            proof.daubert_admissibility_status(),
            DaubertAdmissibility::Admissible
        );
    }

    #[test]
    fn daubert_admissibility_rejects_replayed_attestation_with_swapped_prompt_hash() {
        let mut proof = admissible_inference_proof();
        assert_eq!(
            proof.daubert_admissibility_status(),
            DaubertAdmissibility::Admissible
        );

        proof.prompt_hash = Some(Hash256::digest(b"benign replacement prompt"));

        let status = proof.daubert_admissibility_status();
        assert!(
            matches!(status, DaubertAdmissibility::Inadmissible { ref reason } if reason.contains("integrity") || reason.contains("human_attestation")),
            "replayed provenance with a swapped prompt hash must be inadmissible, got {status:?}"
        );
    }

    #[test]
    fn daubert_admissibility_rejects_legacy_output_only_attestation() {
        let mut proof = admissible_inference_proof();
        let (legacy_attestation, _) = make_attestation(AttestationDecision::Rejected);
        proof.human_attestation = Some(legacy_attestation);

        let status = proof.daubert_admissibility_status();

        assert!(
            matches!(status, DaubertAdmissibility::Inadmissible { ref reason } if reason.contains("human_attestation")),
            "Daubert admissibility must reject attestations that do not bind proof provenance, got {status:?}"
        );
    }

    #[test]
    fn daubert_admissibility_rejects_missing_prompt_hash() {
        let mut proof = admissible_inference_proof();
        proof.prompt_hash = None;

        let status = proof.daubert_admissibility_status();

        assert!(
            matches!(status, DaubertAdmissibility::Inadmissible { ref reason } if reason.contains("prompt_hash")),
            "missing prompt hash must be inadmissible, got {status:?}"
        );
    }

    #[test]
    fn daubert_admissibility_rejects_invalid_human_attestation() {
        let mut proof = admissible_inference_proof();
        let attestation = proof
            .human_attestation
            .as_mut()
            .expect("test proof has attestation");
        attestation.decision = AttestationDecision::Adopted;

        let status = proof.daubert_admissibility_status();

        assert!(
            matches!(status, DaubertAdmissibility::Inadmissible { ref reason } if reason.contains("human_attestation")),
            "invalid attestation must be inadmissible, got {status:?}"
        );
    }

    #[test]
    fn daubert_admissibility_rejects_inconsistent_ai_delta() {
        let mut proof = admissible_inference_proof();
        let delta = proof.ai_delta.as_mut().expect("test proof has AI delta");
        delta.ai_output_hash = Hash256::digest(b"different AI output");

        let status = proof.daubert_admissibility_status();

        assert!(
            matches!(status, DaubertAdmissibility::Inadmissible { ref reason } if reason.contains("ai_delta")),
            "inconsistent AI delta must be inadmissible, got {status:?}"
        );
    }

    #[test]
    fn daubert_admissibility_rejects_incomplete_checklist() {
        let mut proof = admissible_inference_proof();
        proof.daubert_checklist = Some(DaubertChecklist {
            methodology_documented: true,
            peer_reviewable: true,
            known_error_rate: None,
            generally_accepted: true,
        });

        let status = proof.daubert_admissibility_status();

        assert!(
            matches!(status, DaubertAdmissibility::Inadmissible { ref reason } if reason.contains("daubert_checklist")),
            "incomplete checklist must be inadmissible, got {status:?}"
        );
    }

    // ---- zkml_tampered_model_detected (alias of existing test) ----

    #[test]
    fn zkml_tampered_model_detected() {
        let model = make_model();
        let proof = prove_inference(&model, b"input", b"output").unwrap();
        let mut tampered = proof;
        tampered.model_commitment.weights_hash = Hash256::digest(b"evil-weights");
        assert!(!verify_inference(&tampered).unwrap());
    }
}