<!-- SPDX-License-Identifier: CC-BY-4.0 -->
<!-- seo-title: Formal Verification for Software with Examples | HoldFast -->
<!-- description: Learn formal verification for software with HoldFast examples. Trace a loop contract, try a vector proof in the Playground, and replay proofs with Rocq. -->

# Formal verification for software

Trace a loop contract, try a weaker postcondition, and check a vector proof in Rocq.

[Try the vector proof example](../?example=dependent#playground) ·
[Trace a loop contract](#contracts) ·
[Try a weaker contract](#the-specification-gap) ·
[Replay proofs with Rocq](#kernel-replay)

<a id="what-is-formal-verification"></a>

## What is formal verification?

Formal verification establishes properties under stated assumptions, such as
buffer safety for every read or a specified result for every input satisfying
a precondition.

Deductive verification proves properties by logical reasoning. Model checking
can check them across reachable model states. Testing provides execution evidence
from selected inputs to the implementation.
[TLA+ model checking and proof tools](https://lamport.azurewebsites.net/tla/tools.html)

<a id="contracts"></a>

## How function contracts generate proof obligations

A proof obligation is a claim to establish at a program point. The caller must
establish `requires`. On every normal return, the function must establish
`ensures`. In this loop, `i <= limit` bounds the counter and `limit - i`
counts the remaining iterations.
[HoldFast contract rules](../language/reference/#contracts)

```hf
module LoopContracts;

public usize CountUpTo(usize limit)
    requires limit <= 8usize
    ensures result == limit
{
    var i = 0usize;
    while (i < limit)
        invariant i <= limit
        decreases limit - i
    {
        i += 1usize;
    }
    return i;
}
```

| Program point | Proof obligation |
| --- | --- |
| At the call | `CountUpTo(3usize)` meets the precondition. The argument `9usize` violates the bound. |
| At the loop | Initially `0 <= limit`. From `i < limit`, incrementing `i` preserves `i <= limit` and reduces `limit - i` by one. |
| At the return | The false guard gives `i >= limit`. The invariant gives `i <= limit`. Together they give `result == limit`, or `3` for the example call. |

The full module also shows equality proofs and indexed types.
[HoldFast source for `CountUpTo`](https://github.com/symbiogenesis/HoldFast/blob/main/examples/dependent.hf)

## The specification gap

The intended result for input `3` is `3`. Start the local Playground and open
the URL it prints. Replace the editor contents with the complete `LoopContracts`
module above and select **Compile**. In **Console**, enter `Nat(CountUpTo(3usize))`,
set **Result type** to `Nat`, and select **Run** to get `3`.
[Local Playground setup](../tooling/playground/#scope-and-launch)

Keep the module declaration and replace `CountUpTo` with the version below.
Select **Compile** again. The weaker postcondition requires the result to be at
most `limit`. Every admitted limit is at least zero, so returning zero meets
that bound.

```hf
public usize CountUpTo(usize limit)
    requires limit <= 8usize
    ensures Nat(result) <= Nat(limit)
{
    return 0usize;
}
```

Run the same console expression again to get `0`. The result meets the weaker
contract and fails the expected result of `3`. Keep the zero-returning body and
restore `ensures result == limit`. Select **Compile** and look for the
diagnostic at `ensures` in **Problems**. HoldFast's qualification workflow uses
independently expected bytes and status values to catch similar gaps.
[Fedorin on the specification gap](https://danilafe.com/blog/verifiable_language/#the-specification-gap) ·
[HoldFast contract-weakening probes](../assurance/workflow-contract/#change-and-weakening-probes)

<a id="lemma-example"></a>

## Try a formal proof of a vector property

`Vec<Nat, 1>` describes a one-element vector of natural numbers. This example
passes `[42]` through a length-preserving function, then proves that reading
its sole element gives `42`.
[How dependent types encode vector lengths](../dependent-types/)

```hf
public definition Nat PreservedValue() => At(Preserved(), FZero<0>());

public lemma SameValue()
    ensures PreservedValue() == 42
    proof
    {
        assert PreservedValue() == 42;
    }
```

1. Open
   [Dependent functions & length proofs](../?example=dependent#playground)
   in the browser. In **Console**, select **Run** with `PreservedValue()` and
   result type `Nat` to get `42`.
2. Select **Compile**, then open **Problems**. The browser lists
   `SameValue` as an unchecked proof obligation.
3. In the [local Playground](../tooling/playground/#scope-and-launch), load
   the same example and select **Compile** to see Gallina. Change only the assertion to
   `assert PreservedValue() == 41;` and compile again. **Problems** shows the
   assertion the compiler could not establish.

<a id="kernel-replay"></a>

## Replay the proof with Rocq

Restore `assert PreservedValue() == 42;` in the local Playground. Select
**Compile**, then **Download .v** in the **Gallina** tab. In the directory
containing `playground.v`, run the following command with the repository's
Rocq switch active. The kernel checks the generated proof against its theorem.
[Native toolchain setup](https://github.com/symbiogenesis/HoldFast/blob/main/tools/README.md#native-tooling)

```shell
rocq c playground.v
```

To check the repository examples, run the commands below from the checkout
root. Use `python3` on Linux or in WSL. The first prints Gallina for the
module containing `CountUpTo`. The second replays the qualification fixtures,
audits their assumptions and independently rechecks the compiled modules.
[Elaboration and kernel replay commands](../tooling/elaboration-prototype/#commands-and-acceptance)

```shell
python tools/run.py holdfast-parser elaborate examples/dependent.hf
python tools/run.py holdfast-parser elaborate-qualify
```

<a id="compiled-artifacts"></a>

## What does a proof cover in compiled software?

Kernel replay establishes theorems about the elaborated Gallina. An executable
claim needs a checked connection from source contracts to the exact image's
behavior under stated representations, entry conditions and platform assumptions.
CompCert's theorem covers its source and assembly representations. HoldFast's
release also requires frontend, capability-aware lowering and linked-image evidence.
[CompCert semantic preservation](https://compcert.org/man/manual001.html) ·
[HoldFast source-to-image obligations](../assurance/verification-strategy/#compiler-and-evidence-obligations)

Run the generated C for a valid packet to read payload `11 22` through the
returned view at offset `4`.
[Run the packet validator walkthrough](../tooling/packet-walkthrough/)

```shell
python tools/run.py holdfast-parser packet-example "56 02 6B 01 11 22"
```

```text
Ok copied=2 offset=4 length=2 read=1 write=0
payload 11 22
```

[Permissions on the returned view](../borrow-checking/) ·
[Available evidence and remaining executable obligations](../language/first-release/#first-slice-qualification)
