Post Fiat

Research Blog  /  30 November 2026  /  Engineering  /  68 min read

A Hands-On Lean 4 Tutorial for Blockchain Engineers

A step-by-step Lean 4 guide for blockchain engineers. We build TinyVault, a small vault whose solvency, supply conservation and u128 range are proved for every block of every length, test the compiled Lean model against a Rust reference using real checked u128 arithmetic, and link every source file.

Markdown

AI agents now write a large and growing share of protocol code, faster than anyone can review it line by line. On a blockchain that code holds money and cannot be recalled once it ships. Lean 4 gives an engineer working with agents firm ground: the agent writes the proof, and Lean’s small kernel checks it. A wrong proof is rejected no matter how confident the agent was, so the proofs themselves never need a human reader. Human attention goes to the part that is short and readable: the specification, and the statement of each theorem about it.

That changes what an engineer working with agents can promise. Unit tests check the inputs someone thought of, and fuzzers sample a state space far too large to cover. A Lean theorem covers every input and every sequence of transitions of the model it is about, including the rounding edge case and the ten-thousandth transaction. The model also compiles to a binary, so the Rust or Solidity implementation can be run against it on the same test vectors, and CI fails on any disagreement those vectors expose. The proof covers the model completely. Differential testing ties the code to the model.

Lean 4 is in use for this today. Section 2 lists Solana and Ethereum projects built with it, and Post Fiat uses it for its own protocol packages (see the companion post, Lean Verification on Post Fiat).

This guide is for engineers who have never used a theorem prover. It walks through one project, TinyVault:

  • a vault model whose mint limit depends on fixed-point rounding;
  • a failed proof that exposes a real rounding bug, and the counterexample Lean certifies;
  • a proof that the fixed vault, started in a solvent state, stays solvent, conserves supply and stays inside u128 after any block of any length;
  • a Rust reference implementation using checked u128 arithmetic, compared against the compiled Lean model on 4,024 vectors;
  • a CI script that runs all of it and confirms that five planted bugs are caught.

Everything proved here is about a Lean model. The link to Rust is differential testing against a reference implementation written for this guide; Section 5 lists what that leaves open. Every file is linked from the Appendix, and the Lean files are printed there in full. The numbers and outputs quoted below come from one run of ./ci.sh, with the lean4checker stage enabled, on Lean 4.20.0 and rustc 1.95.0. Lean 4.20.0 is the version the Post Fiat packages pin. The project has not been built on later releases.


1. What Is Lean 4?

Lean 4 is two things in one toolchain:

  1. A pure functional programming language. Its structure, inductive and pattern matching will feel familiar from Rust’s struct, enum and match. It compiles to native binaries.
  2. A theorem prover based on dependent type theory, where a mathematical statement is a type and a proof is a program of that type.

In Rust, a function type says “give me two u64 values and I return a u64”. In Lean, a type can mention values, so a type can say “give me any vault state s satisfying the invariant and any list of actions, and I return a proof that the state after executing them satisfies the invariant”.

Why a Lean proof can be trusted, whoever wrote it

Lean separates finding a proof from checking it. This is the de Bruijn criterion.

flowchart LR
    A["Engineer or AI agent<br/>writes tactic script"]
    E["Elaborator and tactics<br/>untrusted search"]
    T["Proof term<br/>explicit, fully detailed"]
    K["Kernel<br/>small trusted type checker"]
    R["lean4checker<br/>replays compiled proofs"]

    A --> E
    E --> T
    T --> K
    K --> R

Tactics, automation and language models all sit on the untrusted side. Whatever they produce is compiled to an explicit proof term, and the kernel, a small type checker, accepts or rejects that term. A missed case or an invalid step is rejected. The compiled proof files can then be replayed through the kernel again by a separate program, lean4checker. Step 5 does exactly that for TinyVault.

Where Lean sits among the other tools

TechniqueWhat it checksStrengthBlind spot
Unit testsHand-written inputsFast; runs on production codeOnly the cases the author thought of
Fuzzing and property testsThousands to millions of random inputsFinds crashes and surprising edge cases in live codeCannot show absence of a rare arithmetic or multi-step bug
Symbolic execution and bounded model checking (Halmos, Kani)All inputs up to a bound, by querying an SMT solverHighly automated; runs on Solidity or Rust directlyLoop and depth bounds; solvers stall on nonlinear arithmetic
Automated deductive verification (Certora Prover)Rules and invariants, discharged by SMT solversUnbounded for many properties; works on contract bytecodeSolver timeouts; nonlinear arithmetic often needs manual summaries
Model checking a design (TLA+ with TLC or Apalache)A protocol design, explored over finite instancesExcellent for consensus and concurrency design errorsThe specification is separate from any executable code
Interactive proof (Lean 4, Rocq, Isabelle)A theorem over all inputs and all trace lengthsInduction, arbitrary sizes, nonlinear roundingThe proof is about a model; tying it to production code is separate work

Rocq and Isabelle are mature and can extract executable code from a specification. Lean’s practical difference is that the specification language is the compiled language. The functions you prove theorems about are the functions lake build turns into a command-line binary, with no extraction step in between. That binary can answer the same test vectors as your Rust node, which is the differential oracle this guide builds in Step 6.


2. Guides and Projects to Study

Learning Lean 4

  1. The Natural Number Game. Runs in the browser with nothing to install. An hour here teaches rw, induction and exact faster than reading does.
  2. Functional Programming in Lean by David Thrane Christiansen. The book for working programmers: syntax, structure, inductive, Option and Except, monads, and Lake builds.
  3. Theorem Proving in Lean 4 by Avigad, de Moura, Kong and Ullrich. The reference for dependent types, quantifiers, tactics and induction.
  4. Mathematics in Lean. Read this when you need Mathlib for algebra or cryptography. Protocol state machines rarely do; TinyVault uses no external dependency.

Blockchain projects written in Lean 4

Descriptions below are taken from each repository’s README on 30 November 2026. Each GitHub link points at the commit that was read.

  • aeyakovenko/lean-svm is a Lean 4 to Solana sBPF compiler toolchain. aeyakovenko/lean-svm-jit is an sBPF to x86-64 JIT compiler with Lean 4 proofs and no external dependencies. aeyakovenko/percolator-lean is a cross-margin perpetuals exchange written in Lean 4, compiled to sBPF through lean-svm, with machine-checked per-market risk isolation. Its README marks it as educational and unaudited.
  • asymmetric-research/lean-svm is an executable Lean 4 model of the Solana runtime. It separates Svm/Spec (pure semantics that theorems are about) from Svm/Exec (proved executable refinements), enforces a no-sorry rule and axiom audits, and runs conformance tests against Firedancer’s test vectors. The structure of TinyVault follows the same separation on a small scale.
  • MidTermDev/lean-Solana-client is a Solana validator client written in Lean 4. Its make oracle target requires Agave’s runtime and its BLS and ZK libraries to print the same results as the Lean tests.
  • NethermindEth/EVMYulLean is an executable formal model of the EVM and Yul in Lean 4.
  • Formal Land verifies Rust and Solidity mainly through translation to Rocq (rocq-of-rust, rocq-of-solidity), with Lean work alongside. It is a good view of the same problem from the Rocq side.
  • Lean Verification on Post Fiat describes Post Fiat’s zero-dependency Lean 4.20.0 packages for Consensus v2 agreement, FastPay v3 recovery, NAVCoin vault arithmetic and bridge finality, each paired with a differential oracle.

3. Mental Model: Four Artifacts and Five Steps

A Lean theorem is a statement about a Lean definition. It says nothing about Rust or Solidity until you connect the two. A verification project therefore has four artifacts, plus a written list of what was assumed.

flowchart TD
    P["Production code<br/>Rust node or Solidity contract"]
    S["Lean specification<br/>pure functions"]
    K["Kernel-checked theorems<br/>invariants, counterexamples, witnesses"]
    O["Differential oracle<br/>one set of vectors, two implementations"]
    B["Assumptions<br/>written as hypotheses or documented limits"]

    P -- "1. transcribe" --> S
    S -- "2. prove and audit" --> K
    S -- "3. compile to a binary" --> O
    P -- "4. run the same vectors" --> O
    B -. "5. state what is assumed" .-> K

The five arrows are the five steps of the method, and the tutorial follows them in order:

  1. Transcribe the logic that matters into pure Lean functions (tutorial Step 2).
  2. Prove and audit. Prove the invariants, turn every stuck proof into a counterexample or a fix, give each theorem a concrete witness, and check that no proof rests on an unapproved axiom (Steps 3 to 5).
  3. Compile the specification into a binary that answers queries (Step 6).
  4. Run the same vectors through the binary and through the other implementation, and fail on any difference (Step 6).
  5. State what is assumed. Everything Lean did not check is written down in one place (Section 5).

4. Tutorial: Building TinyVault

TinyVault holds reserve assets and issues tokens to two users. Each token atom must stay backed by at least navFloor / unitScale asset atoms. In integers:

$$\text{assets} \cdot \text{unitScale} \;\ge\; \text{totalSupply} \cdot \text{navFloor}$$

It supports six actions. fund adds reserves. mint issues tokens, limited by a capacity computed with fixed-point rounding. redeem burns tokens and pays out assets at the floor. transfer moves tokens between the two users. pause and unpause switch a circuit breaker that rejects the other four.

stateDiagram-v2
    [*] --> Active
    Active --> Active: "fund, mint, redeem, transfer: accepted or rejected with an error"
    Active --> Paused: "pause"
    Paused --> Active: "unpause"
    Paused --> Paused: "fund, mint, redeem, transfer: rejected (paused)"

Step 1: Install Lean and create the package

Lean versions are managed by elan, which plays the role rustup plays for Rust. The official install page covers every platform. On Linux and macOS the installer is a script; download it and read it before running it:

curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh -o elan-init.sh
less elan-init.sh
sh elan-init.sh

Then install the Lean 4 extension for VS Code (leanprover.lean4). It provides the infoview, a panel that shows the goal and the hypotheses at the cursor position inside a proof. Proofs are written by moving the cursor down one tactic at a time and reading what the infoview says is left to prove. Step 3 shows what it displays.

Create a directory tiny-vault/ with three small files. lean-toolchain pins the compiler so every machine builds the same thing:

leanprover/lean4:v4.20.0

lakefile.toml configures Lake, Lean’s counterpart to Cargo:

name = "tiny_vault"
version = "0.2.0"
defaultTargets = ["TinyVault", "Audit", "tiny_vault_check"]

[leanOptions]
warningAsError = true

[[lean_lib]]
name = "TinyVault"

[[lean_lib]]
name = "Audit"

[[lean_exe]]
name = "tiny_vault_check"
root = "Main"

Three choices here are deliberate.

  • There is no [[require]] entry. The project depends only on Lean’s standard library and builds from clean in about five seconds.
  • warningAsError = true makes the compiler treat every warning in this package as an error, including the warning Lean emits for an unfinished proof (sorry). CI additionally runs lake build --wfail, which fails the build if any warning appears anywhere in the build log. The first protects every local build; the second also covers warnings from Lake itself.
  • Audit is a separate library. It imports Lean’s metaprogramming API, and keeping it out of TinyVault keeps that API out of the oracle binary: tiny_vault_check is 8.6 MB, against 148 MB when the audit lived inside the main library.

TinyVault.lean is the library root and only lists the modules:

import TinyVault.Spec
import TinyVault.Proofs

The default targets name files that later steps write. To build as you go, run lake build +TinyVault.Spec after Step 2 (the + selects one module), lake build TinyVault after Step 3, and plain lake build once Audit.lean and Main.lean exist.

