verif 0.2.0

In-code formal verification for Rust: an embedded bit-blasting SMT decision procedure, a symbolic DSL, contracts and a machine-checked proof kernel. SPARK-inspired, no_std, no external dependencies.
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
//! The verifier and exhaustive execution must agree on programs with loops.
//!
//! `tests/differential.rs` fuzzes `wp` against concrete execution, but its program
//! generator has no `While` at all. Loops are where the rule set is richest -- four
//! obligations, a variant, and a claim rewrite that reaches past the loop -- so they are
//! exactly where a rule can be wrong without the arithmetic being wrong. This closes that
//! gap: generate a small imperative program with loops and branches, run it concretely on
//! every input, and require that `verify`'s verdict matches what the runs show.
//!
//! The oracle is the same shape the crate already trusts elsewhere: a `valid` verdict must
//! mean no input falsifies the contract, and a refutation must come with a witness that
//! really does falsify it.

use verif::prelude::*;
use verif::smt::{self, var};
use verif::wp::{verify, Established, Stmt};

struct Lcg(u64);
impl Lcg {
    fn next(&mut self) -> u64 {
        self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
        self.0 >> 33
    }
    fn below(&mut self, n: u64) -> u64 {
        if n == 0 { 0 } else { self.next() % n }
    }
}

/// A claim written as `assert acc <= B`, `assert acc == B` or `assert acc < B`.
#[derive(Clone, Copy)]
enum Claim {
    Le(u8),
    Eq(u8),
    Lt(u8),
}

impl Claim {
    fn holds(self, acc: u8) -> bool {
        match self {
            Claim::Le(b) => acc <= b,
            Claim::Eq(b) => acc == b,
            Claim::Lt(b) => acc < b,
        }
    }
    fn build(self, acc: Var) -> Pred {
        match self {
            Claim::Le(b) => acc.le_val(b as u64),
            Claim::Eq(b) => acc.eq_val(b as u64),
            Claim::Lt(b) => acc.lt_val(b as u64),
        }
    }
}

/// Concrete step: `acc := f(acc)`, a claim, a loop, or a branch. Values are `u8`.
enum Step {
    AddConst(u8),
    AddVar,
    Claim(Claim),
    If { cond_lt: u8, then_: Vec<Step>, else_: Vec<Step> },
    While { guard_lt: u8, body: Vec<Step> },
}

/// Run concretely, returning `None` as soon as a claim fails. `None` means "some claim
/// this run reached is false", which is exactly what a verified report forbids.
fn run_checked(steps: &[Step], mut acc: u8, x: u8) -> Option<u8> {
    for s in steps {
        match s {
            Step::AddConst(k) => acc = acc.wrapping_add(*k),
            Step::AddVar => acc = acc.wrapping_add(x),
            Step::Claim(c) => {
                if !c.holds(acc) {
                    return None;
                }
            }
            Step::If { cond_lt, then_, else_ } => {
                let branch = if acc < *cond_lt { then_ } else { else_ };
                acc = run_checked(branch, acc, x)?;
            }
            Step::While { guard_lt, body } => {
                let mut fuel = 300;
                while acc < *guard_lt && fuel > 0 {
                    acc = run_checked(body, acc, x)?;
                    fuel -= 1;
                }
            }
        }
    }
    Some(acc)
}

fn run(steps: &[Step], acc: u8, x: u8) -> u8 {
    // Final value only; a false claim aborts the run, and the claim test uses
    // `run_checked` directly when it needs to know that.
    run_checked(steps, acc, x).unwrap_or(acc)
}

/// Symbolic translation. Every loop carries the invariant "acc < 256" (always true for a
/// byte) plus its guard bound, which is enough for the generated programs: the bodies only
/// add constants or the input, so the accumulator stays a byte by construction.
fn build(steps: &[Step], acc: Var, x: Var) -> &'static Stmt<'static> {
    let mut seq: Stmt = Stmt::Skip;
    for s in steps.iter().rev() {
        let one: Stmt = match s {
            Step::AddConst(k) => Stmt::Assign { var: acc, expr: acc + *k as u32 },
            Step::AddVar => Stmt::Assign { var: acc, expr: acc + x },
            Step::Claim(c) => Stmt::Assert(c.build(acc)),
            Step::If { cond_lt, then_, else_ } => Stmt::If {
                cond: acc.lt_val(*cond_lt as u64),
                then_: Box::leak(Box::new(build(then_, acc, x))),
                else_: Box::leak(Box::new(build(else_, acc, x))),
            },
            Step::While { guard_lt, body } => Stmt::While {
                cond: acc.lt_val(*guard_lt as u64),
                invariant: acc.le_val(255),
                variant: Some(smt::sub(smt::word(*guard_lt as u64, 8), acc)),
                body: Box::leak(Box::new(build(body, acc, x))),
            },
        };
        seq = Stmt::Seq { first: Box::leak(Box::new(one)), second: Box::leak(Box::new(seq)) };
    }
    Box::leak(Box::new(seq))
}

