1use ed25519_dalek::SigningKey;
20use serde::{Deserialize, Serialize};
21use sha2::{Digest, Sha256};
22
23use crate::tcb_policy::AxiomVerdict;
24
25pub const VERIFICATION_SCHEMA_V1: &str = "vela.lean_verification.v0.1";
29
30pub const VERIFICATION_SCHEMA: &str = "vela.lean_verification.v0.2";
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
38#[serde(rename_all = "snake_case")]
39pub enum KernelRecheck {
40 Passed,
42 Failed,
44 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 pub anchor_id: String,
65 pub theorem_id: u32,
66 pub module: String,
67 pub module_sha256: String,
70 pub lean_toolchain: String,
72 pub mathlib_revision: String,
74 pub verifier_output_hash: String,
78 pub status: String,
82 pub verified_at: String,
83 pub verifier_actor: String,
85 #[serde(default, skip_serializing_if = "String::is_empty")]
89 pub tcb_id: String,
90 #[serde(default, skip_serializing_if = "Vec::is_empty")]
93 pub axioms: Vec<String>,
94 #[serde(default, skip_serializing_if = "Option::is_none")]
96 pub axiom_verdict: Option<AxiomVerdict>,
97 #[serde(default, skip_serializing_if = "Option::is_none")]
99 pub kernel_recheck: Option<KernelRecheck>,
100 #[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 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 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 => {} }
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 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 #[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 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 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); r.verify().expect("verify");
376 }
377
378 #[test]
379 fn v01_record_still_verifies_under_v02_schema() {
380 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 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 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 #[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 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 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 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}