Step 2: Write the specification (TinyVault/Spec.lean)

The code blocks from here on are excerpts. Download the files from the Appendix and read along; the text explains the parts that carry the argument.

A specification is ordinary code. Start with the arithmetic. Nat is Lean’s type of natural numbers, and it is unbounded: x * y never overflows. Production code uses u128. The model closes that gap by making the bound explicit and rejecting any product that would not fit:

/-- Largest value a Rust `u128` can hold. -/
def U128_MAX : Nat := 2 ^ 128 - 1
/-- `ceil(x * y / z)` over unbounded naturals (meaningful for `z > 0`). -/
def mulDivCeilNat (x y z : Nat) : Nat :=
  if (x * y) % z = 0 then (x * y) / z else (x * y) / z + 1

/-- Checked `floor(x * y / z)`: rejects `z = 0` and any product above `U128_MAX`,
    exactly like `x.checked_mul(y)` followed by a division in Rust. -/
def mulDivFloor (x y z : Nat) : Except VaultError Nat :=
  if z = 0 then .error .badConfig
  else if x * y > U128_MAX then .error .overflow
  else .ok (mulDivFloorNat x y z)

Except VaultError Nat is Lean’s Result<u128, VaultError>. There are two layers on purpose. mulDivFloorNat and mulDivCeilNat are pure arithmetic, and the rounding lemmas are proved about them. mulDivFloor and mulDivCeil add the checks a u128 implementation performs, and the vault calls only these.

Integer semantics to pin down in every model. Nat subtraction stops at zero: 3 - 5 = 0. That equals Rust’s saturating_sub and nothing else. checked_sub returns an error and Solidity 0.8 reverts, so if production code does either, the model must test a < b and return an error itself, as redeem does below. Nat multiplication and addition never overflow, so every place where production code can overflow needs an explicit bound check in the model, as above.

Now the function with the rounding decision in it. How many more token atoms can be minted? Compute the backing the current supply already needs, subtract it from the assets, and convert what is left into tokens. The backing needed is supply * navFloor / unitScale, which is usually not a whole number, so it has to be rounded. Here are both choices:

/-- Naive mint capacity: rounds the backing already owed DOWN. Intentionally flawed. -/
def mintableCapacityNaive (assets supply navFloor unitScale : Nat) : Except VaultError Nat :=
  match mulDivFloor supply navFloor unitScale with
  | .error e => .error e
  | .ok required => mulDivFloor (assets - required) unitScale navFloor

/-- Sound mint capacity: rounds the backing already owed UP.
    `assets - required` is `Nat` subtraction, which stops at zero; the Rust
    counterpart is `assets.saturating_sub(required)`. -/
def mintableCapacitySound (assets supply navFloor unitScale : Nat) : Except VaultError Nat :=
  match mulDivCeil supply navFloor unitScale with
  | .error e => .error e
  | .ok required => mulDivFloor (assets - required) unitScale navFloor

The state holds the reserves, the floor, the supply and the balances together, so that one transition function sees all of them:

/-- Vault state. `navFloor / unitScale` is the minimum backing per token atom. -/
structure VaultState where
  assets       : Nat
  navFloor     : Nat
  unitScale    : Nat
  totalSupply  : Nat
  aliceBalance : Nat
  bobBalance   : Nat
  paused       : Bool
  deriving Repr, DecidableEq

The transition function stepWith takes the capacity function as a parameter. The real vault is stepWith mintableCapacitySound, named step. The flawed vault is stepWith mintableCapacityNaive, named stepNaive, and exists only so Step 4 can exhibit the bug on the state machine. This is the mint branch:

  | .mint who amt =>
    if s.paused then .error .paused
    else if amt = 0 then .error .zeroAmount
    else match capacity s.assets s.totalSupply s.navFloor s.unitScale with
      | .error e => .error e
      | .ok cap =>
        if amt > cap then .error .exceedsCapacity
        else if s.totalSupply + amt > U128_MAX then .error .overflow
        else match who with
          | .alice => .ok { s with totalSupply := s.totalSupply + amt,
                                   aliceBalance := s.aliceBalance + amt }
          | .bob   => .ok { s with totalSupply := s.totalSupply + amt,
                                   bobBalance := s.bobBalance + amt }

redeem rounds in the other direction. It pays out floor(amount * navFloor / unitScale) assets, so the fraction of an atom stays in the vault. The rule in both places is the same: round against whoever is taking value out.

Last, block execution. A block does not stop at the first rejected transaction. It records the failure and continues:

/-- Apply one action the way a block does: a rejected action leaves the state
    untouched and records its error as a receipt. -/
def applyAction (s : VaultState) (act : Action) : VaultState × Option VaultError :=
  match step s act with
  | .ok s'    => (s', none)
  | .error e  => (s, some e)

/-- Execute a block of actions in order, continuing past rejected ones.
    Returns the final state and one receipt per action. `Main.lean` runs this
    function, and `Proofs.lean` proves the invariant for this function. -/
def execBlock (s : VaultState) : List Action → VaultState × List (Option VaultError)
  | [] => (s, [])
  | act :: rest =>
    let r := applyAction s act
    let out := execBlock r.1 rest
    (out.1, r.2 :: out.2)

execBlock is the one function that matters for the rest of the guide. The main theorem is about it, and the oracle binary runs it.

Prop and Bool. amt = 0 is a Prop, a statement that can be proved. s.paused is a Bool, a value computed at run time. if accepts a Prop whenever Lean can decide it by computation, which it can for comparisons of naturals. Writing conditions as Prop (=, >, ≤) instead of Bool (==) keeps proofs short, because hypotheses come out in the form the arithmetic tactics expect.

Step 3: Prove the invariant (TinyVault/Proofs.lean)

A theorem is proved inside a by block with tactics. Each tactic transforms the current goal until nothing is left. These are the tactics TinyVault uses:

TacticMeaningUsed here for
unfold fReplace f by its definitionOpening mulDivCeilNat, Solvent, step
have h := ...Introduce an intermediate factBringing a rounding lemma into scope
rw [eq]Rewrite the goal with an equation(a + b) * c = a * c + b * c
omegaDecide linear arithmetic over Nat and IntClosing every inequality goal
by_cases h : pSplit on whether p holdsRemainder zero or non-zero
cases xOne goal per constructor of xEach Action; ok or error
splitOne goal per branch of an if or matchWalking down the guards of step
simp only [...]Simplify with the listed rules onlyTurning .ok a = .ok b into a = b
subst hReplace a variable using h : x = eSubstituting the new state
show tRestate the goal in an equal formReducing { s with ... }.field
simp [...]Simplify with the listed rules plus Lean’s default setShowing a failed call cannot equal .ok
obtain ⟨a, b⟩ := hSplit a hypothesis h : A ∧ B into its partsTaking the invariant apart
rename_i hName a hypothesis that split left unnamedReferring to a guard that was passed
apply lemmaReduce the goal to the premises of lemmaMonotonicity of division
exact eSupply the proof term directlyAssembling the parts of the invariant
dsimp onlyReduce { s with ... }.field to the field’s valuePreparing a goal for omega
t1 <;> t2, all_goals tRun a tactic on every open goalHandling Alice and Bob with one script
intro hAssume the left side of an implication or a negationProving that an error cannot occur
induction xsInduction over a listBlocks of any length
decide, rflEvaluate a concrete statementCounterexamples and witnesses

A rounding lemma. The proofs need one fact about mulDivCeilNat: the result q satisfies x * y ≤ q * z < x * y + z.

theorem mulDivCeilNat_spec (x y z : Nat) (hz : z > 0) :
    x * y ≤ mulDivCeilNat x y z * z ∧ mulDivCeilNat x y z * z < x * y + z := by
  unfold mulDivCeilNat
  have hdiv := Nat.div_add_mod (x * y) z
  have hmod := Nat.mod_lt (x * y) hz
  rw [Nat.mul_comm z ((x * y) / z)] at hdiv
  by_cases hrem : (x * y) % z = 0
  · rw [if_pos hrem]
    omega
  · rw [if_neg hrem, Nat.add_mul, Nat.one_mul]
    omega

hdiv is the division identity z * (p / z) + p % z = p, and hmod says the remainder is below z. by_cases splits on the if in the definition. Then omega finishes each case.

With the cursor at the start of the last bullet, the case where the remainder is not zero, the infoview shows this. Hypotheses are above the ⊢, the goal is below it:

x y z : Nat
hz : z > 0
hdiv : x * y / z * z + x * y % z = x * y
hmod : x * y % z < z
hrem : ¬x * y % z = 0
⊢ x * y ≤ (if x * y % z = 0 then x * y / z else x * y / z + 1) * z ∧
    (if x * y % z = 0 then x * y / z else x * y / z + 1) * z < x * y + z

After rw [if_neg hrem, Nat.add_mul, Nat.one_mul] the if is gone and the product is multiplied out:

⊢ x * y ≤ x * y / z * z + z ∧ x * y / z * z + z < x * y + z

Now the goal and the hypotheses mention the same three quantities, x * y, x * y / z * z and x * y % z, and the statement is linear in them.

One idea makes this work, and the same idea carries the whole project. omega decides linear arithmetic only, and x * y is not linear. omega copes by treating each product it cannot see through as one opaque unknown. To omega the goal above is about three unknowns with linear relations between them. The job of the lines before omega is to put every product into the same shape (Nat.mul_comm, Nat.add_mul) so that equal products are recognised as the same unknown.

The invariant. Three properties, in two groups:

/-- Balances add up to the supply. -/
def Conserved (s : VaultState) : Prop :=
  s.aliceBalance + s.bobBalance = s.totalSupply

/-- Every token atom is backed at the NAV floor. -/
def Solvent (s : VaultState) : Prop :=
  s.totalSupply * s.navFloor ≤ s.assets * s.unitScale

/-- The two running totals fit in a `u128`. -/
def InRange (s : VaultState) : Prop :=
  s.assets ≤ U128_MAX ∧ s.totalSupply ≤ U128_MAX

/-- What a fixed-width implementation needs: balances add up and totals fit. -/
def Bounded (s : VaultState) : Prop :=
  Conserved s ∧ InRange s

/-- The full vault invariant. -/
def Inv (s : VaultState) : Prop :=
  Bounded s ∧ Solvent s

Bounded is separate from Solvent because it holds in more places. The vault preserves Bounded from any starting state, solvent or not. It preserves Solvent only if it started solvent. Stating the two separately keeps each theorem’s hypothesis as weak as it can be, which matters in Step 6.

One step. Two theorems cover a single accepted action: step_preserves_bounded (if Bounded s and step s act = .ok s' then Bounded s') and step_preserves_solvent (the same for Solvent). Each proof takes one case per action and walks down the guards with split. Every guard that returns an error contradicts the hypothesis hstep that the step succeeded, and cases hstep closes it. Here is the mint case of the solvency proof. hs is solvency before the step.

  | mint who amt =>
    simp only at hstep
    split at hstep
    · cases hstep
    · split at hstep
      · cases hstep
      · cases hcap : mintableCapacitySound s.assets s.totalSupply s.navFloor s.unitScale with
        | error e => simp [hcap] at hstep
        | ok cap =>
          obtain ⟨hF, hU, hcapEq⟩ := mintableCapacitySound_ok hcap
          simp only [hcap] at hstep
          split at hstep
          · cases hstep
          · split at hstep
            · cases hstep
            · have hsolv : (s.totalSupply + amt) * s.navFloor ≤ s.assets * s.unitScale :=
                soundCap_preserves_solvency hF hU hs (by omega)
              cases who <;> simp only [Except.ok.injEq] at hstep <;> subst hstep <;> exact hsolv

