Skip to main content

aver_cert/
kernels.rs

1//! The paranoid kernel set: every proof checker the pinned Lean release ships,
2//! run over one `leanexport` of the checked module closure.
3//!
4//! The list and the argument shapes are the ones `lake check --paranoid`
5//! uses (Lake's `Check.bundledKernels` plus Lean's own `leanchecker
6//! --from-export`). `lake check` itself is not used: it needs a Linux `bwrap`
7//! sandbox, it exports every default target of the package rather than one
8//! module closure, and it rejects the whole run on any axiom outside the
9//! standard three, where a certificate or proof project reports such a claim
10//! as not credited and keeps judging the rest.
11//!
12//! Each kernel's exit status is its verdict. A kernel that is missing, cannot
13//! start, or exits nonzero fails the run; no kernel is ever skipped.
14//!
15//! Dependency-free on purpose: the certificate verifier and `aver proof`
16//! both read this one list.
17
18/// Lean's standard axioms, the set every kernel is told is permitted. Axioms
19/// outside it are reported by the callers' own audits, not here.
20pub const PERMITTED_AXIOMS: [&str; 3] = ["propext", "Classical.choice", "Quot.sound"];
21
22/// The toolchain binary that writes the NDJSON export the kernels read.
23pub const EXPORTER: &str = "leanexport";
24
25/// How a kernel is told where the export is.
26#[derive(Clone, Copy, Debug, Eq, PartialEq)]
27pub enum KernelInput {
28    /// The export path is the last argument.
29    ExportPath,
30    /// The last argument is a JSON configuration naming the export (nanoda).
31    NanodaConfig,
32}
33
34/// One kernel: a display name, the toolchain binary, its leading arguments,
35/// how it is given the export, and whether it accepts declarations that use
36/// `sorryAx`. A kernel that does not (nanoda leaves the axiom out of its
37/// environment; con-leche and con-ron refuse it) reads the export without the
38/// declarations that depend on `sorryAx`, none of which a caller credits.
39#[derive(Clone, Copy, Debug, Eq, PartialEq)]
40pub struct Kernel {
41    pub name: &'static str,
42    pub binary: &'static str,
43    pub args: &'static [&'static str],
44    pub input: KernelInput,
45    pub admits_sorry: bool,
46}
47
48/// Every kernel `--paranoid` runs, Lean's own first. All of them ship in the
49/// pinned toolchain's `bin/` directory.
50pub const PARANOID_KERNELS: [Kernel; 6] = [
51    Kernel {
52        name: "Lean",
53        binary: "leanchecker",
54        args: &["--silent", "--from-export"],
55        input: KernelInput::ExportPath,
56        admits_sorry: true,
57    },
58    Kernel {
59        name: "Lean (hardened allocator)",
60        binary: "leanchecker-paranoid",
61        args: &["--silent", "--from-export"],
62        input: KernelInput::ExportPath,
63        admits_sorry: true,
64    },
65    Kernel {
66        name: "lean4lean",
67        binary: "lean4lean",
68        args: &["--import"],
69        input: KernelInput::ExportPath,
70        admits_sorry: true,
71    },
72    Kernel {
73        name: "nanoda",
74        binary: "nanoda_bin",
75        args: &[],
76        input: KernelInput::NanodaConfig,
77        admits_sorry: false,
78    },
79    Kernel {
80        name: "con-leche",
81        binary: "con-leche",
82        args: &[],
83        input: KernelInput::ExportPath,
84        admits_sorry: false,
85    },
86    Kernel {
87        name: "con-ron",
88        binary: "con-ron",
89        args: &[],
90        input: KernelInput::ExportPath,
91        admits_sorry: false,
92    },
93];
94
95impl Kernel {
96    /// The export this kernel reads: the whole one, or the one without the
97    /// declarations that depend on `sorryAx`.
98    pub fn export<'a>(&self, whole: &'a str, sorry_free: &'a str) -> &'a str {
99        if self.admits_sorry { whole } else { sorry_free }
100    }
101
102    /// The full command line after the binary: leading arguments, then the
103    /// export path or the nanoda configuration path.
104    pub fn arguments(&self, export_path: &str, nanoda_config_path: &str) -> Vec<String> {
105        let mut arguments: Vec<String> = self.args.iter().map(|a| (*a).to_string()).collect();
106        arguments.push(match self.input {
107            KernelInput::ExportPath => export_path.to_string(),
108            KernelInput::NanodaConfig => nanoda_config_path.to_string(),
109        });
110        arguments
111    }
112}
113
114/// The nanoda configuration for one export, the same fields `lake check`
115/// writes. Axioms outside [`PERMITTED_AXIOMS`] are not a hard error here: the
116/// callers audit axioms per claim themselves.
117pub fn nanoda_config(export_path: &str) -> String {
118    let axioms = PERMITTED_AXIOMS
119        .iter()
120        .map(|axiom| json_string(axiom))
121        .collect::<Vec<_>>()
122        .join(",");
123    format!(
124        "{{\"use_stdin\":false,\"export_file_path\":{},\"permitted_axioms\":[{axioms}],\
125         \"unpermitted_axiom_hard_error\":false,\"num_threads\":4,\
126         \"nat_extension\":true,\"string_extension\":true}}",
127        json_string(export_path)
128    )
129}
130
131fn json_string(text: &str) -> String {
132    let mut out = String::with_capacity(text.len() + 2);
133    out.push('"');
134    for ch in text.chars() {
135        match ch {
136            '"' => out.push_str("\\\""),
137            '\\' => out.push_str("\\\\"),
138            ch if (ch as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", ch as u32)),
139            ch => out.push(ch),
140        }
141    }
142    out.push('"');
143    out
144}
145
146/// An export that names none of the expected declarations is not a check of
147/// anything: every kernel accepts an empty environment. Callers pass a name
148/// component their root module is known to define.
149pub fn export_mentions(export: &[u8], name_component: &str) -> bool {
150    let needle = json_string(name_component);
151    export
152        .windows(needle.len())
153        .any(|window| window == needle.as_bytes())
154}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159
160    #[test]
161    fn every_kernel_gets_the_export_or_its_configuration_last() {
162        for kernel in PARANOID_KERNELS {
163            let arguments = kernel.arguments("/x/export.ndjson", "/x/nanoda.json");
164            let last = arguments.last().unwrap();
165            match kernel.input {
166                KernelInput::ExportPath => assert_eq!(last, "/x/export.ndjson"),
167                KernelInput::NanodaConfig => assert_eq!(last, "/x/nanoda.json"),
168            }
169        }
170    }
171
172    #[test]
173    fn the_set_is_lean_first_and_has_no_duplicates() {
174        assert_eq!(PARANOID_KERNELS[0].binary, "leanchecker");
175        let mut binaries: Vec<_> = PARANOID_KERNELS.iter().map(|k| k.binary).collect();
176        binaries.sort_unstable();
177        binaries.dedup();
178        assert_eq!(binaries.len(), PARANOID_KERNELS.len());
179    }
180
181    #[test]
182    fn nanoda_config_names_the_export_and_the_standard_axioms() {
183        let config = nanoda_config("/tmp/a \"b\".ndjson");
184        assert!(config.contains("\"export_file_path\":\"/tmp/a \\\"b\\\".ndjson\""));
185        assert!(
186            config
187                .contains("\"permitted_axioms\":[\"propext\",\"Classical.choice\",\"Quot.sound\"]")
188        );
189        assert!(config.contains("\"use_stdin\":false"));
190    }
191
192    #[test]
193    fn export_mentions_matches_a_whole_json_string_only() {
194        let export = br#"{"str":{"pre":1,"str":"CheckerWitness"}}"#;
195        assert!(export_mentions(export, "CheckerWitness"));
196        assert!(!export_mentions(export, "Checker"));
197        assert!(!export_mentions(b"", "CheckerWitness"));
198    }
199}