fn make_steps(r: &mut Lcg, depth: u32, n: usize) -> Vec<Step> {
    gen_with(r, depth, n, true)
}

/// `gen`, optionally leaving out `Claim` steps so a caller that only cares about the
/// contract postcondition is not diluted by assertions.
fn gen_with(r: &mut Lcg, depth: u32, n: usize, claims: bool) -> Vec<Step> {
    let top = if claims { 7 } else { 6 };
    (0..n)
        .map(|_| match r.below(top) {
            0 if depth > 0 => {
                let (nt, ne) = (r.below(3) as usize, r.below(3) as usize);
                Step::If { cond_lt: 1 + r.below(250) as u8, then_: gen_with(r, depth - 1, nt, claims), else_: gen_with(r, depth - 1, ne, claims) }
            }
            1 if depth > 0 => {
                let nb = r.below(3) as usize;
                Step::While { guard_lt: 1 + r.below(250) as u8, body: gen_with(r, depth - 1, nb, claims) }
            }
            2 => Step::AddVar,
            3 => {
                let b = r.below(256) as u8;
                match r.below(3) {
                    0 => Step::Claim(Claim::Le(b)),
                    1 => Step::Claim(Claim::Eq(b)),
                    _ => Step::Claim(Claim::Lt(b)),
                }
            }
            k => Step::AddConst((k % 3) as u8 + 1),
        })
        .collect()
}

#[test]
fn a_verified_report_is_never_wrong_about_loops() {
    // The one property that must never fail: if the verifier says the program is verified,
    // then no input falsifies the contract. This is checked by brute force on all 256
    // inputs, so a single disagreement is a soundness bug, not a heuristic miss.
    //
    // The converse is deliberately *not* asserted. A loop's invariant is supplied by the
    // caller, so a contract that happens to hold everywhere may still be refuted -- an
    // unfaithful invariant, or a variant that does not decrease, is a legitimate failure.
    // What the verifier owes the caller is that it never says `verified` about something
    // that is not, and that is what this pins.
    let mut r = Lcg(0x7f3a_91b5_2c8d_0044);
    let mut verified = 0u32;
    let mut total = 0u32;
    for _ in 0..600 {
        let n = 1 + r.below(3) as usize;
        let steps = gen_with(&mut r, 2, n, false);
        // Draw the postcondition bound from the *reachable* outputs, so a large share of
        // contracts genuinely hold and the verifier has something to prove. A uniformly
        // random bound almost never holds, which would leave the soundness assertion with
        // almost nothing to check.
        let mut outputs = [0u8; 256];
        for (v, o) in outputs.iter_mut().enumerate() {
            *o = run(&steps, v as u8, v as u8);
        }
        let use_eq = r.below(2) == 0;
        let bound = if use_eq {
            outputs[r.below(256) as usize] as u64
        } else {
            let m = *outputs.iter().max().unwrap() as u64;
            // Sometimes below the max, sometimes exactly it: the former must be refuted
            // and the latter must verify, so both branches of the assertion get exercised.
            if r.below(2) == 0 { m } else { r.below(m + 1) }
        };

        smt::with_fresh(|| {
            let x = var(8);
            let acc = var(8);
            let prog = build(&steps, acc, x);
            let post = if use_eq { acc.eq_val(bound) } else { acc.le_val(bound) };
            let report = verify(prog, smt::truth(true), post);

            // Oracle: every input, run concretely.
            let mut first_bad = None;
            for (v, out) in outputs.iter().enumerate() {
                let ok = if use_eq { *out as u64 == bound } else { *out as u64 <= bound };
                if !ok {
                    first_bad = Some((v as u8, *out));
                    break;
                }
            }

            if report.establishes() == Established::Total {
                total += 1;
            }
            if report.is_verified() {
                verified += 1;
                assert!(
                    first_bad.is_none(),
                    "the report says verified, but a concrete run falsifies the contract: \
                     bound={}, eq={}, first bad input x={:?}",
                    bound,
                    use_eq,
                    first_bad
                );
            }
        });
    }
    assert!(verified > 30, "too few verified reports to be meaningful: {}", verified);
    assert!(total > 20, "too few Total reports to be meaningful: {}", total);
}