Read it from the top. The first two splits dispose of the paused and zero-amount guards. cases hcap asks whether the capacity call failed; if it did, the step failed too. If it returned cap, the helper lemma mintableCapacitySound_ok extracts three facts: navFloor > 0, unitScale > 0, and cap equals the pure formula. Two more splits leave the branch where amt ≤ cap and the new supply fits in u128. There soundCap_preserves_solvency, proved in Step 4, gives solvency after the mint. The last line handles Alice and Bob together: turn .ok newState = .ok s' into newState = s', substitute, and the goal is exactly hsolv.

Any block. With the single step done, the main theorem is four lines:

theorem execBlock_preserves_inv {s : VaultState} (acts : List Action) (hinv : Inv s) :
    Inv (execBlock s acts).1 := by
  induction acts generalizing s with
  | nil => exact hinv
  | cons act rest ih => exact ih (applyAction_preserves_inv act hinv)

An empty block leaves the state alone. A block act :: rest applies act, which preserves the invariant whether it was accepted or rejected (applyAction_preserves_inv), and then runs rest from the new state, where the induction hypothesis ih applies. generalizing s makes the hypothesis hold for every starting state, which is needed because the state changes after the first action. The theorem covers blocks of every length, with any mixture of accepted and rejected actions, at every u128 magnitude, because overflow is part of the model. Its one hypothesis is Inv s: the block must start in a state that satisfies the invariant.

Three companions are proved the same way:

TheoremStatement
execBlock_preserves_boundedFrom any state with Bounded s, solvent or not, every block ends in a Bounded state
bounded_balances_fitIn a Bounded state each balance is at most U128_MAX, although step never bound-checks a balance
redeem_never_short_of_assetsIn a state with Inv s, no redemption is refused with insufficientAssets. It can still be refused as overflow when amount * navFloor exceeds u128, or as badConfig when unitScale is zero

Step 4: When a proof gets stuck

The most useful moment in this work is when Lean refuses a proof. Suppose the vault used mintableCapacityNaive. The theorem needed in the mint case would be: if the vault is solvent and delta is at most the naive capacity, the vault is solvent after minting delta. The attempt is in scratch/NaiveAttempt.lean, and Lean rejects it:

theorem naiveCap_preserves_solvency_attempt {A S F U delta : Nat}
    (hF : F > 0) (hU : U > 0)
    (hinit : S * F ≤ A * U)
    (hdelta : delta ≤ mulDivFloorNat (A - mulDivFloorNat S F U) U F) :
    (S + delta) * F ≤ A * U := by
  have hreq := (mulDivFloorNat_spec S F U hU).1
  have hfloor := (mulDivFloorNat_spec (A - mulDivFloorNat S F U) U F hF).1
  have hmul : delta * F ≤ mulDivFloorNat (A - mulDivFloorNat S F U) U F * F :=
    Nat.mul_le_mul_right F hdelta
  rw [Nat.sub_mul] at hfloor
  rw [Nat.add_mul]
  omega
scratch/NaiveAttempt.lean:26:2: error: omega could not prove the goal:
a possible counterexample may satisfy the constraints
  ...
  c - f ≥ 0
  c - f - g ≤ 0
  c - f - g + i ≥ 1
  ...
where
 c := ↑S * ↑F
 f := ↑(mulDivFloorNat S F U) * ↑U
 g := ↑(A * U - mulDivFloorNat S F U * U)
 i := ↑delta * ↑F

The output names the problem. c is the backing the supply needs, scaled by U. f is the backing the naive formula reserved, scaled the same way. The only relation omega has between them is c - f ≥ 0: the reserved amount is at most the needed amount. The proof needs the opposite, f ≥ c. Rounding down reserves too little whenever U does not divide S * F.

That tells you where to look for a counterexample: pick numbers where the division leaves a remainder. With A = 100, S = 999, F = 100, U = 1000, the needed backing is 99.9. Rounding down reserves 99, leaves 1 asset atom, and reports a capacity of 10 token atoms. Minting 10 needs 1009 * 100 = 100,900 against 100 * 1000 = 100,000 available. Lean confirms it by evaluation:

/-- The naive capacity admits a mint that breaks solvency. -/
theorem naiveCapacity_breaks_solvency_example :
    999 * 100 ≤ 100 * 1000 ∧
    mintableCapacityNaive 100 999 100 1000 = .ok 10 ∧
    ¬ ((999 + 10) * 100 ≤ 100 * 1000) :=
  ⟨by decide, rfl, by decide⟩

And on the state machine, where it matters:

theorem naive_vault_breaks_solvency :
    let s : VaultState :=
      { assets := 100, navFloor := 100, unitScale := 1000,
        totalSupply := 999, aliceBalance := 999, bobBalance := 0, paused := false }
    Inv s ∧
    (∃ s', stepNaive s (.mint .alice 10) = .ok s' ∧ ¬ Solvent s') ∧
    step s (.mint .alice 10) = .error .exceedsCapacity :=
  ⟨by decide, ⟨_, rfl, by decide⟩, rfl⟩

From a state satisfying the full invariant, the naive vault accepts a mint and lands in an insolvent state. The real vault rejects the same mint.

The fix. Round the reserved backing up. The ceiling lemma from Step 3 supplies the fact the stuck proof was missing, S * F ≤ required * U, and the same proof script now closes:

/-- Soundness: any mint within the sound capacity keeps the vault solvent. -/
theorem soundCap_preserves_solvency {A S F U delta : Nat}
    (hF : F > 0) (hU : U > 0)
    (hinit : S * F ≤ A * U)
    (hdelta : delta ≤ soundCapNat A S F U) :
    (S + delta) * F ≤ A * U := by
  unfold soundCapNat at hdelta
  have hceil := (mulDivCeilNat_spec S F U hU).1
  have hfloor := (mulDivFloorNat_spec (A - mulDivCeilNat S F U) U F hF).1
  have hmul : delta * F ≤ mulDivFloorNat (A - mulDivCeilNat S F U) U F * F :=
    Nat.mul_le_mul_right F hdelta
  rw [Nat.sub_mul] at hfloor
  rw [Nat.add_mul]
  omega

soundCapNat A S F U is the pure value mintableCapacitySound returns when no check fails. The hypothesis hinit is necessary: a vault that starts under-backed gets capacity 0, and minting nothing leaves it under-backed.

How much capacity does the fix give up? A soundness theorem alone is weak. A capacity function that always returned 0 would satisfy it. So the project also proves how close the sound capacity is to the best possible one. The largest safe mint, with no intermediate rounding, is

def exactCapNat (A S F U : Nat) : Nat :=
  (A * U - S * F) / F

and four theorems pin the sound capacity against it:

TheoremStatement
exactCap_preserves_solvencyMinting up to exactCapNat keeps the vault solvent
exactCap_is_maximalMinting exactCapNat + 1 always breaks solvency
soundCap_le_exactCapsoundCapNat ≤ exactCapNat
exactCap_le_soundCap_addexactCapNat ≤ soundCapNat + U / F + 1

So the sound capacity is never above the true maximum and never more than U / F + 1 atoms below it. On the counterexample input the three values are: naive 10, exact 1, sound 0 (capacity_comparison_example). The sound vault refuses one atom it could safely have minted, and the bound allows it to refuse up to eleven there.

These four theorems are about the pure formulas. The function the vault runs adds the u128 checks, and there the picture has one more part. The two-step form multiplies the unreserved remainder (assets - required) * unitScale, and the exact form multiplies assets * unitScale in full, so the two-step form overflows later and never earlier. But it does overflow: a vault holding far more reserves than its supply needs gets overflow from the capacity call, and every mint is rejected until the product fits. The model fails closed, which keeps the solvency theorem true, and it means the U / F + 1 bound applies only when no check fires. A production vault that must mint at those magnitudes needs a 256-bit intermediate product, and the model should then say so too.

Step 5: Witnesses and the axiom audit (TinyVault/Proofs.lean, Audit.lean)

A green build can still mislead in two ways.

Vacuous theorems. If the hypotheses of a theorem can never all hold, the theorem is true and says nothing. The defence is a concrete instance that satisfies the hypotheses, evaluated by the kernel. Every theorem family in TinyVault has one:

WitnessWhat it shows
soundCap_witnessAt (200, 999, 100, 1000) the sound capacity is 1000 and minting all of it keeps solvency: the soundness theorem applies with a non-zero mint
execBlock_witnessA nine-action block from an empty vault: fund, mint, transfer, redeem, pause, a mint rejected as paused, unpause, a mint rejected for capacity, a redeem rejected for balance. Inv holds before and after
naive_vault_breaks_solvencyInv holds in a state where the naive vault fails
pause_reaches_pausedpause is accepted from every state and lands in a paused one, so the paused state is reachable
overflow_witnessWith assets = U128_MAX, fund 1 is rejected as overflow: the u128 checks can fire
execBlock_bounded_witnessA block from an under-backed state: Bounded holds, Inv does not, a redemption is refused with insufficientAssets, and balances still add up at the end
redeem_witnessFrom a state with Inv, redeeming the whole supply pays out all assets and leaves Inv intact
paused_witnessA paused vault refuses a transfer the balance would cover, and accepts it after unpause
exactCap_witnessOn the counterexample input, minting 1 atom is safe and minting 2 is not
capacity_comparison_exampleNaive 10, exact 1, sound 0 on one input: the tightness bounds hold with the sound capacity strictly below the exact one
theorem execBlock_witness :
    let s0 : VaultState :=
      { assets := 0, navFloor := 100, unitScale := 1000,
        totalSupply := 0, aliceBalance := 0, bobBalance := 0, paused := false }
    let block : List Action :=
      [.fund 200, .mint .alice 1000, .transfer .alice 400, .redeem .bob 150,
       .pause, .mint .alice 1, .unpause, .mint .alice 2000, .redeem .bob 9999]
    Inv s0 ∧
    execBlock s0 block =
      ({ assets := 185, navFloor := 100, unitScale := 1000,
         totalSupply := 850, aliceBalance := 600, bobBalance := 250, paused := false },
       [none, none, none, none, none, some .paused, none,
        some .exceedsCapacity, some .insufficientBalance]) ∧
    Inv (execBlock s0 block).1 :=
  ⟨by decide, by decide, by decide⟩

Hidden axioms. sorry closes any goal by appealing to an axiom called sorryAx, and a user-declared axiom can assert anything. Audit.lean runs at build time and fails the build in four situations: a theorem in its required list is missing, the number of hand-written theorems in the namespace differs from the list, a vault module declares something outside the namespace, or any definition or theorem in the TinyVault namespace depends on an axiom other than Lean’s three standard ones. Those are propext (propositions that imply each other are equal), Quot.sound (quotient types behave as expected) and Classical.choice (classical reasoning). They are part of Lean’s ordinary logic and nearly every Lean development accepts them. The audit discovers the constants itself by walking the environment, so a new theorem cannot be left out of the audit by forgetting to list it.

Planting an axiom shows the audit working. Adding these two lines to Proofs.lean

axiom trustMe : ∀ s : VaultState, Solvent s
theorem everything_is_solvent (s : VaultState) : Solvent s := trustMe s

makes lake build fail with

error: Audit.lean:59:0: TinyVault.everything_is_solvent depends on disallowed axiom TinyVault.trustMe

(ci.sh stops even earlier, at its text scan for the word axiom. The scan is a cheap first filter that a determined author can get around; the audit is the check that cannot be talked past.)

Audit.lean uses #eval to run a metaprogram, and ci.sh bans #eval and run_cmd in the specification, the proofs and the driver. Both rules stand. Build-time code execution is how an agent or a careless edit could tamper with a build, so it is allowed in exactly one file, which contains no vault logic and no theorems, and which a reviewer reads in full.

Finally lean4checker replays the compiled TinyVault.Spec and TinyVault.Proofs through the kernel in a separate process. lean4checker is built from source at the tag matching the toolchain. Clone it next to the project, not inside it, so the scan in ci.sh does not read its sources:

git clone --branch v4.20.0 https://github.com/leanprover/lean4checker ../lean4checker
(cd ../lean4checker && lake build)
LEAN4CHECKER=$PWD/../lean4checker/.lake/build/bin/lean4checker ./ci.sh

Without LEAN4CHECKER, ci.sh fails at that stage and prints these commands. ./ci.sh --skip-replay leaves the stage out and says so in its last line.

Step 6: The differential oracle (Main.lean, oracle_test.rs)

Arrows 3 and 4 of the mental model connect the Lean model to another implementation. Main.lean is a thin driver: it parses one query per line, calls mintableCapacitySound or execBlock, and prints the result. It contains no vault logic of its own. oracle_test.rs is a single Rust file with no dependencies. It implements the same vault with real u128 arithmetic (checked_mul, checked_add, saturating_sub), generates the vectors, runs the Lean binary on them, and compares every line.

flowchart LR
    V["4,024 vectors<br/>24 boundary, 2,000 capacity, 2,000 blocks"]
    L["tiny_vault_check --oracle<br/>compiled Lean: execBlock"]
    R["oracle_test.rs<br/>Rust u128, checked arithmetic"]
    D["Line-by-line comparison<br/>results, receipts, final states"]

    V --> L
    V --> R
    L --> D
    R --> D

The wire format is one line in, one line out:

cap 100 999 100 1000
  -> ok 0
block 0 100 1000 0 0 0 fund:200 mint:alice:1000 xfer:alice:400 redeem:bob:150 pause mint:alice:1 unpause mint:alice:2000 redeem:bob:9999
  -> ok,ok,ok,ok,ok,err_paused,ok,err_capacity,err_balance | 185 850 600 250 0 | inv 1 1

A block query gives the starting assets, floor, scale, two balances and paused flag, then the actions. The answer is one receipt per action, the final assets, supply, balances and paused flag, and two bits saying whether Inv held before and after. The second line above is execBlock_witness again, this time computed by the compiled binary and by Rust.

Four design choices make the comparison worth something.

The oracle runs the function that was proved. Main.lean calls execBlock, the function in execBlock_preserves_inv. It does not re-implement block execution.

The reference uses fixed-width integers. Vectors are drawn in three size classes, the largest reaching u128::MAX, and the hand-written boundary set includes the last product that fits and the first that does not. cap 0 340282366920938463463374607431768211455 1 1 succeeds; the same query with navFloor = 2 must return err_overflow from both sides.

Starting states are not all nice. The generator sets the starting reserves relative to what the supply needs at the floor: at or above it for 70% of random blocks, strictly below it for 20%, and unrelated to it for 10%. In this run 1,494 blocks start inside Inv, where the main theorem applies, and 513 start outside, where only execBlock_preserves_bounded applies. The Rust side also checks the theorems as it goes: after every action it asserts that balances add up, and for blocks that started inside Inv it asserts that Inv still holds (comparing the two products in 256 bits) and that no redemption was refused for lack of assets. All 96 err_assets receipts come from blocks that started outside Inv, as redeem_never_short_of_assets requires.

Coverage is reported. The generator tracks the vault state while it builds each block, so it can aim at the edges: a mint of exactly the capacity, a mint of capacity plus one, a redeem of balance plus one. The run prints how often each outcome occurred.

LEAN4CHECKER=$PWD/../lean4checker/.lake/build/bin/lean4checker ./ci.sh
[1/6] banned-construct scan (every .lean file except Audit.lean and scratch/)
[2/6] lake build --wfail (kernel-checks every proof, then runs Audit.lean)
info: Audit.lean:59:0: [TinyVault] audit passed: 155 constants axiom-checked, 30 theorems, all 30 required theorems present
Build completed successfully.
[3/6] independent kernel replay with lean4checker
  replayed TinyVault.Spec and TinyVault.Proofs: accepted
[4/6] the Step 4 naive proof attempt must still be rejected
  rejected as documented: omega could not prove the goal
[5/6] Rust u128 differential oracle
TinyVault differential oracle PASS: 4024/4024 vectors matched (24 boundary + 2000 capacity + 2000 blocks of 12 actions, seed 6073471718092002636)
Outcomes exercised (Lean and Rust agree on every one):
      96  action: err_assets
     849  action: err_balance
    1253  action: err_capacity
     293  action: err_config
     527  action: err_overflow
    2231  action: err_paused
    1748  action: err_zero
   17024  action: ok
    1494  block: starts in Inv
     513  block: starts outside Inv
      70  cap: err_config
     195  cap: err_overflow
    1076  cap: ok, non-zero
     670  cap: ok, zero
       6  parse_err
[6/6] mutation check: each planted Rust bug must make the oracle fail
  detected 'floor': FAIL at vector 0 (hand-written boundary vector)
  detected 'wrapping': FAIL at vector 14 (hand-written boundary vector)
  detected 'payout-ceil': FAIL at vector 2024 (random block)
  detected 'strict-cap': FAIL at vector 20 (hand-written boundary vector)
  detected 'paused-transfer': FAIL at vector 2036 (random block)
ALL CHECKS PASSED (replay included)

(Lake’s per-file progress lines are omitted, and it prints the full path to Audit.lean.)

Stage 6 of that output is the test of the test. A differential oracle that cannot fail proves nothing, so oracle_test.rs carries five planted bugs behind a --mutant flag: rounding the reserved backing down (the Step 4 bug), multiplying with wrap-around instead of checked_mul, rounding redemption payouts up, rejecting a mint of exactly the capacity, and letting transfers through while paused. Each must make the comparison report a mismatch, and each does. Three are caught by hand-written boundary vectors and two only by random blocks. The six parse_err results are deliberate too: malformed lines and numbers above u128::MAX, which both sides must refuse.

What the proofs say about the Rust code. The Rust mint arm uses checked arithmetic where the model has a check, and a plain += on the balance:

                let cap = mintable_capacity(
                    self.assets, self.total_supply, self.nav_floor, self.unit_scale, m)?;
                if amt > cap || (m == Mutant::StrictCap && amt == cap) {
                    return Err(ExceedsCapacity);
                }
                self.total_supply = self.total_supply.checked_add(amt).ok_or(Overflow)?;
                *self.balance(who) += amt;

(m selects a planted bug and is Mutant::None in a normal run.) In the model that += cannot overflow. Both drivers build the starting state with totalSupply = alice + bob and reject a sum above U128_MAX, so every block starts Bounded. execBlock_preserves_bounded then says every later state is Bounded, and bounded_balances_fit says every balance fits. Solvency is not needed for this, which is why the two invariants were separated in Step 3. The same argument covers the unguarded totalSupply - amt in redeem: the amount is at most a balance, and a balance is at most the supply.

That is a theorem about the Lean model. It transfers to the Rust code only as far as the two agree, and the oracle tests that agreement without proving it. So keep the runtime checks: the file is compiled with -C overflow-checks=on, and a drift between model and code aborts the run. The proof tells you the check never fires in a correct implementation. It is not a reason to remove the check from production code.

Using this on a real codebase. oracle_test.rs has three parts: a vault section, a wire-format section and a generator. To test production Rust, delete the vault section and call your crate from eval_cap and eval_block. To test Solidity, keep the Lean binary and the vector file and have a Foundry test read the expected lines and assert them against the deployed contract. The generator steers its random blocks with the Rust reference, so vary it: ./oracle_test --seed N draws a different vector set, and a second generator written against the production code removes the shared bias.

Step 7: Working with AI coding agents

Lean suits AI agents because the kernel rejects a wrong proof no matter how confident its author was. An engineer can state a theorem, let an agent iterate against the goals Lean reports, and accept the result on the kernel’s word.

The kernel checks that a proof matches its statement. It does not check that the statement is the one you wanted. Two rules follow.

  1. Mechanical checks in CI. Everything in ci.sh: the banned-construct scan, warnings as errors, the axiom audit with its required-theorem list, lean4checker, the oracle and its mutants.
  2. Human review of four things.
    • Statement diffs. Confirm no conclusion was weakened and no hypothesis was added. Audit.lean catches a deleted theorem; it does not catch a reworded one.
    • Hypotheses in plain language. Read every assumption and ask whether production really guarantees it.
    • Witnesses. Every universal theorem needs a concrete instance, and the instance should be an interesting one, not a zero.
    • The model against the code. Confirm the Lean specification matches production and the oracle exercises the paths that changed.

5. What TinyVault Does Not Prove

This is the fifth arrow of the mental model: the assumptions, in one place.

  • The starting state is assumed. The main theorem begins from a state satisfying Inv. The model has no genesis constructor and no configuration validation. A deployment must establish Inv for its first state, by construction or by a check, before the theorem says anything about it.
  • Overflow can make minting and redeeming unavailable. When (assets - required) * unitScale or totalSupply * navFloor exceeds u128::MAX, the capacity call returns overflow and mints are rejected. A redemption is rejected the same way when amount * navFloor does not fit, and has to be split. Solvency is safe; availability is not, and the tightness bound of Step 4 does not apply there.
  • The Rust file is a reference implementation written for this guide. Agreement on 4,024 vectors shows that two implementations in two languages, one of them using real u128 arithmetic, compute the same results, and the mutation check shows the comparison detects rounding and overflow bugs. It says nothing about any deployed system until the vault section is replaced with calls into that system.
  • The oracle binary is compiled code. The kernel checks the definitions. The binary is produced from them by Lean’s compiler and runtime, which are trusted. The oracle is test evidence about the model; the theorems are proof about the model.
  • There is no caller. pause and unpause are accepted from anyone. Authorization is outside the model, and paused_rejects_value_actions is a statement about the flag, not about access control.
  • Safety only. The theorems say bad states are unreachable. They do not say a user can always redeem, and they say nothing about ordering, networking or time.
  • Two users, hard-coded. aliceBalance and bobBalance are fields, and some proof cases are written once per user. A real ledger maps addresses to balances, conservation becomes a sum over that map, and the proofs need lemmas about updating one entry of it.
  • The floor is a constant. navFloor and unitScale never change. A vault whose floor moves needs its own solvency argument.
  • Statements are reviewed by people. A theorem with the right name and the wrong statement passes every mechanical check here.

6. Checklist

  • Start with no dependencies. Add Mathlib when a proof needs algebra the standard library lacks.
  • Write assumptions as explicit hypotheses of the theorems that need them. Never declare them as global axioms, which every theorem then inherits silently.
  • Model integer behaviour explicitly: a bound check wherever production can overflow, an error wherever production reverts on underflow.
  • Prove theorems about the function the oracle runs. A separate executor in the driver is a second, unproved specification.
  • Give every universal theorem a non-trivial witness, and prove how tight a conservative bound is.
  • State each theorem with the weakest hypothesis that works, and check that the place you cite it actually satisfies that hypothesis.
  • Keep runtime checks in production code even where a theorem says they cannot fire.
  • Make the oracle fail on purpose before trusting it when it passes.

Appendix: Source Files

These are the files the run above used. Every Lean, Rust and TOML code block in this post is checked against them by a script, and the listings below are generated from them.

Download: lean-toolchain, lakefile.toml, TinyVault.lean, TinyVault/Spec.lean, TinyVault/Proofs.lean, Audit.lean, Main.lean, scratch/NaiveAttempt.lean, ci.sh, oracle_test.rs.

lean-toolchain, lakefile.toml and TinyVault.lean appear in full in Step 1. The Lean files and ci.sh follow. oracle_test.rs is 591 lines, most of it the vector generator, and is provided as a download.

A.1 TinyVault/Spec.lean

namespace TinyVault

/-!
# TinyVault specification (`TinyVault/Spec.lean`)

A pure, executable Lean 4 model of a two-user vault whose token supply must stay
backed by reserve assets at a NAV floor:

    assets * unitScale ≥ totalSupply * navFloor

Every arithmetic step mirrors Rust checked `u128` arithmetic: a product that does
not fit in 128 bits is an `overflow` error, not a silently larger number.
-/

/-- Largest value a Rust `u128` can hold. -/
def U128_MAX : Nat := 2 ^ 128 - 1

inductive VaultError where
  | paused
  | zeroAmount
  | insufficientBalance
  | insufficientAssets
  | exceedsCapacity
  | badConfig
  | overflow
  deriving Repr, DecidableEq

/-- `floor(x * y / z)` over unbounded naturals (meaningful for `z > 0`). -/
def mulDivFloorNat (x y z : Nat) : Nat :=
  (x * y) / z

/-- `ceil(x * y / z)` over unbounded naturals (meaningful for `z > 0`). -/
def mulDivCeilNat (x y z : Nat) : Nat :=
  if (x * y) % z = 0 then (x * y) / z else (x * y) / z + 1

/-- Checked `floor(x * y / z)`: rejects `z = 0` and any product above `U128_MAX`,
    exactly like `x.checked_mul(y)` followed by a division in Rust. -/
def mulDivFloor (x y z : Nat) : Except VaultError Nat :=
  if z = 0 then .error .badConfig
  else if x * y > U128_MAX then .error .overflow
  else .ok (mulDivFloorNat x y z)

/-- Checked `ceil(x * y / z)` with the same two rejections. -/
def mulDivCeil (x y z : Nat) : Except VaultError Nat :=
  if z = 0 then .error .badConfig
  else if x * y > U128_MAX then .error .overflow
  else .ok (mulDivCeilNat x y z)

/-- Naive mint capacity: rounds the backing already owed DOWN. Intentionally flawed. -/
def mintableCapacityNaive (assets supply navFloor unitScale : Nat) : Except VaultError Nat :=
  match mulDivFloor supply navFloor unitScale with
  | .error e => .error e
  | .ok required => mulDivFloor (assets - required) unitScale navFloor

/-- Sound mint capacity: rounds the backing already owed UP.
    `assets - required` is `Nat` subtraction, which stops at zero; the Rust
    counterpart is `assets.saturating_sub(required)`. -/
def mintableCapacitySound (assets supply navFloor unitScale : Nat) : Except VaultError Nat :=
  match mulDivCeil supply navFloor unitScale with
  | .error e => .error e
  | .ok required => mulDivFloor (assets - required) unitScale navFloor

/-- Vault state. `navFloor / unitScale` is the minimum backing per token atom. -/
structure VaultState where
  assets       : Nat
  navFloor     : Nat
  unitScale    : Nat
  totalSupply  : Nat
  aliceBalance : Nat
  bobBalance   : Nat
  paused       : Bool
  deriving Repr, DecidableEq

inductive User where
  | alice
  | bob
  deriving Repr, DecidableEq

inductive Action where
  | fund     (amount : Nat)                  -- add reserve assets
  | mint     (who : User) (amount : Nat)     -- issue tokens, limited by capacity
  | redeem   (who : User) (amount : Nat)     -- burn tokens, pay out assets at the floor
  | transfer (fromUser : User) (amount : Nat)
  | pause
  | unpause
  deriving Repr, DecidableEq

/-- One state transition, parameterised by the capacity function so the flawed
    and the sound vault share every other line. -/
def stepWith (capacity : Nat → Nat → Nat → Nat → Except VaultError Nat)
    (s : VaultState) (act : Action) : Except VaultError VaultState :=
  match act with
  | .pause   => .ok { s with paused := true }
  | .unpause => .ok { s with paused := false }
  | .fund amt =>
    if s.paused then .error .paused
    else if amt = 0 then .error .zeroAmount
    else if s.assets + amt > U128_MAX then .error .overflow
    else .ok { s with assets := s.assets + amt }
  | .mint who amt =>
    if s.paused then .error .paused
    else if amt = 0 then .error .zeroAmount
    else match capacity s.assets s.totalSupply s.navFloor s.unitScale with
      | .error e => .error e
      | .ok cap =>
        if amt > cap then .error .exceedsCapacity
        else if s.totalSupply + amt > U128_MAX then .error .overflow
        else match who with
          | .alice => .ok { s with totalSupply := s.totalSupply + amt,
                                   aliceBalance := s.aliceBalance + amt }
          | .bob   => .ok { s with totalSupply := s.totalSupply + amt,
                                   bobBalance := s.bobBalance + amt }
  | .redeem who amt =>
    if s.paused then .error .paused
    else if amt = 0 then .error .zeroAmount
    else if (match who with | .alice => s.aliceBalance | .bob => s.bobBalance) < amt then
      .error .insufficientBalance
    else match mulDivFloor amt s.navFloor s.unitScale with
      | .error e => .error e
      | .ok payout =>
        if payout > s.assets then .error .insufficientAssets
        else match who with
          | .alice => .ok { s with assets := s.assets - payout,
                                   totalSupply := s.totalSupply - amt,
                                   aliceBalance := s.aliceBalance - amt }
          | .bob   => .ok { s with assets := s.assets - payout,
                                   totalSupply := s.totalSupply - amt,
                                   bobBalance := s.bobBalance - amt }
  | .transfer fromUser amt =>
    if s.paused then .error .paused
    else if amt = 0 then .error .zeroAmount
    else match fromUser with
      | .alice =>
        if s.aliceBalance < amt then .error .insufficientBalance
        else .ok { s with aliceBalance := s.aliceBalance - amt,
                          bobBalance := s.bobBalance + amt }
      | .bob =>
        if s.bobBalance < amt then .error .insufficientBalance
        else .ok { s with bobBalance := s.bobBalance - amt,
                          aliceBalance := s.aliceBalance + amt }

/-- The real vault: mints are limited by `mintableCapacitySound`. -/
def step : VaultState → Action → Except VaultError VaultState :=
  stepWith mintableCapacitySound

/-- The flawed vault, kept only so the bug can be exhibited on the state machine. -/
def stepNaive : VaultState → Action → Except VaultError VaultState :=
  stepWith mintableCapacityNaive

/-- Apply one action the way a block does: a rejected action leaves the state
    untouched and records its error as a receipt. -/
def applyAction (s : VaultState) (act : Action) : VaultState × Option VaultError :=
  match step s act with
  | .ok s'    => (s', none)
  | .error e  => (s, some e)

