Skip to main content

vela_protocol/domains/
lean_verification.rs

1//! v0.170: Lean theorem verification records. A `vlv_*` record
2//! is an Ed25519-signed attestation that a specific Lean module
3//! built cleanly under a specific toolchain, tying back to the
4//! v0.164 `vla_*` anchor that pins the source bytes.
5//!
6//! Substrate-honest framing: the substrate does NOT run lake
7//! itself. A trusted verifier (typically the project's GitHub
8//! Action) runs `lake build`, captures the verifier output,
9//! and signs the record. Consumers verify the signature
10//! against the verifier's published pubkey and accept the
11//! record only when the anchor's module_sha256 still matches
12//! the source. Two consumers reading the same vlv_* + anchor
13//! reach the same verdict.
14//!
15//! Composition: vla_* (v0.164) pins source bytes; vlv_*
16//! (v0.170) attests that those bytes built under a specific
17//! toolchain.
18
19use ed25519_dalek::SigningKey;
20use serde::{Deserialize, Serialize};
21use sha2::{Digest, Sha256};
22
23use crate::tcb_policy::AxiomVerdict;
24
25/// The frozen v0.1 schema. Records carrying this schema use the original
26/// nine-field preimage (no axiom block), so their historical Ed25519
27/// signatures stay valid forever. Never change the v0.1 preimage layout.
28pub const VERIFICATION_SCHEMA_V1: &str = "vela.lean_verification.v0.1";
29
30/// The current schema. v0.2 records append the axiom-hardening block
31/// (`tcb_id`, axioms, axiom verdict, kernel re-check, axioms-output hash) to
32/// the signed preimage. `build` always mints v0.2.
33pub const VERIFICATION_SCHEMA: &str = "vela.lean_verification.v0.2";
34
35/// Outcome of an external kernel re-check (lean4checker / Lean4Lean) over the
36/// compiled artifact, independent of the `lake build` elaboration.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
38#[serde(rename_all = "snake_case")]
39pub enum KernelRecheck {
40    /// An independent kernel checker re-validated the proof term.
41    Passed,
42    /// The independent checker rejected the proof term.
43    Failed,
44    /// No external re-check ran (e.g. no checker built for the toolchain).
45    NotRun,
46}
47
48impl KernelRecheck {
49    #[must_use]
50    pub fn as_str(self) -> &'static str {
51        match self {
52            Self::Passed => "passed",
53            Self::Failed => "failed",
54            Self::NotRun => "not_run",
55        }
56    }
57}
58
59#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
60pub struct LeanVerification {
61    pub schema: String,
62    pub verification_id: String,
63    /// The `vla_*` anchor this verification attests to.
64    pub anchor_id: String,
65    pub theorem_id: u32,
66    pub module: String,
67    /// The module_sha256 the anchor pinned; the verifier confirms
68    /// it matched at verification time.
69    pub module_sha256: String,
70    /// Lean toolchain pin (e.g. "leanprover/lean4:v4.29.1").
71    pub lean_toolchain: String,
72    /// Mathlib revision (commit or tag) the build used.
73    pub mathlib_revision: String,
74    /// sha256 over the verifier's full stdout+stderr+exit-code
75    /// canonical bytes. Lets a re-verifier confirm byte-for-byte
76    /// they got the same output.
77    pub verifier_output_hash: String,
78    /// "verified" | "failed" | "toolchain_mismatch" | "failed_axiom_check"
79    /// | "compiler_checked". `"verified"` requires `axiom_verdict =
80    /// kernel_clean` and `kernel_recheck != failed`.
81    pub status: String,
82    pub verified_at: String,
83    /// Free-form verifier identity (e.g. "github-action:vela-science/vela:verify-lean-bundle").
84    pub verifier_actor: String,
85    // --- axiom hardening (v0.2) ---
86    /// The `vtcb_` policy this verification was judged against. Empty on
87    /// legacy v0.1 records.
88    #[serde(default, skip_serializing_if = "String::is_empty")]
89    pub tcb_id: String,
90    /// The exact axiom names `#print axioms <decl>` reported, sorted. Empty
91    /// on legacy records (axioms unknown).
92    #[serde(default, skip_serializing_if = "Vec::is_empty")]
93    pub axioms: Vec<String>,
94    /// Verdict of `TcbPolicy::classify(axioms)`. None on legacy records.
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub axiom_verdict: Option<AxiomVerdict>,
97    /// Outcome of the external kernel re-check. None on legacy records.
98    #[serde(default, skip_serializing_if = "Option::is_none")]
99    pub kernel_recheck: Option<KernelRecheck>,
100    /// sha256 over the `#print axioms` stdout for this decl. Empty on legacy.
101    #[serde(default, skip_serializing_if = "String::is_empty")]
102    pub axioms_output_hash: String,
103    pub verifier_pubkey_hex: String,
104    pub signature_hex: String,
105}
106
107#[derive(Debug, Clone)]
108pub struct VerificationDraft {
109    pub anchor_id: String,
110    pub theorem_id: u32,
111    pub module: String,
112    pub module_sha256: String,
113    pub lean_toolchain: String,
114    pub mathlib_revision: String,
115    pub verifier_output_hash: String,
116    pub status: String,
117    pub verified_at: String,
118    pub verifier_actor: String,
119    // --- axiom hardening (v0.2); pass empty/None for an axiom-unknown record ---
120    pub tcb_id: String,
121    pub axioms: Vec<String>,
122    pub axiom_verdict: Option<AxiomVerdict>,
123    pub kernel_recheck: Option<KernelRecheck>,
124    pub axioms_output_hash: String,
125}
126
127impl LeanVerification {
128    pub fn build(draft: VerificationDraft, key: &SigningKey) -> Result<Self, String> {
129        if !draft.anchor_id.starts_with("vla_") {
130            return Err(format!(
131                "anchor_id must start with `vla_`, got `{}`",
132                draft.anchor_id
133            ));
134        }
135        if !matches!(
136            draft.status.as_str(),
137            "verified"
138                | "failed"
139                | "toolchain_mismatch"
140                | "failed_axiom_check"
141                | "compiler_checked"
142        ) {
143            return Err(format!(
144                "status must be one of verified|failed|toolchain_mismatch|failed_axiom_check|compiler_checked, got `{}`",
145                draft.status
146            ));
147        }
148        // `verified` is reserved for a kernel-clean axiom set whose external
149        // re-check did not fail. A compiler-trust / sorry proof cannot be
150        // minted as verified.
151        if draft.status == "verified" {
152            match draft.axiom_verdict {
153                Some(AxiomVerdict::KernelClean) => {}
154                Some(other) => {
155                    return Err(format!(
156                        "status `verified` requires axiom_verdict=kernel_clean, got `{}`",
157                        other.as_str()
158                    ));
159                }
160                None => {} // axioms unknown (legacy-style build); allowed but not asserting cleanliness
161            }
162            if draft.kernel_recheck == Some(KernelRecheck::Failed) {
163                return Err(
164                    "status `verified` cannot accompany a failed external kernel re-check"
165                        .to_string(),
166                );
167            }
168        }
169        if draft.verifier_output_hash.len() != 64
170            || !draft
171                .verifier_output_hash
172                .chars()
173                .all(|c| c.is_ascii_hexdigit())
174        {
175            return Err("verifier_output_hash must be 64 hex chars".to_string());
176        }
177        if draft.module_sha256.len() != 64
178            || !draft.module_sha256.chars().all(|c| c.is_ascii_hexdigit())
179        {
180            return Err("module_sha256 must be 64 hex chars".to_string());
181        }
182        let mut record = LeanVerification {
183            schema: VERIFICATION_SCHEMA.to_string(),
184            verification_id: String::new(),
185            anchor_id: draft.anchor_id,
186            theorem_id: draft.theorem_id,
187            module: draft.module,
188            module_sha256: draft.module_sha256,
189            lean_toolchain: draft.lean_toolchain,
190            mathlib_revision: draft.mathlib_revision,
191            verifier_output_hash: draft.verifier_output_hash,
192            status: draft.status,
193            verified_at: draft.verified_at,
194            verifier_actor: draft.verifier_actor,
195            tcb_id: draft.tcb_id,
196            axioms: draft.axioms,
197            axiom_verdict: draft.axiom_verdict,
198            kernel_recheck: draft.kernel_recheck,
199            axioms_output_hash: draft.axioms_output_hash,
200            verifier_pubkey_hex: hex::encode(key.verifying_key().to_bytes()),
201            signature_hex: String::new(),
202        };
203        let preimage = record.preimage_bytes();
204        record.signature_hex = hex::encode(crate::sign::sign_bytes(key, &preimage));
205        record.verification_id = record.derive_id();
206        Ok(record)
207    }
208
209    fn preimage_bytes(&self) -> Vec<u8> {
210        let mut out = Vec::new();
211        out.extend_from_slice(self.anchor_id.as_bytes());
212        out.push(b'|');
213        out.extend_from_slice(self.module.as_bytes());
214        out.push(b'|');
215        out.extend_from_slice(self.module_sha256.as_bytes());
216        out.push(b'|');
217        out.extend_from_slice(self.lean_toolchain.as_bytes());
218        out.push(b'|');
219        out.extend_from_slice(self.mathlib_revision.as_bytes());
220        out.push(b'|');
221        out.extend_from_slice(self.verifier_output_hash.as_bytes());
222        out.push(b'|');
223        out.extend_from_slice(self.status.as_bytes());
224        out.push(b'|');
225        out.extend_from_slice(self.verified_at.as_bytes());
226        out.push(b'|');
227        out.extend_from_slice(self.verifier_actor.as_bytes());
228        out.push(b'|');
229        out.extend_from_slice(self.verifier_pubkey_hex.as_bytes());
230        // v0.2+ appends the axiom-hardening block. A v0.1 record omits it
231        // entirely, so its preimage — and therefore its historical Ed25519
232        // signature and `vlv_` id — is byte-for-byte unchanged. The schema
233        // string is what selects the layout; never alter the v0.1 branch.
234        if self.schema != VERIFICATION_SCHEMA_V1 {
235            out.push(b'|');
236            out.extend_from_slice(self.tcb_id.as_bytes());
237            out.push(b'|');
238            out.extend_from_slice(self.axioms.join(",").as_bytes());
239            out.push(b'|');
240            out.extend_from_slice(
241                self.axiom_verdict
242                    .map(AxiomVerdict::as_str)
243                    .unwrap_or("")
244                    .as_bytes(),
245            );
246            out.push(b'|');
247            out.extend_from_slice(
248                self.kernel_recheck
249                    .map(KernelRecheck::as_str)
250                    .unwrap_or("")
251                    .as_bytes(),
252            );
253            out.push(b'|');
254            out.extend_from_slice(self.axioms_output_hash.as_bytes());
255        }
256        out
257    }
258
259    /// Map this verification's axiom result to the method integrity the gate
260    /// consumes (G5). A kernel-clean axiom set with no failed external
261    /// re-check is `Sound`; a forbidden/unlisted axiom or a failed re-check is
262    /// `Compromised`; an axiom-unknown (legacy) record is `Unattested`. The
263    /// gate never imports Lean types — only this `MethodIntegrity`.
264    #[must_use]
265    pub fn to_attachment_integrity(&self) -> crate::verifier_attachment::MethodIntegrity {
266        use crate::verifier_attachment::MethodIntegrity;
267        if self.kernel_recheck == Some(KernelRecheck::Failed) {
268            return MethodIntegrity::Compromised;
269        }
270        match self.axiom_verdict {
271            Some(AxiomVerdict::KernelClean) => MethodIntegrity::Sound,
272            Some(_) => MethodIntegrity::Compromised,
273            None => MethodIntegrity::Unattested,
274        }
275    }
276
277    fn derive_id(&self) -> String {
278        let mut hasher = Sha256::new();
279        hasher.update(self.preimage_bytes());
280        hasher.update(b"|");
281        hasher.update(self.signature_hex.as_bytes());
282        format!("vlv_{}", &hex::encode(hasher.finalize())[..16])
283    }
284
285    /// Verify signature and id derivation. Returns Ok(()) iff
286    /// both the Ed25519 signature is valid under the declared
287    /// pubkey AND the verification_id was derived from the
288    /// signed body.
289    pub fn verify(&self) -> Result<(), String> {
290        if !crate::sign::verify_action_signature(
291            &self.preimage_bytes(),
292            &self.signature_hex,
293            &self.verifier_pubkey_hex,
294        )? {
295            return Err(
296                "lean verification signature does not verify under the declared pubkey".to_string(),
297            );
298        }
299        let rederived = self.derive_id();
300        if rederived != self.verification_id {
301            return Err(format!(
302                "verification_id mismatch: declared {}, rebuilt {}",
303                self.verification_id, rederived
304            ));
305        }
306        Ok(())
307    }
308}
309
310#[cfg(test)]
311mod tests {
312    use super::*;
313    use rand::rngs::OsRng;
314
315    fn key() -> SigningKey {
316        SigningKey::generate(&mut OsRng)
317    }
318
319    fn ok_draft() -> VerificationDraft {
320        VerificationDraft {
321            anchor_id: "vla_abc123def4567890".to_string(),
322            theorem_id: 1,
323            module: "Vela/Log.lean".to_string(),
324            module_sha256: "a".repeat(64),
325            lean_toolchain: "leanprover/lean4:v4.29.1".to_string(),
326            mathlib_revision: "v4.29.1".to_string(),
327            verifier_output_hash: "b".repeat(64),
328            status: "verified".to_string(),
329            verified_at: "2026-05-11T00:00:00Z".to_string(),
330            verifier_actor: "github-action:test".to_string(),
331            tcb_id: "vtcb_0123456789abcdef".to_string(),
332            axioms: vec!["Classical.choice".to_string(), "propext".to_string()],
333            axiom_verdict: Some(AxiomVerdict::KernelClean),
334            kernel_recheck: Some(KernelRecheck::Passed),
335            axioms_output_hash: "d".repeat(64),
336        }
337    }
338
339    /// Hand-build a v0.1 record exactly as the pre-axiom builder would have:
340    /// schema v0.1, no axiom fields, signed over the original 10-field
341    /// preimage. Used to prove the migration preserves historical signatures.
342    fn legacy_v01_record(key: &SigningKey) -> LeanVerification {
343        let mut r = LeanVerification {
344            schema: VERIFICATION_SCHEMA_V1.to_string(),
345            verification_id: String::new(),
346            anchor_id: "vla_abc123def4567890".to_string(),
347            theorem_id: 1,
348            module: "Vela/Log.lean".to_string(),
349            module_sha256: "a".repeat(64),
350            lean_toolchain: "leanprover/lean4:v4.29.1".to_string(),
351            mathlib_revision: "v4.29.1".to_string(),
352            verifier_output_hash: "b".repeat(64),
353            status: "verified".to_string(),
354            verified_at: "2026-05-11T00:00:00Z".to_string(),
355            verifier_actor: "github-action:test".to_string(),
356            tcb_id: String::new(),
357            axioms: vec![],
358            axiom_verdict: None,
359            kernel_recheck: None,
360            axioms_output_hash: String::new(),
361            verifier_pubkey_hex: hex::encode(key.verifying_key().to_bytes()),
362            signature_hex: String::new(),
363        };
364        let preimage = r.preimage_bytes();
365        r.signature_hex = hex::encode(crate::sign::sign_bytes(key, &preimage));
366        r.verification_id = r.derive_id();
367        r
368    }
369
370    #[test]
371    fn builds_signs_verifies() {
372        let r = LeanVerification::build(ok_draft(), &key()).expect("build");
373        assert!(r.verification_id.starts_with("vlv_"));
374        assert_eq!(r.schema, VERIFICATION_SCHEMA); // v0.2
375        r.verify().expect("verify");
376    }
377
378    #[test]
379    fn v01_record_still_verifies_under_v02_schema() {
380        // The migration guarantee: a record minted before the axiom block
381        // existed still verifies, and its preimage omits the v0.2 block
382        // byte-for-byte (so its historical signature/id are unchanged).
383        let k = key();
384        let r = legacy_v01_record(&k);
385        r.verify().expect("legacy v0.1 record must still verify");
386
387        let expected_old = format!(
388            "{}|{}|{}|{}|{}|{}|{}|{}|{}|{}",
389            r.anchor_id,
390            r.module,
391            r.module_sha256,
392            r.lean_toolchain,
393            r.mathlib_revision,
394            r.verifier_output_hash,
395            r.status,
396            r.verified_at,
397            r.verifier_actor,
398            r.verifier_pubkey_hex,
399        );
400        assert_eq!(
401            r.preimage_bytes(),
402            expected_old.as_bytes(),
403            "v0.1 preimage must equal the original 10-field layout (no axiom block)"
404        );
405    }
406
407    #[test]
408    fn axiom_fields_enter_preimage() {
409        // Flipping an axiom field on a signed v0.2 record breaks verify(),
410        // proving the axiom result is covered by the signature.
411        let mut r = LeanVerification::build(ok_draft(), &key()).expect("build");
412        assert!(r.verify().is_ok());
413        r.axiom_verdict = Some(AxiomVerdict::ForbiddenAxiom);
414        assert!(
415            r.verify().is_err(),
416            "axiom_verdict must be inside the signed preimage"
417        );
418    }
419
420    #[test]
421    fn verified_status_requires_kernel_clean() {
422        let mut d = ok_draft();
423        d.axiom_verdict = Some(AxiomVerdict::ForbiddenAxiom);
424        // status stays "verified" but verdict is forbidden -> build must reject
425        assert!(LeanVerification::build(d, &key()).is_err());
426    }
427
428    #[test]
429    fn compiler_checked_status_is_valid() {
430        let mut d = ok_draft();
431        d.status = "compiler_checked".to_string();
432        d.axiom_verdict = Some(AxiomVerdict::ForbiddenAxiom);
433        d.axioms = vec!["Lean.ofReduceBool".to_string()];
434        let r = LeanVerification::build(d, &key()).expect("compiler_checked builds");
435        r.verify().expect("verify");
436        assert_eq!(
437            r.to_attachment_integrity(),
438            crate::verifier_attachment::MethodIntegrity::Compromised
439        );
440    }
441
442    #[test]
443    fn integrity_mapping_is_sound_for_kernel_clean() {
444        let r = LeanVerification::build(ok_draft(), &key()).expect("build");
445        assert_eq!(
446            r.to_attachment_integrity(),
447            crate::verifier_attachment::MethodIntegrity::Sound
448        );
449    }
450
451    /// The A6 reject vector, end to end: a `native_decide` Lean record (the
452    /// flagship Sidon cert's shape) becomes a `compiler_checked` /
453    /// `Compromised` attachment that the gate excludes, so it can never carry
454    /// a finding to `Verified` through the Lean leg — only the independent
455    /// Sound method counts.
456    #[test]
457    fn native_decide_record_cannot_gate_verified_end_to_end() {
458        use crate::verifier_attachment::{
459            AdversarialProbe, AttachmentDraft, AttachmentOutcome, GateStatus, MatchToClaim,
460            MethodIntegrity, ProbeKind, ProbeResult, VerifierAttachment, VerifierMethod,
461            claim_digest, derive_gate_status,
462        };
463
464        // 1. The native_decide Lean record tiers as compiler_checked.
465        let mut d = ok_draft();
466        d.status = "compiler_checked".to_string();
467        d.axiom_verdict = Some(AxiomVerdict::ForbiddenAxiom);
468        d.axioms = vec![
469            "Lean.ofReduceBool".to_string(),
470            "Lean.trustCompiler".to_string(),
471        ];
472        let lean_rec = LeanVerification::build(d, &key()).expect("build compiler_checked");
473        assert_eq!(
474            lean_rec.to_attachment_integrity(),
475            MethodIntegrity::Compromised
476        );
477
478        let digest = claim_digest("a(8) >= 33 (OEIS A309370)");
479        let probe = AdversarialProbe {
480            kind: ProbeKind::CounterexampleSearch,
481            result: ProbeResult::Survived,
482            note: String::new(),
483            evidence_root: String::new(),
484        };
485        let mk = |method, solver: &str, indep: Vec<String>| {
486            VerifierAttachment::build(AttachmentDraft {
487                target: "vf_0123456789abcdef".to_string(),
488                claim_digest: digest.clone(),
489                verifier_method: method,
490                solver_id: solver.to_string(),
491                independent_of: indep,
492                match_to_claim: MatchToClaim {
493                    matches: true,
494                    checker_actor: "ci".to_string(),
495                },
496                adversarial_probes: vec![probe.clone()],
497                outcome: AttachmentOutcome::Passed,
498                verifier_actor: "ci".to_string(),
499                note: String::new(),
500            })
501            .unwrap()
502        };
503
504        // 2. The Lean attachment carries the compromised integrity; the Rust
505        //    frozen verifier is the Sound method.
506        let lean_att = mk(VerifierMethod::LeanKernel, "lean4@4.29.1", vec![])
507            .with_method_integrity(lean_rec.to_attachment_integrity())
508            .unwrap();
509        let rust_att = mk(
510            VerifierMethod::ComputationalSearch,
511            "vela-verify",
512            vec![lean_att.id.clone()],
513        )
514        .with_method_integrity(MethodIntegrity::Sound)
515        .unwrap();
516
517        // Only one SOUND matched attachment remains -> G1 unmet, G5 explains
518        // the exclusion. Never Verified on a native_decide proof.
519        let outcome = derive_gate_status(&digest, &[lean_att, rust_att]);
520        assert_eq!(outcome.status, GateStatus::NeedsVerification);
521        assert!(outcome.reasons.iter().any(|r| r.starts_with("G5")));
522    }
523
524    #[test]
525    fn tampered_body_fails_verify() {
526        let mut r = LeanVerification::build(ok_draft(), &key()).expect("build");
527        r.module_sha256 = "c".repeat(64);
528        assert!(r.verify().is_err());
529    }
530
531    #[test]
532    fn bad_status_rejected() {
533        let mut d = ok_draft();
534        d.status = "maybe".to_string();
535        assert!(LeanVerification::build(d, &key()).is_err());
536    }
537
538    #[test]
539    fn bad_hash_length_rejected() {
540        let mut d = ok_draft();
541        d.verifier_output_hash = "short".to_string();
542        assert!(LeanVerification::build(d, &key()).is_err());
543    }
544
545    #[test]
546    fn roundtrips_through_json() {
547        let r = LeanVerification::build(ok_draft(), &key()).expect("build");
548        let s = serde_json::to_string(&r).expect("ser");
549        let back: LeanVerification = serde_json::from_str(&s).expect("de");
550        assert_eq!(r, back);
551        back.verify().expect("verify after roundtrip");
552    }
553}