#[test]
fn a_verified_report_never_misses_a_failed_claim() {
    // The claim-rewrite machinery -- the `If` and `While` arms rewriting the assertions to
    // their right -- is where three defects lived. This drives it under brute force: build
    // programs whose claims are scattered through branches and loops, make the *contract*
    // vacuous (`pre = post = true`) so nothing but the claims can fail the report, and then
    // require that a verified report means no run reaches a false claim.
    //
    // A report that is *not* verified proves nothing here -- an unfaithful invariant or a
    // claim that is genuinely false both look the same from outside. The one-directional
    // assertion is the whole point: the verifier may miss a proof, but it may not certify a
    // claim that a concrete run falsifies.
    let mut r = Lcg(0x2b9c_4e17_a3f0_8811);
    let mut verified = 0u32;
    let mut with_failed_claim = 0u32;
    for _ in 0..800 {
        let n = 1 + r.below(4) as usize;
        let steps = make_steps(&mut r, 2, n);

        smt::with_fresh(|| {
            let x = var(8);
            let acc = var(8);
            let prog = build(&steps, acc, x);
            let report = verify(prog, smt::truth(true), smt::truth(true));

            // Oracle: every input, in order, stopping at the first false claim.
            let mut first_bad = None;
            for v in 0..=255u8 {
                if run_checked(&steps, v, v).is_none() {
                    first_bad = Some(v);
                    break;
                }
            }
            if first_bad.is_some() {
                with_failed_claim += 1;
            }

            if report.is_verified() {
                verified += 1;
                assert!(
                    first_bad.is_none(),
                    "the report says verified, but a concrete run reaches a false claim: \
                     first bad input x={:?}",
                    first_bad
                );
            }
        });
    }
    assert!(verified > 30, "too few verified reports to be meaningful: {}", verified);
    assert!(
        with_failed_claim > 30,
        "too few programs with a genuinely false claim to be meaningful: {}",
        with_failed_claim
    );
}

/// What a loop body does to the variable it runs on.
#[derive(Clone, Copy)]
enum Act {
    Add(u8),
    Set(u8),
    Skip,
}

impl Act {
    fn apply(self, v: u8) -> u8 {
        match self {
            Act::Add(k) => v.wrapping_add(k),
            Act::Set(k) => k,
            Act::Skip => v,
        }
    }
    fn build(self, v: Var) -> Stmt<'static> {
        match self {
            Act::Add(k) => Stmt::Assign { var: v, expr: v + k as u32 },
            Act::Set(k) => Stmt::Assign { var: v, expr: smt::word(k as u64, 8) },
            Act::Skip => Stmt::Skip,
        }
    }
    fn name(self) -> &'static str {
        match self {
            Act::Add(k) => match k { 1 => "Add(1)", 2 => "Add(2)", _ => "Add(50)" },
            Act::Set(k) => match k { 0 => "Set(0)", 10 => "Set(10)", 100 => "Set(100)", _ => "Set(255)" },
            Act::Skip => "Skip",
        }
    }
}

/// A nested loop over two variables: the outer counter `i` and an inner scan `j`, plus an
/// optional extra action the inner body performs on `i` -- which is the divergence shape
/// (`i := 0` inside the inner loop resets the outer counter forever).
struct Nested {
    outer_guard: u8,
    outer: Act,
    inner_guard: u8,
    inner: Act,
    inner_on_i: Option<Act>,
    start_i: u8,
    start_j: u8,
}

/// Run the nested loop concretely. `None` means the fuel ran out, which for a two-byte
/// state means a cycle, i.e. non-termination.
fn run_nested(p: &Nested) -> Option<u8> {
    let (mut i, mut j) = (p.start_i, p.start_j);
    let mut fuel = 100_000u32;
    while i < p.outer_guard {
        if fuel == 0 {
            return None;
        }
        fuel -= 1;
        i = p.outer.apply(i);
        while j < p.inner_guard {
            if fuel == 0 {
                return None;
            }
            fuel -= 1;
            j = p.inner.apply(j);
            if let Some(a) = p.inner_on_i {
                i = a.apply(i);
            }
        }
        // The inner loop's index is reset so the next outer iteration runs it again.
        // Without this the inner loop runs at most once and a body that writes the outer
        // counter from inside it cannot cause divergence -- which is why the first version
        // of this family contained no divergent program that the report called `Total`.
        j = p.start_j;
    }
    Some(i)
}