/-- Execute a block of actions in order, continuing past rejected ones.
    Returns the final state and one receipt per action. `Main.lean` runs this
    function, and `Proofs.lean` proves the invariant for this function. -/
def execBlock (s : VaultState) : List Action → VaultState × List (Option VaultError)
  | [] => (s, [])
  | act :: rest =>
    let r := applyAction s act
    let out := execBlock r.1 rest
    (out.1, r.2 :: out.2)

end TinyVault

A.2 TinyVault/Proofs.lean

import TinyVault.Spec

namespace TinyVault

/-! ## 1. Rounding lemmas -/

theorem mulDivFloorNat_spec (x y z : Nat) (hz : z > 0) :
    mulDivFloorNat x y z * z ≤ x * y ∧ x * y < (mulDivFloorNat x y z + 1) * z := by
  unfold mulDivFloorNat
  have hdiv := Nat.div_add_mod (x * y) z
  have hmod := Nat.mod_lt (x * y) hz
  rw [Nat.mul_comm z ((x * y) / z)] at hdiv
  rw [Nat.add_mul, Nat.one_mul]
  omega

theorem mulDivCeilNat_spec (x y z : Nat) (hz : z > 0) :
    x * y ≤ mulDivCeilNat x y z * z ∧ mulDivCeilNat x y z * z < x * y + z := by
  unfold mulDivCeilNat
  have hdiv := Nat.div_add_mod (x * y) z
  have hmod := Nat.mod_lt (x * y) hz
  rw [Nat.mul_comm z ((x * y) / z)] at hdiv
  by_cases hrem : (x * y) % z = 0
  · rw [if_pos hrem]
    omega
  · rw [if_neg hrem, Nat.add_mul, Nat.one_mul]
    omega

/-! ## 2. Capacity: counterexample, soundness, tightness -/

/-- What `mintableCapacitySound` returns when no check fails. -/
def soundCapNat (A S F U : Nat) : Nat :=
  mulDivFloorNat (A - mulDivCeilNat S F U) U F

/-- The largest mint that keeps `S * F ≤ A * U`, computed without intermediate rounding.
    Used only as a yardstick in theorems; the vault does not execute it. -/
def exactCapNat (A S F U : Nat) : Nat :=
  (A * U - S * F) / F

/-- The naive capacity admits a mint that breaks solvency. -/
theorem naiveCapacity_breaks_solvency_example :
    999 * 100 ≤ 100 * 1000 ∧
    mintableCapacityNaive 100 999 100 1000 = .ok 10 ∧
    ¬ ((999 + 10) * 100 ≤ 100 * 1000) :=
  ⟨by decide, rfl, by decide⟩

/-- Soundness: any mint within the sound capacity keeps the vault solvent. -/
theorem soundCap_preserves_solvency {A S F U delta : Nat}
    (hF : F > 0) (hU : U > 0)
    (hinit : S * F ≤ A * U)
    (hdelta : delta ≤ soundCapNat A S F U) :
    (S + delta) * F ≤ A * U := by
  unfold soundCapNat at hdelta
  have hceil := (mulDivCeilNat_spec S F U hU).1
  have hfloor := (mulDivFloorNat_spec (A - mulDivCeilNat S F U) U F hF).1
  have hmul : delta * F ≤ mulDivFloorNat (A - mulDivCeilNat S F U) U F * F :=
    Nat.mul_le_mul_right F hdelta
  rw [Nat.sub_mul] at hfloor
  rw [Nat.add_mul]
  omega

/-- The exact capacity is also safe ... -/
theorem exactCap_preserves_solvency {A S F U delta : Nat}
    (hinit : S * F ≤ A * U)
    (hdelta : delta ≤ exactCapNat A S F U) :
    (S + delta) * F ≤ A * U := by
  unfold exactCapNat at hdelta
  have hq := Nat.div_mul_le_self (A * U - S * F) F
  have hmul : delta * F ≤ (A * U - S * F) / F * F := Nat.mul_le_mul_right F hdelta
  rw [Nat.add_mul]
  omega

/-- ... and it is the maximum: one more atom always breaks solvency. -/
theorem exactCap_is_maximal {A S F U : Nat} (hF : F > 0) :
    A * U < (S + (exactCapNat A S F U + 1)) * F := by
  unfold exactCapNat
  have hdiv := Nat.div_add_mod (A * U - S * F) F
  have hmod := Nat.mod_lt (A * U - S * F) hF
  rw [Nat.mul_comm F ((A * U - S * F) / F)] at hdiv
  rw [Nat.add_mul, Nat.add_mul, Nat.one_mul]
  omega

