Skip to content

eBPF-based security platform

testing: prove models of the number parser and the register in Lean 4

Daniel Borkmann645b90a91065
diff --git a/.agents/skills/proofs/SKILL.md b/.agents/skills/proofs/SKILL.md
index 4f7dfa05..b157bd3b 100644
--- a/.agents/skills/proofs/SKILL.md
+++ b/.agents/skills/proofs/SKILL.md
@@ -1,6 +1,6 @@
---
name: proofs
-description: Run, write and debug shirudo's CBMC proofs under testing/proofs/cbmc, which check its parsers and emitters for every input within a bound. Covers make proofs, the harness and proofs.list conventions, choosing properties and bounds, keeping a proof fast and within memory, and telling a real bug from a harness error. Use when changing code a proof covers, when adding a parser or emitter, when a proof fails, or when asked to prove code correct.
+description: Run, write and debug shirudo's proofs, CBMC under testing/proofs/cbmc, which checks its parsers and emitters for every input within a bound, and Lean 4 under testing/proofs/lean4, which proves models of its algorithms for every input. Covers make proofs, the CBMC harness and proofs.list conventions, writing a Lean model and linking it to the C, choosing properties and bounds, keeping a proof fast and within memory, and telling a real bug from a harness error. Use when changing code a proof covers, when adding a parser or emitter, when a proof fails, or when asked to prove code correct.
---
# Proofs
@@ -14,9 +14,10 @@ page in the same commit.
## Run
```sh
-make proofs # every proof
-make proofs PROOFS="string-number hex" # some of them
+make proofs # CBMC and Lean 4
+make proofs-cbmc PROOFS="string-number hex" # some CBMC proofs
testing/proofs/cbmc/run.sh -v <proof> # whole output and traces
+make proofs-lean4 # the Lean 4 proofs
```
Cap the memory of a long run, `ulimit -v 24000000` in the shell that
@@ -59,6 +60,29 @@ to wait for.
take minutes: split it, proving the parts the caller composes, as the
`.upatch` header, sections and decoders are proven apart.
+## Lean 4
+
+CBMC proves the C within a bound; Lean proves a model for every input.
+Use Lean where a bounded proof is not enough: an algorithm whose
+correctness needs every length, such as `Number.lean`'s exact value of a
+digit string, or a protocol property, such as `Chain.lean`'s register
+determining its events.
+
+- A model goes in `testing/proofs/lean4/Shirudo/<Name>.lean`, imported
+ from `Shirudo.lean`, and follows the C step by step, with the values the
+ C can hold (2^64 for a `__u64`).
+- What the C cannot show, such as a hash being collision resistant, is
+ an explicit hypothesis of the theorem, never an axiom.
+- Core Lean only, no Mathlib: `omega`, `simp`, `decide` and induction
+ carry these proofs. A lemma Mathlib has, such as
+ `List.map_injective_iff`, is proved in the file.
+- The lakefile makes every warning an error, so a `sorry`, a deprecated
+ name or an unused `simp` argument fails the build.
+- Link the model to the C with a CBMC proof where one is cheap, as
+ `string-number-model.c` checks `parse_u64()` against `Number.lean` up
+ to 4 bytes; the coverage page says which models follow the C by review.
+- The toolchain is the one `lean-toolchain` names; elan installs it.
+
## When it fails
- `no body for function <f>`: CBMC lets that call return anything, so
diff --git a/.gitignore b/.gitignore
index 988a831f..923b6fbb 100644
--- a/.gitignore
+++ b/.gitignore
@@ -90,3 +90,6 @@ util/version_id.c
# rendered documentation from make docs and make -C Documentation html
/Documentation/output*/
__pycache__/
+
+# Lean 4 build output
+/testing/proofs/lean4/.lake/
diff --git a/AGENTS.md b/AGENTS.md
index 1a48c899..f28a52ab 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -46,7 +46,7 @@ Before changing security-relevant code, read
| `Documentation/upatches/` | Authoring and shipping upatches: attach kinds, maps and serializers, decoders, the Beefile, publishing, debugging a failed load. |
| `Documentation/reference/` | Every command (`reference/cli/`), the formats and settings (`reference/formats/`, including the `.upatch` container), failure categories and exit status, files, units, environment variables, the cheat sheet. |
| `Documentation/contribute/` | Developer guide, test tiers and the test VM (read `testing.rst` before adding or moving a test), test coverage, the kernel coding style, commits and sign-off (read `contributing.rst` before crafting a commit), and the documentation style guide `writing-docs.rst`. |
-| `.agents/skills/` | Skills for coding agents in the `SKILL.md` format of agentskills.io, which Codex reads there and Claude Code through the `.claude/skills` link: `coding` writes C in the tree's style and grows `util/`, `testing` runs the test tiers and the test VM, `pre-submit` the checks CI runs on a series, `upatch` writes for the target's preemption model and a low cost, builds, packages and publishes an upatch, `bpf-concurrency` checks upatch code whose runs share state, `bpf-coccinelle` runs and extends the Coccinelle rules for it, `docs` finds and checks the pages a change touches, `fuzz-target` adds a libFuzzer target for a parser, `proofs` runs and writes the CBMC proofs. |
+| `.agents/skills/` | Skills for coding agents in the `SKILL.md` format of agentskills.io, which Codex reads there and Claude Code through the `.claude/skills` link: `coding` writes C in the tree's style and grows `util/`, `testing` runs the test tiers and the test VM, `pre-submit` the checks CI runs on a series, `upatch` writes for the target's preemption model and a low cost, builds, packages and publishes an upatch, `bpf-concurrency` checks upatch code whose runs share state, `bpf-coccinelle` runs and extends the Coccinelle rules for it, `docs` finds and checks the pages a change touches, `fuzz-target` adds a libFuzzer target for a parser, `proofs` runs and writes the CBMC and Lean 4 proofs. |
The kernel side of the signing design is the kernel's own
`Documentation/bpf/signing.rst`; `bpf_prog_verify_signature()` runs
@@ -306,10 +306,12 @@ one usually still compiles and passes tests.
fuzz target, and a shell test `t<F><K><NN>` lives in its family's
directory (`Documentation/contribute/testing/testing.rst`). The
`testing` and `fuzz-target` skills say how to run and add them.
-- `make proofs` runs the CBMC proofs of `testing/proofs/cbmc/`, which check
- parsers and emitters for every input within a bound. A change to code a
- proof covers runs it, and a new parser gets one where CBMC can carry
- it; the `proofs` skill says how.
+- `make proofs` runs the CBMC proofs of `testing/proofs/cbmc/`, which
+ check parsers and emitters for every input within a bound, and the Lean
+ 4 proofs of `testing/proofs/lean4/`, which prove models of algorithms
+ for every input. A change to code a proof covers, or to an algorithm a
+ model follows, runs them, and a new parser gets a proof where CBMC can
+ carry one; the `proofs` skill says how.
- CI runs `.github/scripts/build-commits.sh`, `check-style.sh`,
`check-dco.sh`, `check-coccinelle.sh`, `check-sparse.sh`,
`check-spdx.sh` and the documentation check on every pull request;
diff --git a/Documentation/contribute/testing/proof-coverage.rst b/Documentation/contribute/testing/proof-coverage.rst
index df0c08ce..263aad40 100644
--- a/Documentation/contribute/testing/proof-coverage.rst
+++ b/Documentation/contribute/testing/proof-coverage.rst
@@ -8,18 +8,19 @@
Proof coverage
==============
-This page lists the CBMC proofs under :src:`testing/proofs/cbmc/`, the code
-each one proves, the inputs it covers and the properties it states, and
-the parsers no proof covers yet. :doc:`proofs` explains how to run and
-write them. Every proof also shows that the code reads and writes nothing
-outside its objects and has no undefined arithmetic for those inputs.
+This page lists the CBMC proofs under :src:`testing/proofs/cbmc/` and the
+Lean 4 proofs under :src:`testing/proofs/lean4/`, what each one proves and
+for which inputs, and the parsers no proof covers yet. :doc:`proofs`
+explains how to run and write them.
-"Every input" means every input of any length. A bound such as "up to 22
-bytes" means every input of that length or shorter, and "lengths 0 to 6"
-every input of each of those lengths.
+CBMC proofs
+-----------
-Proofs
-------
+Every CBMC proof shows that the code reads and writes nothing outside its
+objects and has no undefined arithmetic for the inputs it covers, besides
+the properties the table lists. "Every input" means every input of any
+length. A bound such as "up to 22 bytes" means every input of that length
+or shorter, and "lengths 0 to 6" every input of each of those lengths.
.. list-table::
:header-rows: 1
@@ -35,6 +36,11 @@ Proofs
- Refuses exactly what is empty or holds a non-digit; a number
within its bounds and of the sign the string spells; nothing
written on refusal; ``digits()`` finds the whole run
+ * - ``string-number-model``
+ - ``parse_u64()``, ``parse_x64()``
+ - Up to 4 bytes
+ - The value of the Lean model ``Shirudo.Number``, or ``-ERANGE``
+ exactly where the model refuses
* - ``string-utf8``
- ``utf8_width()``
- Every input
@@ -71,6 +77,34 @@ Proofs
every section inside the file and behind the header, and a
``.rodata`` offset inside the data
+Lean 4 proofs
+-------------
+
+Each proof holds for every input of the model; the last column says how
+the model follows the C.
+
+.. list-table::
+ :header-rows: 1
+ :widths: 22 30 26 22
+
+ * - Model
+ - Theorems
+ - Assumptions
+ - Follows the C
+ * - ``Shirudo.Number``, ``parse_base()`` of :src:`util/string.c`
+ - ``parse_exact``: for digit strings of every length, the value they
+ spell, or ``-ERANGE`` exactly when it passes ``max``
+ - ``max`` fits a ``__u64``
+ - CBMC, ``string-number-model``, up to 4 bytes
+ * - ``Shirudo.Chain``, the register of :src:`util/chain.c`
+ - ``register_injective``, ``register_tagged_injective``: equal
+ registers come from the same events, tagged the same, in the same
+ order; ``register_eq_foldl``: the register folds the events in the
+ order they came
+ - The hash is injective on (register, event) pairs and never yields
+ the initial value; the tagged event encoding is injective
+ - Review
+
Not covered yet
---------------
diff --git a/Documentation/contribute/testing/proofs.rst b/Documentation/contribute/testing/proofs.rst
index 5172c197..c7080d5b 100644
--- a/Documentation/contribute/testing/proofs.rst
+++ b/Documentation/contribute/testing/proofs.rst
@@ -5,33 +5,48 @@
:page-type: How-to
:audience: shirudo contributors
-Prove code with CBMC
-====================
+Prove code with CBMC and Lean 4
+===============================
A test checks the inputs someone thought of, and a fuzz target the ones it
-happens to find. A proof under :src:`testing/proofs/cbmc/` checks every input
-within its bounds: `CBMC <https://www.cprover.org/cbmc/>`_ turns shirudo's
-C and a harness into a formula and asks a SAT solver for an input that
-breaks a property. When none exists, the property holds for all of them.
-
-Each proof states two kinds of property. CBMC adds the first to every
+happens to find. shirudo's proofs check all of them, in two ways that
+complement each other:
+
+- `CBMC <https://www.cprover.org/cbmc/>`_ proves properties of the C
+ itself. The proofs under :src:`testing/proofs/cbmc/` turn shirudo's C
+ and a harness into a formula and ask a SAT solver for an input that
+ breaks a property; when none exists, the property holds for every input
+ within the harness's bounds.
+- `Lean 4 <https://lean-lang.org/>`_ proves properties of a model of an
+ algorithm. The proofs under :src:`testing/proofs/lean4/` state the
+ algorithm in Lean and prove it meets its specification for every input,
+ of any length, without a bound. Lean does not read shirudo's C: a CBMC
+ proof checks the C against the model within its bounds, where one does.
+
+A CBMC proof states two kinds of property. CBMC adds the first to every
proof: no read or write outside an object, no null or dangling pointer,
no signed overflow, no shift past the width of a type, no division by
zero, no conversion that changes a value, and no loop that runs longer
than the harness allows. The harness states the second: what the code
must do, such as that a parser accepts exactly the well-formed inputs and
-that every offset it returns lies inside the input.
-
-A proof covers every input up to the bound its harness names. Where the
-format itself bounds what the code reads, as a fixed-size header does, the
-proof covers every input of any size; elsewhere it covers every input up
-to the stated length, and :doc:`proof-coverage` says which is which.
+that every offset it returns lies inside the input. A CBMC proof covers
+every input up to the bound its harness names. Where the format itself
+bounds what the code reads, as a fixed-size header does, the proof covers
+every input of any size; elsewhere it covers every input up to the stated
+length, and :doc:`proof-coverage` says which is which.
Before you begin
----------------
- CBMC 5.95 or newer, packaged as ``cbmc`` by Debian and Ubuntu.
-- Memory: most proofs need little, but a large one can take several
+- For the Lean 4 proofs, elan, packaged as ``elan``, and the toolchain
+ :src:`testing/proofs/lean4/lean-toolchain` names:
+
+ .. code-block:: console
+
+ $ elan toolchain install "$(cat testing/proofs/lean4/lean-toolchain)"
+
+- Memory: most CBMC proofs need little, but a large one can take several
gigabytes.
Run the proofs
@@ -43,29 +58,32 @@ Run the proofs
$ make proofs
- Each line names a proof, the number of checks CBMC made and the time
- it took. ``proofs: <n> hold`` ends a run in which all of them held.
+ Each CBMC line names a proof, the number of checks CBMC made and the
+ time it took, and ``proofs: <n> hold`` ends a run in which all of them
+ held. ``Build completed successfully`` ends the Lean 4 run.
-2. Run some of them by name:
+2. Run one kind, or some CBMC proofs by name:
.. code-block:: console
- $ make proofs PROOFS="string-number upatch-header"
+ $ make proofs-lean4
+ $ make proofs-cbmc PROOFS="string-number upatch-header"
-3. Read why one failed:
+3. Read why a CBMC proof failed:
.. code-block:: console
$ testing/proofs/cbmc/run.sh -v string-number
``-v`` prints CBMC's whole output, with the trace of each failed
- check: the input that breaks it and the steps that lead there.
+ check: the input that breaks it and the steps that lead there. Lean
+ prints the theorem and the goal it could not close.
-Write a proof
--------------
+Write a CBMC proof
+------------------
-1. Write ``testing/proofs/cbmc/<name>.c``. It includes ``proof.h`` and the
- source file it proves, so that it reaches static functions too, and
+1. Write ``testing/proofs/cbmc/<name>.c``. It includes ``proof.h`` and
+ the source file it proves, so that it reaches static functions too, and
defines ``harness()``, which CBMC runs with every input at once.
``any_bytes(n)`` gives ``n`` bytes of any contents, and a variable
left uninitialized takes any value; ``__CPROVER_assume()`` narrows the
@@ -100,14 +118,38 @@ a system call, returns any value, and ``run.sh`` fails a proof that calls
one. Give the function a model in ``proof.h``, or keep the proof away from
the code that calls it.
+Write a Lean 4 proof
+--------------------
+
+1. Write the model in ``testing/proofs/lean4/Shirudo/<Name>.lean`` as
+ close to the C as Lean allows: the same steps, the same checks, the
+ values the C can hold. State each theorem as the specification the
+ algorithm must meet for every input, and assume what the C cannot
+ prove, such as a hash being collision resistant, as an explicit
+ hypothesis of the theorem.
+
+2. Import the module in :src:`testing/proofs/lean4/Shirudo.lean`. A
+ ``sorry`` or any other warning fails the build, so every theorem is
+ proved in full.
+
+3. Where CBMC can, add a CBMC proof that the C computes what the model
+ computes, for every input up to a bound, as
+ :src:`testing/proofs/cbmc/string-number-model.c` does for the number
+ parser; elsewhere the model follows the C by review, and the coverage
+ page says so.
+
+4. Add a row to :doc:`proof-coverage`.
+
Limits
------
-A proof is about the code CBMC sees: the C of the files the harness
+A CBMC proof is about the code CBMC sees: the C of the files the harness
includes, with ``-funsigned-char`` as the build sets it, against a model
of the libc functions it calls. It says nothing about the kernel, the
compiler's code generation, time, or other threads, and it holds only
-within its bounds.
+within its bounds. A Lean 4 proof holds for every input, but of the model:
+it carries over to the C as far as the model matches the C, and its
+assumptions hold.
Related
-------
diff --git a/Makefile b/Makefile
index b75504ea..16aa68a7 100644
--- a/Makefile
+++ b/Makefile
@@ -50,7 +50,7 @@ export prefix exec_prefix bindir libexecdir sharedir libdir mandir completionsdi
systemdunitdir dracutmodulesdir SHIRUDO_TARGET_PKG_CONFIG_PATH \
SHIRUDO_TARGET_STATIC_LIBDIR
-.PHONY: all help target target-deps target-deps-clean shirudo-target target-config shirudo-build docs bpf-deps install install-target install-operator clean distclean config tests proofs sparse
+.PHONY: all help target target-deps target-deps-clean shirudo-target target-config shirudo-build docs bpf-deps install install-target install-operator clean distclean config tests proofs proofs-cbmc proofs-lean4 sparse
all: config
+$(Q)$(MAKE) -f Makefile.shirudo PROFILE=operator CONFIG_MK=config.mk all
@@ -91,7 +91,7 @@ help:
' Install roles: make install-target, make install-operator' \
' Package: make -C packaging help' \
' Tests: make tests (all of them), make -C testing help' \
- ' Proofs: make proofs [PROOFS=<proof>...] (CBMC, testing/proofs/cbmc)' \
+ ' Proofs: make proofs (CBMC and Lean 4), make proofs-cbmc [PROOFS=<proof>...], make proofs-lean4' \
' Documentation: make docs (render and serve), make -C Documentation help' \
' Watch lists: make -C upatches/kernel-obs lists'
@@ -107,9 +107,14 @@ docs:
tests:
+$(Q)$(MAKE) -C testing
-proofs:
+proofs: proofs-cbmc proofs-lean4
+
+proofs-cbmc:
$(Q)testing/proofs/cbmc/run.sh $(PROOFS)
+proofs-lean4:
+ $(Q)testing/proofs/lean4/run.sh
+
# config.mk is regenerated by Makefile.config from the host's pkg-config
# state. Caches results until `make distclean`.
bpf-deps:
diff --git a/testing/proofs/cbmc/proofs.list b/testing/proofs/cbmc/proofs.list
index efcfbd8a..b2507eb7 100644
--- a/testing/proofs/cbmc/proofs.list
+++ b/testing/proofs/cbmc/proofs.list
@@ -7,3 +7,4 @@ string-sanitize --unwind 8 LEN=0-6
hex --unwind 12
io-lines --unwind 10
upatch-header --unwind 2 --unwindset memchr.0:257
+string-number-model --unwind 6
diff --git a/testing/proofs/cbmc/string-number-model.c b/testing/proofs/cbmc/string-number-model.c
new file mode 100644
index 00000000..fd5d4615
--- /dev/null
+++ b/testing/proofs/cbmc/string-number-model.c
@@ -0,0 +1,62 @@
+// SPDX-License-Identifier: BSD-2-Clause
+/*
+ * Copyright (c) 2026 Authors of shirudo
+ *
+ * parse_u64() and parse_x64() of util/string.c against the model that
+ * testing/proofs/lean4/Shirudo/Number.lean proves exact for every length:
+ * on every string of up to LEN_MAX bytes they yield the model's value, or
+ * -ERANGE exactly where the model refuses.
+ */
+
+#include <errno.h>
+#include <stdbool.h>
+
+#include "proof.h"
+#include "../../../util/string.c"
+
+#define LEN_MAX 4 /* short enough that no step reaches 2^64 */
+
+static int model_digit(char c, bool hex)
+{
+ if (c >= '0' && c <= '9')
+ return c - '0';
+ if (hex && c >= 'a' && c <= 'f')
+ return c - 'a' + 10;
+ if (hex && c >= 'A' && c <= 'F')
+ return c - 'A' + 10;
+ return -1;
+}
+
+static void against_model(bool hex)
+{
+ __u64 max, out, v = 0;
+ bool digits = true, within = true;
+ size_t len, i;
+ char *s;
+ int ret;
+
+ __CPROVER_assume(len <= LEN_MAX);
+ s = any_bytes(len);
+ for (i = 0; i < len; i++) {
+ int d = model_digit(s[i], hex);
+
+ if (d < 0) {
+ digits = false;
+ continue;
+ }
+ v = v * (hex ? 16 : 10) + (__u64)d;
+ if (v > max)
+ within = false;
+ }
+ ret = hex ? parse_x64(s, len, max, &out) : parse_u64(s, len, max, &out);
+ if (!len || !digits)
+ return;
+ __CPROVER_assert(within ? !ret && out == v : ret == -ERANGE,
+ "the model's value, or -ERANGE where it refuses");
+}
+
+void harness(void)
+{
+ against_model(false);
+ against_model(true);
+}
diff --git a/testing/proofs/lean4/Shirudo.lean b/testing/proofs/lean4/Shirudo.lean
new file mode 100644
index 00000000..6bb4b1a3
--- /dev/null
+++ b/testing/proofs/lean4/Shirudo.lean
@@ -0,0 +1,5 @@
+-- SPDX-License-Identifier: BSD-2-Clause
+-- Copyright (c) 2026 Authors of shirudo
+
+import Shirudo.Number
+import Shirudo.Chain
diff --git a/testing/proofs/lean4/Shirudo/Chain.lean b/testing/proofs/lean4/Shirudo/Chain.lean
new file mode 100644
index 00000000..f4c8232b
--- /dev/null
+++ b/testing/proofs/lean4/Shirudo/Chain.lean
@@ -0,0 +1,69 @@
+-- SPDX-License-Identifier: BSD-2-Clause
+-- Copyright (c) 2026 Authors of shirudo
+
+/-!
+The measurement register of util/chain.c. Each upatch state change
+extends it as `H(register ‖ event)`, the way a TPM extends a PCR, with an
+event that hashes a domain-separating tag and its payload. `attest verify`
+replays the eventlog and compares the result with the register the TPM
+signed. Assuming `H` is collision resistant, modelled as injective on
+(register, event) pairs and never yielding the initial value, and the
+tagged encoding of events likewise, equal registers mean the target
+measured exactly the events the log shows, in that order.
+-/
+
+namespace Shirudo.Chain
+
+variable {D K P : Type}
+
+/-- The register after `events`, the newest first. -/
+def register (H : D → D → D) (init : D) : List D → D
+ | [] => init
+ | e :: es => H (register H init es) e
+
+/-- The same register, folded over the events in the order they came. -/
+theorem register_eq_foldl (H : D → D → D) (init : D) (events : List D) :
+ register H init events = events.reverse.foldl H init := by
+ induction events with
+ | nil => rfl
+ | cons e es ih => simp [register, ih]
+
+/-- Equal registers come from equal event sequences. -/
+theorem register_injective (H : D → D → D) (init : D)
+ (hH : ∀ a b c d, H a b = H c d → a = c ∧ b = d)
+ (hinit : ∀ a b, H a b ≠ init) :
+ ∀ l1 l2 : List D, register H init l1 = register H init l2 → l1 = l2
+ | [], [], _ => rfl
+ | [], f :: fs, h => absurd h.symm (hinit _ f)
+ | e :: es, [], h => absurd h (hinit _ e)
+ | e :: es, f :: fs, h => by
+ have ⟨hr, he⟩ := hH _ _ _ _ h
+ rw [he, register_injective H init hH hinit es fs hr]
+
+theorem map_injective {α β : Type} (f : α → β) (hf : Function.Injective f) :
+ ∀ l1 l2 : List α, l1.map f = l2.map f → l1 = l2
+ | [], [], _ => rfl
+ | [], _ :: _, h => by simp at h
+ | _ :: _, [], h => by simp at h
+ | a :: as, b :: bs, h => by
+ simp only [List.map_cons, List.cons.injEq] at h
+ rw [hf h.1, map_injective f hf as bs h.2]
+
+/-- Equal registers come from the same tagged events, in the same order:
+an event can be neither left out, added, swapped for another nor moved. -/
+theorem register_tagged_injective (H : D → D → D) (init : D)
+ (encode : K → P → D)
+ (hH : ∀ a b c d, H a b = H c d → a = c ∧ b = d)
+ (hinit : ∀ a b, H a b ≠ init)
+ (henc : ∀ k p k' p', encode k p = encode k' p' → k = k' ∧ p = p')
+ (l1 l2 : List (K × P))
+ (h : register H init (l1.map fun e => encode e.1 e.2) =
+ register H init (l2.map fun e => encode e.1 e.2)) :
+ l1 = l2 := by
+ have hinj : Function.Injective (fun e : K × P => encode e.1 e.2) := by
+ intro ⟨k, p⟩ ⟨k', p'⟩ he
+ have ⟨hk, hp⟩ := henc _ _ _ _ he
+ subst hk; subst hp; rfl
+ exact map_injective _ hinj _ _ (register_injective H init hH hinit _ _ h)
+
+end Shirudo.Chain
diff --git a/testing/proofs/lean4/Shirudo/Number.lean b/testing/proofs/lean4/Shirudo/Number.lean
new file mode 100644
index 00000000..277cad08
--- /dev/null
+++ b/testing/proofs/lean4/Shirudo/Number.lean
@@ -0,0 +1,81 @@
+-- SPDX-License-Identifier: BSD-2-Clause
+-- Copyright (c) 2026 Authors of shirudo
+
+/-!
+The number parsers of util/string.c. `parse_base()` reads the digits most
+significant first and refuses with `-ERANGE` once the value would reach
+2^64 or pass `max`. For digit strings of every length it yields exactly
+the value they spell, or that refusal when the value passes `max`.
+-/
+
+namespace Shirudo.Number
+
+/-- 2^64, the first value a `__u64` cannot hold. -/
+def u64Limit : Nat := 18446744073709551616
+
+/-- The value of the digits `ds`, read most significant first onto `v`. -/
+def valueFrom (base v : Nat) (ds : List Nat) : Nat :=
+ ds.foldl (fun v d => v * base + d) v
+
+/-- One digit of `parse_base()`: the checked multiply and add, then `max`. -/
+def step (base max : Nat) : Option Nat → Nat → Option Nat
+ | none, _ => none
+ | some v, d =>
+ if v * base + d < u64Limit ∧ v * base + d ≤ max then
+ some (v * base + d)
+ else
+ none
+
+/-- `parse_base()` on the digit values `ds`; `none` is `-ERANGE`. -/
+def parse (base max : Nat) (ds : List Nat) : Option Nat :=
+ ds.foldl (step base max) (some 0)
+
+theorem foldl_none (base max : Nat) (ds : List Nat) :
+ ds.foldl (step base max) none = none := by
+ induction ds with
+ | nil => rfl
+ | cons d ds ih => simpa [List.foldl, step] using ih
+
+theorem valueFrom_ge (base v : Nat) (ds : List Nat) (hb : 0 < base) :
+ v ≤ valueFrom base v ds := by
+ induction ds generalizing v with
+ | nil => simp [valueFrom]
+ | cons d ds ih =>
+ have hm : v ≤ v * base := Nat.le_mul_of_pos_right v hb
+ have hrest := ih (v * base + d)
+ simp only [valueFrom, List.foldl] at hrest ⊢
+ omega
+
+theorem parseFrom (base max v : Nat) (ds : List Nat) (hb : 0 < base)
+ (hmax : max < u64Limit) (hv : v ≤ max) :
+ ds.foldl (step base max) (some v) =
+ if valueFrom base v ds ≤ max then some (valueFrom base v ds)
+ else none := by
+ induction ds generalizing v with
+ | nil => simp [valueFrom, hv]
+ | cons d ds ih =>
+ have hnext : valueFrom base v (d :: ds) =
+ valueFrom base (v * base + d) ds := rfl
+ rw [hnext]
+ by_cases h : v * base + d ≤ max
+ · have hs : step base max (some v) d = some (v * base + d) := by
+ simp [step, h, Nat.lt_of_le_of_lt h hmax]
+ simp only [List.foldl, hs]
+ exact ih (v * base + d) h
+ · have hs : step base max (some v) d = none := by
+ simp [step, h]
+ simp only [List.foldl, hs, foldl_none]
+ have hge := valueFrom_ge base (v * base + d) ds hb
+ have hgt : ¬ valueFrom base (v * base + d) ds ≤ max := by omega
+ simp [hgt]
+
+/-- The value of an accepted number, or `-ERANGE` exactly when it passes
+`max`, for digit strings of every length and every `max` a `__u64` holds. -/
+theorem parse_exact (base max : Nat) (ds : List Nat) (hb : 0 < base)
+ (hmax : max < u64Limit) :
+ parse base max ds =
+ if valueFrom base 0 ds ≤ max then some (valueFrom base 0 ds)
+ else none :=
+ parseFrom base max 0 ds hb hmax (Nat.zero_le _)
+
+end Shirudo.Number
diff --git a/testing/proofs/lean4/lake-manifest.json b/testing/proofs/lean4/lake-manifest.json
new file mode 100644
index 00000000..eef63837
--- /dev/null
+++ b/testing/proofs/lean4/lake-manifest.json
@@ -0,0 +1,6 @@
+{"version": "1.3.0",
+ "packagesDir": ".lake/packages",
+ "packages": [],
+ "name": "«shirudo-proofs»",
+ "lakeDir": ".lake",
+ "fixedToolchain": false}
diff --git a/testing/proofs/lean4/lakefile.toml b/testing/proofs/lean4/lakefile.toml
new file mode 100644
index 00000000..90f58904
--- /dev/null
+++ b/testing/proofs/lean4/lakefile.toml
@@ -0,0 +1,10 @@
+# SPDX-License-Identifier: BSD-2-Clause
+# Copyright (c) 2026 Authors of shirudo
+
+name = "shirudo-proofs"
+defaultTargets = ["Shirudo"]
+
+[[lean_lib]]
+name = "Shirudo"
+# A warning, a sorry among them, fails the build.
+leanOptions = { warningAsError = true }
diff --git a/testing/proofs/lean4/lean-toolchain b/testing/proofs/lean4/lean-toolchain
new file mode 100644
index 00000000..a6aff065
--- /dev/null
+++ b/testing/proofs/lean4/lean-toolchain
@@ -0,0 +1 @@
+leanprover/lean4:v4.35.0
diff --git a/testing/proofs/lean4/run.sh b/testing/proofs/lean4/run.sh
new file mode 100755
index 00000000..2d047dbe
--- /dev/null
+++ b/testing/proofs/lean4/run.sh
@@ -0,0 +1,19 @@
+#!/bin/sh
+# SPDX-License-Identifier: BSD-2-Clause
+# Copyright (c) 2026 Authors of shirudo
+#
+# testing/proofs/lean4/run.sh -- check the Lean 4 proofs of the models of
+# shirudo's algorithms in this directory. A proof left unfinished with
+# sorry, or any other warning, fails the build.
+#
+# testing/proofs/lean4/run.sh
+
+set -eu
+
+cd "$(dirname "$0")"
+command -v lake >/dev/null 2>&1 || {
+ printf 'proofs: lake not found; install elan and run elan toolchain install %s\n' \
+ "$(cat lean-toolchain)" >&2
+ exit 2
+}
+lake build