use ed25519_dalek::SigningKey;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use crate::tcb_policy::AxiomVerdict;
pub const VERIFICATION_SCHEMA_V1: &str = "vela.lean_verification.v0.1";
pub const VERIFICATION_SCHEMA: &str = "vela.lean_verification.v0.2";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum KernelRecheck {
Passed,
Failed,
NotRun,
}
impl KernelRecheck {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Passed => "passed",
Self::Failed => "failed",
Self::NotRun => "not_run",
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct LeanVerification {
pub schema: String,
pub verification_id: String,
pub anchor_id: String,
pub theorem_id: u32,
pub module: String,
pub module_sha256: String,
pub lean_toolchain: String,
pub mathlib_revision: String,
pub verifier_output_hash: String,
pub status: String,
pub verified_at: String,
pub verifier_actor: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub tcb_id: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub axioms: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub axiom_verdict: Option<AxiomVerdict>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kernel_recheck: Option<KernelRecheck>,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub axioms_output_hash: String,
pub verifier_pubkey_hex: String,
pub signature_hex: String,
}
#[derive(Debug, Clone)]
pub struct VerificationDraft {
pub anchor_id: String,
pub theorem_id: u32,
pub module: String,
pub module_sha256: String,
pub lean_toolchain: String,
pub mathlib_revision: String,
pub verifier_output_hash: String,
pub status: String,
pub verified_at: String,
pub verifier_actor: String,
pub tcb_id: String,
pub axioms: Vec<String>,
pub axiom_verdict: Option<AxiomVerdict>,
pub kernel_recheck: Option<KernelRecheck>,
pub axioms_output_hash: String,
}
impl LeanVerification {
pub fn build(draft: VerificationDraft, key: &SigningKey) -> Result<Self, String> {
if !draft.anchor_id.starts_with("vla_") {
return Err(format!(
"anchor_id must start with `vla_`, got `{}`",
draft.anchor_id
));
}
if !matches!(
draft.status.as_str(),
"verified"
| "failed"
| "toolchain_mismatch"
| "failed_axiom_check"
| "compiler_checked"
) {
return Err(format!(
"status must be one of verified|failed|toolchain_mismatch|failed_axiom_check|compiler_checked, got `{}`",
draft.status
));
}
if draft.status == "verified" {
match draft.axiom_verdict {
Some(AxiomVerdict::KernelClean) => {}
Some(other) => {
return Err(format!(
"status `verified` requires axiom_verdict=kernel_clean, got `{}`",
other.as_str()
));
}
None => {} }
if draft.kernel_recheck == Some(KernelRecheck::Failed) {
return Err(
"status `verified` cannot accompany a failed external kernel re-check"
.to_string(),
);
}
}
if draft.verifier_output_hash.len() != 64
|| !draft
.verifier_output_hash
.chars()
.all(|c| c.is_ascii_hexdigit())
{
return Err("verifier_output_hash must be 64 hex chars".to_string());
}
if draft.module_sha256.len() != 64
|| !draft.module_sha256.chars().all(|c| c.is_ascii_hexdigit())
{
return Err("module_sha256 must be 64 hex chars".to_string());
}
let mut record = LeanVerification {
schema: VERIFICATION_SCHEMA.to_string(),
verification_id: String::new(),
anchor_id: draft.anchor_id,
theorem_id: draft.theorem_id,
module: draft.module,
module_sha256: draft.module_sha256,
lean_toolchain: draft.lean_toolchain,
mathlib_revision: draft.mathlib_revision,
verifier_output_hash: draft.verifier_output_hash,
status: draft.status,
verified_at: draft.verified_at,
verifier_actor: draft.verifier_actor,
tcb_id: draft.tcb_id,
axioms: draft.axioms,
axiom_verdict: draft.axiom_verdict,
kernel_recheck: draft.kernel_recheck,
axioms_output_hash: draft.axioms_output_hash,
verifier_pubkey_hex: hex::encode(key.verifying_key().to_bytes()),
signature_hex: String::new(),
};
let preimage = record.preimage_bytes();
record.signature_hex = hex::encode(crate::sign::sign_bytes(key, &preimage));
record.verification_id = record.derive_id();
Ok(record)
}
fn preimage_bytes(&self) -> Vec<u8> {
let mut out = Vec::new();
out.extend_from_slice(self.anchor_id.as_bytes());
out.push(b'|');
out.extend_from_slice(self.module.as_bytes());
out.push(b'|');
out.extend_from_slice(self.module_sha256.as_bytes());
out.push(b'|');
out.extend_from_slice(self.lean_toolchain.as_bytes());
out.push(b'|');
out.extend_from_slice(self.mathlib_revision.as_bytes());
out.push(b'|');
out.extend_from_slice(self.verifier_output_hash.as_bytes());
out.push(b'|');
out.extend_from_slice(self.status.as_bytes());
out.push(b'|');
out.extend_from_slice(self.verified_at.as_bytes());
out.push(b'|');
out.extend_from_slice(self.verifier_actor.as_bytes());
out.push(b'|');
out.extend_from_slice(self.verifier_pubkey_hex.as_bytes());
if self.schema != VERIFICATION_SCHEMA_V1 {
out.push(b'|');
out.extend_from_slice(self.tcb_id.as_bytes());
out.push(b'|');
out.extend_from_slice(self.axioms.join(",").as_bytes());
out.push(b'|');
out.extend_from_slice(
self.axiom_verdict
.map(AxiomVerdict::as_str)
.unwrap_or("")
.as_bytes(),
);
out.push(b'|');
out.extend_from_slice(
self.kernel_recheck
.map(KernelRecheck::as_str)
.unwrap_or("")
.as_bytes(),
);
out.push(b'|');
out.extend_from_slice(self.axioms_output_hash.as_bytes());
}
out
}
#[must_use]
pub fn to_attachment_integrity(&self) -> crate::verifier_attachment::MethodIntegrity {
use crate::verifier_attachment::MethodIntegrity;
if self.kernel_recheck == Some(KernelRecheck::Failed) {
return MethodIntegrity::Compromised;
}
match self.axiom_verdict {
Some(AxiomVerdict::KernelClean) => MethodIntegrity::Sound,
Some(_) => MethodIntegrity::Compromised,
None => MethodIntegrity::Unattested,
}
}
fn derive_id(&self) -> String {
let mut hasher = Sha256::new();
hasher.update(self.preimage_bytes());
hasher.update(b"|");
hasher.update(self.signature_hex.as_bytes());
format!("vlv_{}", &hex::encode(hasher.finalize())[..16])
}
pub fn verify(&self) -> Result<(), String> {
if !crate::sign::verify_action_signature(
&self.preimage_bytes(),
&self.signature_hex,
&self.verifier_pubkey_hex,
)? {
return Err(
"lean verification signature does not verify under the declared pubkey".to_string(),
);
}
let rederived = self.derive_id();
if rederived != self.verification_id {
return Err(format!(
"verification_id mismatch: declared {}, rebuilt {}",
self.verification_id, rederived
));
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use rand::rngs::OsRng;
fn key() -> SigningKey {
SigningKey::generate(&mut OsRng)
}
fn ok_draft() -> VerificationDraft {
VerificationDraft {
anchor_id: "vla_abc123def4567890".to_string(),
theorem_id: 1,
module: "Vela/Log.lean".to_string(),
module_sha256: "a".repeat(64),
lean_toolchain: "leanprover/lean4:v4.29.1".to_string(),
mathlib_revision: "v4.29.1".to_string(),
verifier_output_hash: "b".repeat(64),
status: "verified".to_string(),
verified_at: "2026-05-11T00:00:00Z".to_string(),
verifier_actor: "github-action:test".to_string(),
tcb_id: "vtcb_0123456789abcdef".to_string(),
axioms: vec!["Classical.choice".to_string(), "propext".to_string()],
axiom_verdict: Some(AxiomVerdict::KernelClean),
kernel_recheck: Some(KernelRecheck::Passed),
axioms_output_hash: "d".repeat(64),
}
}
fn legacy_v01_record(key: &SigningKey) -> LeanVerification {
let mut r = LeanVerification {
schema: VERIFICATION_SCHEMA_V1.to_string(),
verification_id: String::new(),
anchor_id: "vla_abc123def4567890".to_string(),
theorem_id: 1,
module: "Vela/Log.lean".to_string(),
module_sha256: "a".repeat(64),
lean_toolchain: "leanprover/lean4:v4.29.1".to_string(),
mathlib_revision: "v4.29.1".to_string(),
verifier_output_hash: "b".repeat(64),
status: "verified".to_string(),
verified_at: "2026-05-11T00:00:00Z".to_string(),
verifier_actor: "github-action:test".to_string(),
tcb_id: String::new(),
axioms: vec![],
axiom_verdict: None,
kernel_recheck: None,
axioms_output_hash: String::new(),
verifier_pubkey_hex: hex::encode(key.verifying_key().to_bytes()),
signature_hex: String::new(),
};
let preimage = r.preimage_bytes();
r.signature_hex = hex::encode(crate::sign::sign_bytes(key, &preimage));
r.verification_id = r.derive_id();
r
}
#[test]
fn builds_signs_verifies() {
let r = LeanVerification::build(ok_draft(), &key()).expect("build");
assert!(r.verification_id.starts_with("vlv_"));
assert_eq!(r.schema, VERIFICATION_SCHEMA); r.verify().expect("verify");
}
#[test]
fn v01_record_still_verifies_under_v02_schema() {
let k = key();
let r = legacy_v01_record(&k);
r.verify().expect("legacy v0.1 record must still verify");
let expected_old = format!(
"{}|{}|{}|{}|{}|{}|{}|{}|{}|{}",
r.anchor_id,
r.module,
r.module_sha256,
r.lean_toolchain,
r.mathlib_revision,
r.verifier_output_hash,
r.status,
r.verified_at,
r.verifier_actor,
r.verifier_pubkey_hex,
);
assert_eq!(
r.preimage_bytes(),
expected_old.as_bytes(),
"v0.1 preimage must equal the original 10-field layout (no axiom block)"
);
}
#[test]
fn axiom_fields_enter_preimage() {
let mut r = LeanVerification::build(ok_draft(), &key()).expect("build");
assert!(r.verify().is_ok());
r.axiom_verdict = Some(AxiomVerdict::ForbiddenAxiom);
assert!(
r.verify().is_err(),
"axiom_verdict must be inside the signed preimage"
);
}
#[test]
fn verified_status_requires_kernel_clean() {
let mut d = ok_draft();
d.axiom_verdict = Some(AxiomVerdict::ForbiddenAxiom);
assert!(LeanVerification::build(d, &key()).is_err());
}
#[test]
fn compiler_checked_status_is_valid() {
let mut d = ok_draft();
d.status = "compiler_checked".to_string();
d.axiom_verdict = Some(AxiomVerdict::ForbiddenAxiom);
d.axioms = vec!["Lean.ofReduceBool".to_string()];
let r = LeanVerification::build(d, &key()).expect("compiler_checked builds");
r.verify().expect("verify");
assert_eq!(
r.to_attachment_integrity(),
crate::verifier_attachment::MethodIntegrity::Compromised
);
}
#[test]
fn integrity_mapping_is_sound_for_kernel_clean() {
let r = LeanVerification::build(ok_draft(), &key()).expect("build");
assert_eq!(
r.to_attachment_integrity(),
crate::verifier_attachment::MethodIntegrity::Sound
);
}
#[test]
fn native_decide_record_cannot_gate_verified_end_to_end() {
use crate::verifier_attachment::{
AdversarialProbe, AttachmentDraft, AttachmentOutcome, GateStatus, MatchToClaim,
MethodIntegrity, ProbeKind, ProbeResult, VerifierAttachment, VerifierMethod,
claim_digest, derive_gate_status,
};
let mut d = ok_draft();
d.status = "compiler_checked".to_string();
d.axiom_verdict = Some(AxiomVerdict::ForbiddenAxiom);
d.axioms = vec![
"Lean.ofReduceBool".to_string(),
"Lean.trustCompiler".to_string(),
];
let lean_rec = LeanVerification::build(d, &key()).expect("build compiler_checked");
assert_eq!(
lean_rec.to_attachment_integrity(),
MethodIntegrity::Compromised
);
let digest = claim_digest("a(8) >= 33 (OEIS A309370)");
let probe = AdversarialProbe {
kind: ProbeKind::CounterexampleSearch,
result: ProbeResult::Survived,
note: String::new(),
evidence_root: String::new(),
};
let mk = |method, solver: &str, indep: Vec<String>| {
VerifierAttachment::build(AttachmentDraft {
target: "vf_0123456789abcdef".to_string(),
claim_digest: digest.clone(),
verifier_method: method,
solver_id: solver.to_string(),
independent_of: indep,
match_to_claim: MatchToClaim {
matches: true,
checker_actor: "ci".to_string(),
},
adversarial_probes: vec![probe.clone()],
outcome: AttachmentOutcome::Passed,
verifier_actor: "ci".to_string(),
note: String::new(),
})
.unwrap()
};
let lean_att = mk(VerifierMethod::LeanKernel, "lean4@4.29.1", vec![])
.with_method_integrity(lean_rec.to_attachment_integrity())
.unwrap();
let rust_att = mk(
VerifierMethod::ComputationalSearch,
"vela-verify",
vec![lean_att.id.clone()],
)
.with_method_integrity(MethodIntegrity::Sound)
.unwrap();
let outcome = derive_gate_status(&digest, &[lean_att, rust_att]);
assert_eq!(outcome.status, GateStatus::NeedsVerification);
assert!(outcome.reasons.iter().any(|r| r.starts_with("G5")));
}
#[test]
fn tampered_body_fails_verify() {
let mut r = LeanVerification::build(ok_draft(), &key()).expect("build");
r.module_sha256 = "c".repeat(64);
assert!(r.verify().is_err());
}
#[test]
fn bad_status_rejected() {
let mut d = ok_draft();
d.status = "maybe".to_string();
assert!(LeanVerification::build(d, &key()).is_err());
}
#[test]
fn bad_hash_length_rejected() {
let mut d = ok_draft();
d.verifier_output_hash = "short".to_string();
assert!(LeanVerification::build(d, &key()).is_err());
}
#[test]
fn roundtrips_through_json() {
let r = LeanVerification::build(ok_draft(), &key()).expect("build");
let s = serde_json::to_string(&r).expect("ser");
let back: LeanVerification = serde_json::from_str(&s).expect("de");
assert_eq!(r, back);
back.verify().expect("verify after roundtrip");
}
}