/-- The sound capacity never exceeds the exact capacity ... -/
theorem soundCap_le_exactCap {A S F U : Nat} (hU : U > 0) :
    soundCapNat A S F U ≤ exactCapNat A S F U := by
  unfold soundCapNat exactCapNat mulDivFloorNat
  apply Nat.div_le_div_right
  have hceil := (mulDivCeilNat_spec S F U hU).1
  rw [Nat.sub_mul]
  omega

/-- ... and gives up at most `U / F + 1` atoms of it. -/
theorem exactCap_le_soundCap_add {A S F U : Nat} (hF : F > 0) (hU : U > 0) :
    exactCapNat A S F U ≤ soundCapNat A S F U + U / F + 1 := by
  have hceil := (mulDivCeilNat_spec S F U hU).2
  have hgap : A * U - S * F < (A - mulDivCeilNat S F U) * U + U := by
    by_cases hle : mulDivCeilNat S F U ≤ A
    · rw [Nat.sub_mul]
      have := Nat.mul_le_mul_right U hle
      omega
    · have hlt : A + 1 ≤ mulDivCeilNat S F U := by omega
      have := Nat.mul_le_mul_right U hlt
      rw [Nat.add_mul, Nat.one_mul] at this
      omega
  unfold soundCapNat exactCapNat mulDivFloorNat
  have hN := Nat.div_mul_le_self (A * U - S * F) F
  have hM := (mulDivFloorNat_spec (A - mulDivCeilNat S F U) U F hF).2
  have hQ := (mulDivFloorNat_spec U 1 F hF).2
  unfold mulDivFloorNat at hM hQ
  rw [Nat.mul_one] at hQ
  have hlt : (A * U - S * F) / F * F
      < ((A - mulDivCeilNat S F U) * U / F + U / F + 2) * F := by
    rw [Nat.add_mul] at hM hQ
    rw [Nat.add_mul, Nat.add_mul]
    omega
  have := Nat.lt_of_mul_lt_mul_right hlt
  omega

/-- A successful capacity call pins down the configuration and the returned value. -/
theorem mintableCapacitySound_ok {A S F U cap : Nat}
    (h : mintableCapacitySound A S F U = .ok cap) :
    F > 0 ∧ U > 0 ∧ cap = soundCapNat A S F U := by
  unfold mintableCapacitySound mulDivCeil at h
  by_cases hU : U = 0
  · simp [hU] at h
  · by_cases hov : S * F > U128_MAX
    · simp [hU, hov] at h
    · simp only [hU, hov, if_false] at h
      unfold mulDivFloor at h
      by_cases hF : F = 0
      · simp [hF] at h
      · by_cases hov2 : (A - mulDivCeilNat S F U) * U > U128_MAX
        · simp [hF, hov2] at h
        · simp only [hF, hov2, if_false, Except.ok.injEq] at h
          exact ⟨Nat.pos_of_ne_zero hF, Nat.pos_of_ne_zero hU, h.symm⟩

/-- A successful checked floor division really is a floor: `q * z ≤ x * y`. -/
theorem mulDivFloor_ok {x y z q : Nat} (h : mulDivFloor x y z = .ok q) : q * z ≤ x * y := by
  unfold mulDivFloor at h
  split at h
  · cases h
  · split at h
    · cases h
    · rename_i hz _
      simp only [Except.ok.injEq] at h
      subst h
      exact (mulDivFloorNat_spec x y z (Nat.pos_of_ne_zero hz)).1

/-! ## 3. State-machine invariants -/

/-- Balances add up to the supply. -/
def Conserved (s : VaultState) : Prop :=
  s.aliceBalance + s.bobBalance = s.totalSupply

/-- Every token atom is backed at the NAV floor. -/
def Solvent (s : VaultState) : Prop :=
  s.totalSupply * s.navFloor ≤ s.assets * s.unitScale

/-- The two running totals fit in a `u128`. -/
def InRange (s : VaultState) : Prop :=
  s.assets ≤ U128_MAX ∧ s.totalSupply ≤ U128_MAX

/-- What a fixed-width implementation needs: balances add up and totals fit. -/
def Bounded (s : VaultState) : Prop :=
  Conserved s ∧ InRange s

/-- The full vault invariant. -/
def Inv (s : VaultState) : Prop :=
  Bounded s ∧ Solvent s

-- All five predicates are plain comparisons, so `decide` can evaluate them on concrete states.
instance (s : VaultState) : Decidable (Conserved s) := by unfold Conserved; exact inferInstance
instance (s : VaultState) : Decidable (Solvent s) := by unfold Solvent; exact inferInstance
instance (s : VaultState) : Decidable (InRange s) := by unfold InRange; exact inferInstance
instance (s : VaultState) : Decidable (Bounded s) := by unfold Bounded; exact inferInstance
instance (s : VaultState) : Decidable (Inv s) := by unfold Inv; exact inferInstance

/-- Conservation and the `u128` range are preserved by every accepted action,
    from ANY state: this theorem does not assume solvency. -/