fn build_nested(p: &Nested) -> Stmt<'static> {
    let i = var(8);
    let j = var(8);
    let mut inner_body: Stmt<'static> = Stmt::Skip;
    if let Some(a) = p.inner_on_i {
        inner_body = Stmt::Seq {
            first: Box::leak(Box::new(inner_body)),
            second: Box::leak(Box::new(a.build(i))),
        };
    }
    let inner_body = Stmt::Seq {
        first: Box::leak(Box::new(p.inner.build(j))),
        second: Box::leak(Box::new(inner_body)),
    };
    let inner_loop = Stmt::While {
        cond: j.lt_val(p.inner_guard as u64),
        invariant: j.le_val(255),
        variant: Some(smt::sub(smt::word(p.inner_guard as u64, 8), j)),
        body: Box::leak(Box::new(inner_body)),
    };
    let reset_j = Stmt::Assign { var: j, expr: smt::word(p.start_j as u64, 8) };
    let outer_body = Stmt::Seq {
        first: Box::leak(Box::new(p.outer.build(i))),
        second: Box::leak(Box::new(Stmt::Seq {
            first: Box::leak(Box::new(inner_loop)),
            second: Box::leak(Box::new(reset_j)),
        })),
    };
    Stmt::While {
        cond: i.lt_val(p.outer_guard as u64),
        invariant: i.le_val(255),
        variant: Some(smt::sub(smt::word(p.outer_guard as u64, 8), i)),
        body: Box::leak(Box::new(outer_body)),
    }
}

#[test]
fn a_total_report_means_the_nested_loop_terminates() {
    // The behavioural oracle for a termination *claim* -- the one claim a concrete run
    // cannot otherwise see. `variant_after` used to read a nested loop as a no-op, so
    // `while i < 100 { i := i + 1; while i != 0 { i := 0 } }` was proved `Total` and
    // diverges. Here a whole family of nested loops is enumerated, each run concretely
    // with a fuel cap, and the report's `Total` is checked against whether the run ended.
    //
    // Two variables, deliberately. With one variable the inner loop always havocs the
    // outer measure, so no program in the family is ever `Total` and the oracle would
    // assert nothing -- the first version of this test failed exactly that way, on
    // `total == 0`. The inner scan now runs on `j`, so the outer counter `i` survives it
    // and a genuine `Total` is reachable; the `inner_on_i` field re-introduces the
    // divergence by writing `i` from inside the inner loop.
    //
    // The assertion is one-directional on purpose: a report that is not `Total` may be a
    // divergent program correctly refused, or a terminating one whose stated invariant or
    // variant is too weak. Both are legitimate, so nothing is asserted in that direction.
    let mut total = 0u32;
    let mut divergent = 0u32;
    let outer_acts = [Act::Add(1), Act::Add(2), Act::Add(50), Act::Set(0), Act::Skip];
    let inner_acts = [Act::Add(1), Act::Add(2), Act::Set(10), Act::Set(100), Act::Set(0), Act::Skip];
    let inner_on_i = [None, Some(Act::Set(0)), Some(Act::Add(1))];
    for &outer_guard in &[10u8, 100] {
        for &inner_guard in &[10u8, 100, 255] {
            for &outer in &outer_acts {
                for &inner in &inner_acts {
                    for &on_i in &inner_on_i {
                        for &(start_i, start_j) in &[(0u8, 0u8), (1, 0), (50, 5)] {
                            let p = Nested { outer_guard, outer, inner_guard, inner, inner_on_i: on_i, start_i, start_j };
                            let terminates = run_nested(&p);
                            if terminates.is_none() {
                                divergent += 1;
                            }
                            smt::with_fresh(|| {
                                let i = var(8);
                                let j = var(8);
                                let prog = build_nested(&p);
                                let pre = smt::and(i.eq_val(start_i as u64), j.eq_val(start_j as u64));
                                let report = verify(&prog, pre, smt::truth(true));
                                if report.establishes() == Established::Total {
                                    total += 1;
                                    assert!(
                                        terminates.is_some(),
                                        "the report says Total, but the program diverges: \
                                         outer_guard={}, outer={}, inner_guard={}, inner={}, \
                                         inner_on_i={:?}, start=({}, {})",
                                        outer_guard, outer.name(), inner_guard, inner.name(),
                                        on_i.map(Act::name), start_i, start_j
                                    );
                                }
                            });
                        }
                    }
                }
            }
        }
    }
    assert!(total > 20, "too few Total reports to be meaningful: {}", total);
    assert!(
        divergent > 0,
        "the family must contain a divergent program, or it proves nothing"
    );
}