theorem step_preserves_bounded {s s' : VaultState} {act : Action}
    (hb : Bounded s) (hstep : step s act = .ok s') : Bounded s' := by
  obtain ⟨hc, hr1, hr2⟩ := hb
  unfold Conserved at hc
  unfold Bounded Conserved InRange
  unfold step stepWith at hstep
  cases act with
  | pause =>
    simp only [Except.ok.injEq] at hstep
    subst hstep
    exact ⟨hc, hr1, hr2⟩
  | unpause =>
    simp only [Except.ok.injEq] at hstep
    subst hstep
    exact ⟨hc, hr1, hr2⟩
  | fund amt =>
    simp only at hstep
    split at hstep
    · cases hstep
    · split at hstep
      · cases hstep
      · split at hstep
        · cases hstep
        · simp only [Except.ok.injEq] at hstep
          subst hstep
          exact ⟨hc, by show s.assets + amt ≤ U128_MAX; omega, hr2⟩
  | mint who amt =>
    simp only at hstep
    split at hstep
    · cases hstep
    · split at hstep
      · cases hstep
      · cases hcap : mintableCapacitySound s.assets s.totalSupply s.navFloor s.unitScale with
        | error e => simp [hcap] at hstep
        | ok cap =>
          simp only [hcap] at hstep
          split at hstep
          · cases hstep
          · split at hstep
            · cases hstep
            · cases who <;> simp only [Except.ok.injEq] at hstep <;> subst hstep
              · exact ⟨by show s.aliceBalance + amt + s.bobBalance = s.totalSupply + amt; omega,
                  hr1, by show s.totalSupply + amt ≤ U128_MAX; omega⟩
              · exact ⟨by show s.aliceBalance + (s.bobBalance + amt) = s.totalSupply + amt; omega,
                  hr1, by show s.totalSupply + amt ≤ U128_MAX; omega⟩
  | redeem who amt =>
    -- Alice and Bob differ only in which balance field changes, so one script
    -- handles both: `all_goals` runs it on each of the two goals `cases` made.
    cases who <;> simp only at hstep
    all_goals
      split at hstep
      · cases hstep
      · split at hstep
        · cases hstep
        · split at hstep
          · cases hstep
          · cases hpay : mulDivFloor amt s.navFloor s.unitScale with
            | error e => simp [hpay] at hstep
            | ok payout =>
              simp only [hpay] at hstep
              split at hstep
              · cases hstep
              · simp only [Except.ok.injEq] at hstep
                subst hstep
                exact ⟨by dsimp only; omega, by dsimp only; omega, by dsimp only; omega⟩
  | transfer fromUser amt =>
    simp only at hstep
    split at hstep
    · cases hstep
    · split at hstep
      · cases hstep
      · cases fromUser <;> simp only at hstep <;> split at hstep
        · cases hstep
        · simp only [Except.ok.injEq] at hstep
          subst hstep
          exact ⟨by show s.aliceBalance - amt + (s.bobBalance + amt) = s.totalSupply; omega,
            hr1, hr2⟩
        · cases hstep
        · simp only [Except.ok.injEq] at hstep
          subst hstep
          exact ⟨by show s.aliceBalance + amt + (s.bobBalance - amt) = s.totalSupply; omega,
            hr1, hr2⟩

/-- Solvency is preserved by every accepted action. This is where the rounding
    direction matters: `mint` relies on the ceiling, `redeem` on the floor. -/
theorem step_preserves_solvent {s s' : VaultState} {act : Action}
    (hs : Solvent s) (hstep : step s act = .ok s') : Solvent s' := by
  unfold Solvent at hs
  unfold Solvent
  unfold step stepWith at hstep
  cases act with
  | pause =>
    simp only [Except.ok.injEq] at hstep
    subst hstep
    exact hs
  | unpause =>
    simp only [Except.ok.injEq] at hstep
    subst hstep
    exact hs
  | fund amt =>
    simp only at hstep
    split at hstep
    · cases hstep
    · split at hstep
      · cases hstep
      · split at hstep
        · cases hstep
        · simp only [Except.ok.injEq] at hstep
          subst hstep
          show s.totalSupply * s.navFloor ≤ (s.assets + amt) * s.unitScale
          rw [Nat.add_mul]
          omega
  | mint who amt =>
    simp only at hstep
    split at hstep
    · cases hstep
    · split at hstep
      · cases hstep
      · cases hcap : mintableCapacitySound s.assets s.totalSupply s.navFloor s.unitScale with
        | error e => simp [hcap] at hstep
        | ok cap =>
          obtain ⟨hF, hU, hcapEq⟩ := mintableCapacitySound_ok hcap
          simp only [hcap] at hstep
          split at hstep
          · cases hstep
          · split at hstep
            · cases hstep
            · have hsolv : (s.totalSupply + amt) * s.navFloor ≤ s.assets * s.unitScale :=
                soundCap_preserves_solvency hF hU hs (by omega)
              cases who <;> simp only [Except.ok.injEq] at hstep <;> subst hstep <;> exact hsolv
  | redeem who amt =>
    cases who <;> simp only at hstep
    all_goals
      split at hstep
      · cases hstep
      · split at hstep
        · cases hstep
        · split at hstep
          · cases hstep
          · cases hpay : mulDivFloor amt s.navFloor s.unitScale with
            | error e => simp [hpay] at hstep
            | ok payout =>
              have hpayle := mulDivFloor_ok hpay
              simp only [hpay] at hstep
              split at hstep
              · cases hstep
              · simp only [Except.ok.injEq] at hstep
                subst hstep
                show (s.totalSupply - amt) * s.navFloor ≤ (s.assets - payout) * s.unitScale
                rw [Nat.sub_mul, Nat.sub_mul]
                omega
  | transfer fromUser amt =>
    simp only at hstep
    split at hstep
    · cases hstep
    · split at hstep
      · cases hstep
      · cases fromUser <;> simp only at hstep <;> split at hstep
        · cases hstep
        · simp only [Except.ok.injEq] at hstep
          subst hstep
          exact hs
        · cases hstep
        · simp only [Except.ok.injEq] at hstep
          subst hstep
          exact hs

/-- Every accepted action preserves the full invariant. -/
theorem step_preserves_inv {s s' : VaultState} {act : Action}
    (hinv : Inv s) (hstep : step s act = .ok s') : Inv s' :=
  ⟨step_preserves_bounded hinv.1 hstep, step_preserves_solvent hinv.2 hstep⟩

/-- Applying one action block-style (a rejection leaves the state alone)
    preserves the bounded invariant ... -/
theorem applyAction_preserves_bounded {s : VaultState} (act : Action) (hb : Bounded s) :
    Bounded (applyAction s act).1 := by
  unfold applyAction
  cases hstep : step s act with
  | error e => exact hb
  | ok s' => exact step_preserves_bounded hb hstep

/-- ... and the full invariant. -/
theorem applyAction_preserves_inv {s : VaultState} (act : Action) (hinv : Inv s) :
    Inv (applyAction s act).1 := by
  unfold applyAction
  cases hstep : step s act with
  | error e => exact hinv
  | ok s' => exact step_preserves_inv hinv hstep

/-- From ANY state whose balances add up and whose totals fit in a `u128`
    (solvent or not), every block ends in such a state. -/
theorem execBlock_preserves_bounded {s : VaultState} (acts : List Action) (hb : Bounded s) :
    Bounded (execBlock s acts).1 := by
  induction acts generalizing s with
  | nil => exact hb
  | cons act rest ih => exact ih (applyAction_preserves_bounded act hb)

/-- Main theorem: from a state satisfying `Inv`, a block of any length, mixing
    accepted and rejected actions, ends in a state satisfying `Inv`: balances add
    up, totals fit in a `u128`, and every token atom is backed.
    `execBlock` is the function `Main.lean` runs for the differential oracle. -/
theorem execBlock_preserves_inv {s : VaultState} (acts : List Action) (hinv : Inv s) :
    Inv (execBlock s acts).1 := by
  induction acts generalizing s with
  | nil => exact hinv
  | cons act rest ih => exact ih (applyAction_preserves_inv act hinv)

/-- What `Bounded` gives a fixed-width implementation: each balance fits in a
    `u128`, although `step` never bound-checks a balance. -/
theorem bounded_balances_fit {s : VaultState} (hb : Bounded s) :
    s.aliceBalance ≤ U128_MAX ∧ s.bobBalance ≤ U128_MAX := by
  obtain ⟨hc, _, hr2⟩ := hb
  unfold Conserved at hc
  omega

/-- In a state satisfying `Inv`, a redemption is never refused for lack of
    assets. (It can still be refused as `overflow` or `badConfig`.) -/
theorem redeem_never_short_of_assets {s : VaultState} (who : User) (amt : Nat) (hinv : Inv s) :
    step s (.redeem who amt) ≠ .error .insufficientAssets := by
  obtain ⟨⟨hc, _, _⟩, hs⟩ := hinv
  unfold Conserved at hc
  unfold Solvent at hs
  intro hstep
  unfold step stepWith at hstep
  cases who <;> simp only at hstep
  all_goals
    split at hstep
    · cases hstep
    · split at hstep
      · cases hstep
      · split at hstep
        · cases hstep
        · rename_i hbal
          cases hpay : mulDivFloor amt s.navFloor s.unitScale with
          | error e =>
            simp only [hpay] at hstep
            unfold mulDivFloor at hpay
            split at hpay
            · cases hpay; cases hstep
            · split at hpay
              · cases hpay; cases hstep
              · cases hpay
          | ok payout =>
            have hpayle := mulDivFloor_ok hpay
            simp only [hpay] at hstep
            split at hstep
            · rename_i hshort
              have hU : s.unitScale > 0 := by
                unfold mulDivFloor at hpay
                split at hpay
                · cases hpay
                · rename_i hz; exact Nat.pos_of_ne_zero hz
              have hamt : amt ≤ s.totalSupply := by omega
              have h1 := Nat.mul_le_mul_right s.navFloor hamt
              have h2 : (s.assets + 1) * s.unitScale ≤ payout * s.unitScale :=
                Nat.mul_le_mul_right s.unitScale (by omega)
              rw [Nat.add_mul, Nat.one_mul] at h2
              omega
            · cases hstep

/-- A paused vault rejects every fund, mint, redeem and transfer. -/
theorem paused_rejects_value_actions (s : VaultState) (act : Action)
    (hp : s.paused = true) (h1 : act ≠ .pause) (h2 : act ≠ .unpause) :
    step s act = .error .paused := by
  cases act <;> simp [step, stepWith, hp] at *

/-- `pause` is always accepted and always lands in a paused state, so the
    `Paused` state is reachable from every state. -/
theorem pause_reaches_paused (s : VaultState) :
    ∃ s', step s .pause = .ok s' ∧ s'.paused = true :=
  ⟨{ s with paused := true }, rfl, rfl⟩

/-! ## 4. Non-vacuity witnesses

A theorem whose hypotheses can never hold proves nothing. Each universal
theorem above gets a concrete instance here. -/

/-- The soundness theorem applies with a non-zero capacity and a non-zero mint:
    at `(A, S, F, U) = (200, 999, 100, 1000)` the capacity is 1000 atoms. -/
theorem soundCap_witness :
    999 * 100 ≤ 200 * 1000 ∧
    mintableCapacitySound 200 999 100 1000 = .ok 1000 ∧
    (999 + 1000) * 100 ≤ 200 * 1000 :=
  ⟨by decide, rfl, by decide⟩

/-- The three capacities on the counterexample input: naive 10 (breaks solvency),
    exact 1 (the true maximum), sound 0 (safe, one atom below the maximum). -/
theorem capacity_comparison_example :
    mintableCapacityNaive 100 999 100 1000 = .ok 10 ∧
    exactCapNat 100 999 100 1000 = 1 ∧
    mintableCapacitySound 100 999 100 1000 = .ok 0 :=
  ⟨rfl, by decide, rfl⟩

/-- The same bug on the state machine: from a state satisfying `Inv`, the naive
    vault accepts a mint that lands in an insolvent state, and the real vault
    rejects that mint. -/
theorem naive_vault_breaks_solvency :
    let s : VaultState :=
      { assets := 100, navFloor := 100, unitScale := 1000,
        totalSupply := 999, aliceBalance := 999, bobBalance := 0, paused := false }
    Inv s ∧
    (∃ s', stepNaive s (.mint .alice 10) = .ok s' ∧ ¬ Solvent s') ∧
    step s (.mint .alice 10) = .error .exceedsCapacity :=
  ⟨by decide, ⟨_, rfl, by decide⟩, rfl⟩

/-- A block that exercises every action, three different rejections and the
    pause/unpause round trip, starting and ending in states satisfying `Inv`. -/
theorem execBlock_witness :
    let s0 : VaultState :=
      { assets := 0, navFloor := 100, unitScale := 1000,
        totalSupply := 0, aliceBalance := 0, bobBalance := 0, paused := false }
    let block : List Action :=
      [.fund 200, .mint .alice 1000, .transfer .alice 400, .redeem .bob 150,
       .pause, .mint .alice 1, .unpause, .mint .alice 2000, .redeem .bob 9999]
    Inv s0 ∧
    execBlock s0 block =
      ({ assets := 185, navFloor := 100, unitScale := 1000,
         totalSupply := 850, aliceBalance := 600, bobBalance := 250, paused := false },
       [none, none, none, none, none, some .paused, none,
        some .exceedsCapacity, some .insufficientBalance]) ∧
    Inv (execBlock s0 block).1 :=
  ⟨by decide, by decide, by decide⟩

/-- Outside `Inv` only the bounded invariant applies. This block starts
    under-backed: the redemption is refused for lack of assets (so the error
    `redeem_never_short_of_assets` rules out under `Inv` is reachable without
    it), and balances still add up afterwards. -/
theorem execBlock_bounded_witness :
    let s0 : VaultState :=
      { assets := 50, navFloor := 100, unitScale := 1000,
        totalSupply := 1000, aliceBalance := 600, bobBalance := 400, paused := false }
    let block : List Action := [.redeem .alice 600, .fund 10, .mint .bob 1, .transfer .bob 400]
    Bounded s0 ∧ ¬ Inv s0 ∧
    execBlock s0 block =
      ({ assets := 60, navFloor := 100, unitScale := 1000,
         totalSupply := 1000, aliceBalance := 1000, bobBalance := 0, paused := false },
       [some .insufficientAssets, none, some .exceedsCapacity, none]) ∧
    Bounded (execBlock s0 block).1 ∧
    (execBlock s0 block).1.aliceBalance ≤ U128_MAX :=
  ⟨by decide, by decide, by decide, by decide, by decide⟩

/-- A redemption from a state satisfying `Inv` that is paid in full. -/
theorem redeem_witness :
    let s : VaultState :=
      { assets := 100, navFloor := 100, unitScale := 1000,
        totalSupply := 1000, aliceBalance := 1000, bobBalance := 0, paused := false }
    Inv s ∧ ∃ s', step s (.redeem .alice 1000) = .ok s' ∧ s'.assets = 0 ∧ Inv s' :=
  ⟨by decide, _, rfl, rfl, by decide⟩

/-- The exact capacity is tight on a concrete input: 1 atom is safe, 2 are not. -/
theorem exactCap_witness :
    exactCapNat 100 999 100 1000 = 1 ∧
    (999 + 1) * 100 ≤ 100 * 1000 ∧ ¬ ((999 + 2) * 100 ≤ 100 * 1000) := by
  decide

/-- A paused vault with funds: the transfer is refused although the balance is there. -/
theorem paused_witness :
    let s : VaultState :=
      { assets := 100, navFloor := 100, unitScale := 1000,
        totalSupply := 1000, aliceBalance := 1000, bobBalance := 0, paused := true }
    Inv s ∧ step s (.transfer .alice 1) = .error .paused ∧
    ∃ s', step s .unpause = .ok s' ∧ ∃ s'', step s' (.transfer .alice 1) = .ok s'' :=
  ⟨by decide, rfl, _, rfl, _, rfl⟩

/-- The `u128` boundary is live: one more asset atom than `U128_MAX` is rejected. -/
theorem overflow_witness :
    let s : VaultState :=
      { assets := U128_MAX, navFloor := 1, unitScale := 1,
        totalSupply := 0, aliceBalance := 0, bobBalance := 0, paused := false }
    Inv s ∧ step s (.fund 1) = .error .overflow ∧
    mulDivCeil U128_MAX 2 3 = .error .overflow :=
  ⟨by decide, rfl, rfl⟩

end TinyVault

A.3 Audit.lean

import Lean
import TinyVault

/-!
# Build-time audit (`Audit.lean`)

This is the only file in the project allowed to run metaprograms. It contains no
definitions the vault uses and no theorems, and it is not linked into the oracle
binary. `lake build` fails if

1. a theorem listed in `requiredTheorems` is missing or is no longer a theorem,
2. any constant in the `TinyVault` namespace (definitions and theorems alike,
   discovered automatically) depends on an axiom outside Lean's three standard
   ones (`sorry` shows up here as the axiom `sorryAx`), or
3. the number of hand-written theorems in the namespace differs from the length
   of `requiredTheorems`, so a new theorem cannot go unlisted.

4. `TinyVault/Spec.lean` or `TinyVault/Proofs.lean` declares anything outside
   the `TinyVault` namespace, where checks 2 and 3 would not see it.
-/

open Lean

/-- Theorems the project promises. Deleting or renaming one fails the build.
    Changing what one *states* does not: review statement diffs by hand. -/
def requiredTheorems : Array Name := #[
  `TinyVault.mulDivFloorNat_spec,
  `TinyVault.mulDivCeilNat_spec,
  `TinyVault.naiveCapacity_breaks_solvency_example,
  `TinyVault.soundCap_preserves_solvency,
  `TinyVault.exactCap_preserves_solvency,
  `TinyVault.exactCap_is_maximal,
  `TinyVault.soundCap_le_exactCap,
  `TinyVault.exactCap_le_soundCap_add,
  `TinyVault.mintableCapacitySound_ok,
  `TinyVault.mulDivFloor_ok,
  `TinyVault.step_preserves_bounded,
  `TinyVault.step_preserves_solvent,
  `TinyVault.step_preserves_inv,
  `TinyVault.applyAction_preserves_bounded,
  `TinyVault.applyAction_preserves_inv,
  `TinyVault.execBlock_preserves_bounded,
  `TinyVault.execBlock_preserves_inv,
  `TinyVault.bounded_balances_fit,
  `TinyVault.redeem_never_short_of_assets,
  `TinyVault.paused_rejects_value_actions,
  `TinyVault.pause_reaches_paused,
  `TinyVault.soundCap_witness,
  `TinyVault.capacity_comparison_example,
  `TinyVault.naive_vault_breaks_solvency,
  `TinyVault.execBlock_witness,
  `TinyVault.execBlock_bounded_witness,
  `TinyVault.redeem_witness,
  `TinyVault.exactCap_witness,
  `TinyVault.paused_witness,
  `TinyVault.overflow_witness
]

#eval show MetaM Unit from do
  let env ← getEnv
  let allowed : Array Name := #[``propext, ``Classical.choice, ``Quot.sound]
  for thm in requiredTheorems do
    match env.find? thm with
    | some (.thmInfo _) => pure ()
    | _ => throwError "required theorem {thm} is missing or is not a theorem"
  let names := env.constants.fold (init := (#[] : Array Name)) fun acc name _ =>
    -- Skip compiler-generated helpers such as `_cstage1`: they are code-generation
    -- artefacts, not part of the logic the kernel checks. Everything a human-written
    -- definition or theorem depends on is still reached through `collectAxioms`.
    if (`TinyVault).isPrefixOf name && !name.isInternal then acc.push name else acc
  -- Check 4: every declaration of the two vault modules lives in the namespace.
  for modName in [`TinyVault.Spec, `TinyVault.Proofs] do
    let some idx := env.getModuleIdx? modName
      | throwError "module {modName} is not imported"
    for name in env.header.moduleData[idx.toNat]!.constNames do
      unless (`TinyVault).isPrefixOf name || name.isInternal do
        throwError "{name} is declared in {modName} outside namespace TinyVault"
  let mut theorems := 0
  for name in names do
    for ax in ← collectAxioms name do
      unless allowed.contains ax do
        throwError "{name} depends on disallowed axiom {ax}"
    -- Count hand-written theorems (`TinyVault.<name>`); derived ones such as
    -- `TinyVault.VaultState.mk.injEq` sit one level deeper.
    if let some (.thmInfo _) := env.find? name then
      if name.getPrefix == `TinyVault then theorems := theorems + 1
  unless theorems == requiredTheorems.size do
    throwError "found {theorems} top-level theorems in namespace TinyVault but {requiredTheorems.size} are listed in requiredTheorems; list every theorem"
  logInfo m!"[TinyVault] audit passed: {names.size} constants axiom-checked, {theorems} theorems, all {requiredTheorems.size} required theorems present"

A.4 Main.lean

import TinyVault

/-!
# Oracle driver (`Main.lean`)

Parses one query per line and prints one answer per line. All vault logic is
called from `TinyVault.Spec`; this file only parses and formats. Numbers above
`U128_MAX` are parse errors, as they are for a Rust `u128`.
-/

open TinyVault

private def parseU128? (tok : String) : Option Nat := do
  let n ← tok.toNat?
  if n ≤ U128_MAX then some n else none

private def parseUser? : String → Option User
  | "alice" => some .alice
  | "bob"   => some .bob
  | _       => none

private def parseAction? (tok : String) : Option Action :=
  match tok.splitOn ":" with
  | ["fund", aS]       => do pure (.fund (← parseU128? aS))
  | ["mint", uS, aS]   => do pure (.mint (← parseUser? uS) (← parseU128? aS))
  | ["redeem", uS, aS] => do pure (.redeem (← parseUser? uS) (← parseU128? aS))
  | ["xfer", uS, aS]   => do pure (.transfer (← parseUser? uS) (← parseU128? aS))
  | ["pause"]          => some .pause
  | ["unpause"]        => some .unpause
  | _                  => none

private def fmtErr : VaultError → String
  | .paused              => "err_paused"
  | .zeroAmount          => "err_zero"
  | .insufficientBalance => "err_balance"
  | .insufficientAssets  => "err_assets"
  | .exceedsCapacity     => "err_capacity"
  | .badConfig           => "err_config"
  | .overflow            => "err_overflow"

private def fmtReceipt : Option VaultError → String
  | none   => "ok"
  | some e => fmtErr e

private def evalCap (toks : List String) : Option String := do
  match toks with
  | [aS, sS, fS, uS] =>
    let a ← parseU128? aS
    let s ← parseU128? sS
    let f ← parseU128? fS
    let u ← parseU128? uS
    match mintableCapacitySound a s f u with
    | .ok cap  => pure s!"ok {cap}"
    | .error e => pure (fmtErr e)
  | _ => none

private def evalBlock (toks : List String) : Option String := do
  match toks with
  | aS :: fS :: uS :: aliceS :: bobS :: pS :: actToks =>
    let assets ← parseU128? aS
    let navFloor ← parseU128? fS
    let unitScale ← parseU128? uS
    let alice ← parseU128? aliceS
    let bob ← parseU128? bobS
    let paused ← (match pS with | "0" => some false | "1" => some true | _ => none)
    if alice + bob > U128_MAX then none
    let acts ← actToks.mapM parseAction?
    let s0 : VaultState :=
      { assets, navFloor, unitScale, totalSupply := alice + bob,
        aliceBalance := alice, bobBalance := bob, paused }
    let (sF, receipts) := execBlock s0 acts
    let tags := String.intercalate "," (receipts.map fmtReceipt)
    let p := if sF.paused then 1 else 0
    -- Report whether the full invariant held before and after, so the other
    -- implementation can be compared on that as well.
    let inv0 := if decide (Inv s0) then 1 else 0
    let invF := if decide (Inv sF) then 1 else 0
    pure s!"{tags} | {sF.assets} {sF.totalSupply} {sF.aliceBalance} {sF.bobBalance} {p} | inv {inv0} {invF}"
  | _ => none

private def evalOracleLine (line : String) : String :=
  let toks := (line.splitOn " ").filter (fun s => !s.isEmpty)
  let answer := match toks with
    | "cap" :: rest   => evalCap rest
    | "block" :: rest => evalBlock rest
    | _               => none
  answer.getD "parse_err"

def main (args : List String) : IO Unit := do
  match args with
  | ["--oracle", path] =>
    let content ← IO.FS.readFile path
    for line in content.splitOn "\n" do
      if !line.trim.isEmpty then
        IO.println (evalOracleLine line.trim)
  | _ =>
    IO.println "TinyVault capacities at (assets, supply, navFloor, unitScale) = (100, 999, 100, 1000):"
    IO.println s!"  naive  = {repr (mintableCapacityNaive 100 999 100 1000)}"
    IO.println s!"  sound  = {repr (mintableCapacitySound 100 999 100 1000)}"
    IO.println "Run with --oracle <vectors.txt> for differential testing."

A.5 scratch/NaiveAttempt.lean

import TinyVault.Proofs

/-!
# The proof that gets stuck (`scratch/NaiveAttempt.lean`)

This file is EXPECTED TO FAIL and is not part of `lake build`. It is the Step 4
attempt to prove that the naive (floor-rounded) capacity preserves solvency.
Reproduce the stuck goal with:

    lake env lean scratch/NaiveAttempt.lean
-/

namespace TinyVault

theorem naiveCap_preserves_solvency_attempt {A S F U delta : Nat}
    (hF : F > 0) (hU : U > 0)
    (hinit : S * F ≤ A * U)
    (hdelta : delta ≤ mulDivFloorNat (A - mulDivFloorNat S F U) U F) :
    (S + delta) * F ≤ A * U := by
  have hreq := (mulDivFloorNat_spec S F U hU).1
  have hfloor := (mulDivFloorNat_spec (A - mulDivFloorNat S F U) U F hF).1
  have hmul : delta * F ≤ mulDivFloorNat (A - mulDivFloorNat S F U) U F * F :=
    Nat.mul_le_mul_right F hdelta
  rw [Nat.sub_mul] at hfloor
  rw [Nat.add_mul]
  omega

end TinyVault

A.6 ci.sh

#!/bin/sh
# TinyVault CI: every check the guide recommends, in one script.
# Usage: LEAN4CHECKER=/path/to/lean4checker ./ci.sh
#        ./ci.sh --skip-replay      (leaves out stage 3 and says so at the end)
set -eu
cd "$(dirname "$0")"
REPLAY="replay included"

echo "[1/6] banned-construct scan (every .lean file except Audit.lean and scratch/)"
# Audit.lean is deliberately not scanned: it is the one allowlisted metaprogram.
# This scan is a cheap first filter. The axiom audit in stage 2 is the backstop.
scan() { # usage: scan <grep flags> <pattern>; prints matches, succeeds if any
  find . -name '*.lean' -not -path './.lake/*' -not -path './scratch/*' -not -name Audit.lean \
    -exec grep -n "$1" "$2" {} +
}
if scan -wE 'sorry|admit|axiom|native_decide|implemented_by|unsafe|run_cmd|run_elab|run_meta|skipKernelTC|macro|elab|initialize' \
   || scan -E '#eval|decide \+native'; then
  echo "FAIL: banned construct found (the scan is textual: reword a comment that trips it)" >&2
  exit 1
fi

echo "[2/6] lake build --wfail (kernel-checks every proof, then runs Audit.lean)"
lake build --wfail

echo "[3/6] independent kernel replay with lean4checker"
if [ -n "${LEAN4CHECKER:-}" ]; then
  lake env "$LEAN4CHECKER" TinyVault.Spec TinyVault.Proofs
  echo "  replayed TinyVault.Spec and TinyVault.Proofs: accepted"
elif [ "${1:-}" = "--skip-replay" ]; then
  REPLAY="replay skipped"
  echo "  SKIPPED on request (--skip-replay)"
else
  echo "FAIL: LEAN4CHECKER is not set. Build lean4checker for this toolchain:" >&2
  echo "  git clone --branch v4.20.0 https://github.com/leanprover/lean4checker ../lean4checker && (cd ../lean4checker && lake build)" >&2
  echo "then run: LEAN4CHECKER=\$PWD/../lean4checker/.lake/build/bin/lean4checker ./ci.sh" >&2
  echo "or run ./ci.sh --skip-replay to leave this stage out." >&2
  exit 1
fi

echo "[4/6] the Step 4 naive proof attempt must still be rejected"
if lake env lean scratch/NaiveAttempt.lean >stuck.log 2>&1; then
  echo "FAIL: scratch/NaiveAttempt.lean compiled; the naive capacity is not provable" >&2
  exit 1
fi
if ! grep -q "omega could not prove the goal" stuck.log; then
  echo "FAIL: scratch/NaiveAttempt.lean failed for a different reason:" >&2
  cat stuck.log >&2
  exit 1
fi
echo "  rejected as documented: omega could not prove the goal"
rm -f stuck.log

echo "[5/6] Rust u128 differential oracle"
rustc -O -C overflow-checks=on oracle_test.rs -o oracle_test
./oracle_test

echo "[6/6] mutation check: each planted Rust bug must make the oracle fail"
for mutant in floor wrapping payout-ceil strict-cap paused-transfer; do
  status=0
  ./oracle_test --mutant "$mutant" >/dev/null 2>mutant.log || status=$?
  # Detected means: the comparison itself reported a mismatch (exit code 1).
  if [ "$status" != 1 ] || ! grep -q '^FAIL at vector' mutant.log; then
    echo "FAIL: mutant '$mutant' was not detected" >&2
    exit 1
  fi
  echo "  detected '$mutant': $(sed -n 1p mutant.log)"
done
rm -f mutant.log

echo "ALL CHECKS PASSED ($REPLAY)"