Crypto Training

Halmos vs Lean: two ways to be sure about a smart contract

Halmos runs your Foundry tests symbolically on the compiled bytecode and stops at its bounds. Lean proves unbounded theorems about a model of the contract. The same two properties go through both tools here, next to evidence from public repositories that use each.

Crypto Training•2026-11-24•41 min read

Halmos and Lean both let you claim "this holds for every input" about a smart contract and have a machine check the claim. They reach it from opposite ends.

Halmos takes the Foundry tests you already write, runs the compiled EVM bytecode with symbols in place of concrete inputs, and asks a solver whether any input can break an assertion. Lean is a proof assistant. You write a mathematical model of the system and a theorem about it, then build a proof that a small trusted program checks step by step.

The short answer:

  • Halmos is the cheaper tool and the right default. It checks the real bytecode, needs no new language, returns a concrete counterexample in seconds when a property is false, and runs in CI. Its guarantees are bounded by loop counts, input sizes, call depth and solver time, and it stalls on 256-bit multiplication and division.
  • Lean has none of those bounds and can state almost anything: a fact about every sequence of calls, every field size, every adversary. The price is effort (in the projects surveyed here, from about 4 to 170 lines of Lean per line of contract source), and the proof is about a model, so something else has to tie the model to the deployed code.
  • They combine well. One project in the survey, split-fv, proves ten safety theorems in Lean and uses Halmos to check that the shipped Solidity behaves like the Lean model.

The rest of this article shows why: first on a small example run through both tools, then on evidence from real repositories.

What this is based on. Public repositories that use Halmos (OpenZeppelin, Snekmate, Farcaster, a16z's verification of the Pectra system contracts, and others) and public repositories that use Lean 4 (EVM semantics, verified compilers, bytecode proofs, zero-knowledge libraries, AWS's Cedar and SampCert). Each one is linked where it is first used and again in the list at the end. The experiments were run in November 2026 with Halmos 0.3.3 and Lean 4.36.0 on an Apple M3 Max. Treat the timings as orders of magnitude. The full experiment sources are in the appendix.

Contents

  1. The short version
  2. One arithmetic fact in both tools
  3. One stateful fact in both tools
  4. How Halmos works
  5. How Lean works
  6. What the two have in common
  7. Where they differ
  8. Where Halmos fits, and where it does not
  9. Where Lean fits, and where it does not
  10. Using both: the split-fv layout
  11. Choosing
  12. Appendix: experiment sources

1. The short version#

HalmosLean 4
What it isA symbolic bounded model checker for EVM bytecodeA general-purpose proof assistant and programming language
What you writeFoundry-style tests in Solidity (check_…, invariant_…)Definitions, theorem statements and proofs in Lean
What gets checkedThe compiled bytecode of your contractsA model: an abstract state machine, a program in a Lean DSL, or raw bytecode under an EVM semantics written in Lean
Who finds the proofAn SMT solver, with no help from youYou or an AI agent, using tactics; a kernel checks the result
What "all inputs" coversEvery value of fixed-size inputs, inside loop, length, depth and time boundsEverything you can quantify over, with no bounds
If the property is falseA concrete counterexample, usually in secondsThe proof gets stuck; you can then prove the negation from a witness
If the tool cannot decideA timeout or a path explosionAn unsolved goal that you keep working on
Hard casesNonlinear 256-bit arithmetic, unbounded loops, long call sequences, hash propertiesA model far from the deployed code; proofs that must track changing code
Typical effortHours to daysWeeks to months, now falling as AI agents write the proofs
What a green result meansNo violation exists inside the stated bounds, provided the tool and solver are rightThe theorem follows from the listed axioms, and it is a theorem about the model

Two terms used throughout:

  • An SMT solver is a program that decides whether a logical formula over machine integers, bitvectors and arrays has a solution. Z3, Yices, Bitwuzla and cvc5 are among those Halmos can call.
  • A proof assistant is a program in which you state theorems in a formal language and build proofs interactively. It checks every step, and in general you still have to find the proof yourself.

2. One arithmetic fact in both tools#

A vault that rounds in its own favour needs a division that rounds up when money comes in. For q = ceilDiv(a, b) the vault must never under-collect: q * b >= a. The library below has a buggy variant and one unrelated bit trick for comparison.

SOLIDITY
library Rounding {
    /// Money coming in: round up.
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        return (a + b - 1) / b;
    }

    /// Buggy variant: rounds down.
    function ceilDivBuggy(uint256 a, uint256 b) internal pure returns (uint256) {
        return a / b;
    }

    /// Average of two uint256 that cannot overflow.
    function avg(uint256 a, uint256 b) internal pure returns (uint256) {
        return (a & b) + ((a ^ b) >> 1);
    }
}

Halmos finds the bug at once#

A Halmos test looks like a Foundry fuzz test. The function name starts with check_, and the parameters are symbols that stand for every value of their type.

SOLIDITY
function check_buggy_never_undercollects(uint256 a, uint256 b) public pure {
    vm.assume(b > 0);
    vm.assume(a < 2 ** 64 && b < 2 ** 64);
    uint256 q = Rounding.ceilDivBuggy(a, b);
    assert(q * b >= a);
}
TEXT
Counterexample:
    p_a_uint256_83419fd_00 = 0xc000000000000000
    p_b_uint256_3255e68_00 = 0x8000000000000000
[FAIL] check_buggy_never_undercollects(uint256,uint256) (paths: 3, time: 0.46s, bounds: [])

Half a second, no setup beyond the test, and the output is a pair of numbers you can paste into a unit test. This is the strongest argument for Halmos, and nothing in Lean matches it for speed.

Halmos proves a bit-level fact at full width#

The avg trick should equal (a + b) / 2 computed without losing the carry. The test compares it to that reference for all 2^512 input pairs.

TEXT
[PASS] check_avg_matches_wide_math(uint256,uint256) (paths: 6, time: 0.45s, bounds: [])

Bitwise operations, additions, shifts and comparisons are what bitvector solvers are built for. No bound on the inputs was needed.

Halmos stalls on the correct rounding#

Now the property we care about, on the correct ceilDiv. The only change from test to test below is how far vm.assume restricts a and b. Each assertion was given 60 seconds.

Inputs restricted toYices (Halmos default)Z3
a, b < 2^8PASS in 7.7 stimeout
a, b < 2^16timeouttimeout
a, b < 2^32timeouttimeout
a, b < 2^128timeouttimeout
amount * 30 / 10_000 rounded up, amount < 2^240 (constant divisor)timeouttimeout

The property is true. The solver cannot show it, because q * b multiplies two unknowns, and q is itself the result of a division by an unknown. Solvers handle bitvector multiplication and division by expanding them into circuits of single bits, and the search over those circuits grows out of reach long before 256 bits. The last row shows that even a constant divisor is not always enough.

This is the main practical limit of Halmos, and the surveyed projects hit it repeatedly:

  • split-fv bounds its nonlinear checks to q < 2^32, fixes the strike price to a constant, and switches to Z3. Its notes say that at 2^48 to 2^96 both Yices and Z3 time out even after 120 seconds.
  • OpenZeppelin's own ceilDiv check carries the annotation /// @custom:halmos --solver cvc5-int, which selects a different solver configuration for that one test.
  • Snekmate has five math checks commented out (mul_div, wad_ln, wad_exp, cbrt, wad_cbrt) because the solver "consumes a lot of memory, causing the CI to crash due to out of memory".

Solver choice is part of the work. A different solver might close this test. Only Yices and Z3 were tried here.

Lean proves it for every natural number#

The same function and property look like this in Lean.

LEAN
/-- Money coming in: round up. -/
def ceilDiv (a b : Nat) : Nat := (a + b - 1) / b

/-- Ceil never under-collects, for every natural number `a` and every positive `b`. -/
theorem ceil_never_undercollects (a b : Nat) (hb : 0 < b) : a ≤ ceilDiv a b * b := by
  unfold ceilDiv
  have hdm := Nat.div_add_mod (a + b - 1) b   -- b * q + r = a + b - 1
  have hmod : (a + b - 1) % b < b := Nat.mod_lt _ hb
  have hcomm : (a + b - 1) / b * b = b * ((a + b - 1) / b) := Nat.mul_comm _ _
  omega

Read the proof as four moves. unfold replaces ceilDiv by its definition. The first two have lines bring in the facts every division satisfies: dividend equals divisor times quotient plus remainder, and the remainder is smaller than the divisor. The third reorders a product. Then omega, Lean's tactic for linear arithmetic over naturals and integers, finishes.

This works where the solver stalled because a person supplied the one algebraic law that matters. Once b * q is treated as a single unknown, everything left is linear, and omega closes linear goals instantly. No bits are involved. The file checks in about two seconds, most of it startup.

Lean then reports what the theorem depends on:

TEXT
'ceil_never_undercollects' depends on axioms: [propext, Quot.sound]

Those are two of Lean's three standard axioms. There is no bound on a or b.

Two more things Lean can do with the same example. The buggy version is refuted by exhibiting a witness, the Lean analogue of a counterexample, except that you supply it:

LEAN
theorem floor_can_undercollect : ∃ a b : Nat, 0 < b ∧ ¬ (a ≤ a / b * b) :=
  ⟨3, 2, by decide⟩

And the constant-divisor fee case that timed out in Halmos is a single omega call, because omega understands division by a literal.

What the Lean theorem does not say#

The Lean theorem is about natural numbers, which never overflow. The Solidity function works on 256-bit words, where a + b reverts if it exceeds 2^256 - 1. For those inputs the two artefacts disagree, and nothing in the proof above notices.

So the comparison is uneven in both directions. Halmos checked the real bytecode, but only for tiny inputs. Lean checked every input, but for an idealised function. Closing the gap on the Lean side means modelling 256-bit words (Lean has a BitVec 256 type and several full EVM semantics, covered below) or checking separately that the code matches the model.

Lean can also reason at the bit level. Its bv_decide tactic translates a bitvector goal to a SAT problem, much as Halmos's solvers do. It proves the 256-bit avg identity in about six seconds:

TEXT
'avg_no_overflow_256' depends on axioms: [propext, Classical.choice, Quot.sound,
 avg_no_overflow_256._native.bv_decide.ax_1_5]

The fourth entry is the cost. The result is accepted through natively compiled checking code, and Lean records that as an extra axiom. Projects with a strict trust policy reject it. Whatever a Lean proof relies on beyond the kernel is listed by name.

3. One stateful fact in both tools#

Most contract bugs need more than one call. This example comes from Halmos's own examples/invariants directory (originally from the ItyFuzz paper). The file in the Halmos repository carries the annotation /// @custom:halmos --invariant-depth 10 above the invariant. It is left out here so that the command line decides the depth.

SOLIDITY
contract SimpleState {
    uint counter = 0;

    function incr(uint x) public {
        require(x <= counter);
        counter += 1;
    }

    function decr(uint x) public {
        require(x >= counter);
        counter -= 1;
    }

    function buggy() public view returns (bool) {
        return counter == 10;
    }
}

contract SimpleStateTest is Test {
    SimpleState target;
    function setUp() public { target = new SimpleState(); }

    function invariant_buggy() public view {
        assertFalse(target.buggy());
    }
}

A function named invariant_… is checked after every sequence of calls to the target, with symbolic callers and arguments, up to a depth set by --invariant-depth. The default depth is 2. Reaching counter == 10 takes ten successful calls.

--invariant-depthResultPathsTime
2 (default)PASS30.02 s
9PASS100.09 s
10FAIL, with the ten-call trace120.12 s

Halmos finds the bug, which its examples page describes as "hard to detect with simple random testing". The first two rows matter more. A pass at depth 9 says nothing about depth 10. A Halmos pass always means "no violation up to this bound".

The same holds for loops. In the next test (source in the appendix) the bug needs five loop iterations, and Halmos unrolls loops twice by default.

TEXT
$ halmos --loop 2
[PASS] check_sumOnes(uint256) (paths: 3, time: 0.01s, bounds: [])
WARNING  check_sumOnes(uint256): paths have not been fully explored due to the
         loop unrolling bound: 2

$ halmos --loop 5
Counterexample:
    p_n_uint256_25d03f8_00 = 0x05
[FAIL] check_sumOnes(uint256) (paths: 6, time: 0.07s, bounds: [])

With the default bound the summary line reads 1 passed; 0 failed. The warning is the only sign that some paths were cut off.

A property that is true at every depth#

Change the contract so that incr and decr move the counter by 2, and assert that it is never 11. The property now holds for every sequence, because the counter stays even.

--invariant-depthResultPathsTime
2PASS40.02 s
20PASS220.24 s
100PASS1022.31 s

Each row is a true statement about sequences of that length. No row is the statement "for every length".

Lean proves it for every sequence#

In Lean you model the contract as a transition function and define the reachable states inductively: the initial state is reachable, and any state one successful call away from a reachable state is reachable.

LEAN
inductive Step where
  | incr (x : Nat)
  | decr (x : Nat)

/-- One transaction on the counter. `none` models a revert. -/
def apply (c : Nat) : Step → Option Nat
  | .incr x => if x ≤ c then some (c + 2) else none
  | .decr x => if c ≤ x ∧ 2 ≤ c then some (c - 2) else none

/-- Counter values produced by ANY finite sequence of successful calls after deployment. -/
inductive Reachable : Nat → Prop
  | init : Reachable 0
  | step {c c' : Nat} {s : Step} : Reachable c → apply c s = some c' → Reachable c'

/-- The inductive invariant: the counter is always even. -/
theorem even_of_reachable {c : Nat} (h : Reachable c) : c % 2 = 0 := by
  induction h with
  | init => rfl
  | @step c c' s _ hstep ih =>
    cases s with
    | incr x =>
      simp only [apply] at hstep
      split at hstep
      · injection hstep with h'; omega
      · exact absurd hstep (by simp)
    | decr x =>
      simp only [apply] at hstep
      split at hstep
      · injection hstep with h'; omega
      · exact absurd hstep (by simp)

/-- The property we care about, for every call sequence of every length. -/
theorem never_eleven {c : Nat} (h : Reachable c) : c ≠ 11 := by
  have := even_of_reachable h
  omega

The proof is an induction over how the state was reached: the property holds at deployment, and every successful step preserves it. That covers sequences of length 2, 100 and 10^9 in one argument.

Notice what had to be invented. The property we want, c ≠ 11, is true of every reachable state, but it is not preserved by a step from an arbitrary state that satisfies it: 9 is not 11, yet incr takes 9 to 11. Induction needs a stronger property that is preserved from any state satisfying it. Here that is "the counter is even". Such a property is called an inductive invariant, and finding it is the creative part of most contract proofs.

Halmos's invariant mode never asked for one, because it starts from the state after setUp and walks forward. That is why it is easier to use, and also why it stops at a depth.

The middle path: an induction step inside Halmos#

Halmos can do the induction step too, if you write it by hand. Make the contract's storage symbolic with svm.enableSymbolicStorage, assume the invariant, make one arbitrary call, and assert the invariant again. a16z's verification of the Pectra system contracts does exactly this for the queue invariant head <= tail:

In setUp():

SOLIDITY
// assume the contract invariants before executing any transaction
vm.assume(initState.queueHeadIndex <= initState.queueTailIndex);

And the check itself:

SOLIDITY
/// @custom:halmos --array-lengths data={0,1,2,32,64,96,1024}
function check_invariant(address caller, uint256 value, bytes memory data) public {
    // ... one arbitrary call with symbolic caller, value and calldata ...
    assertLe(newState.queueHeadIndex, newState.queueTailIndex, "invariant: head <= tail");
}

That is an unbounded result in the number of transactions, obtained from a bounded tool. It has the same price as in Lean: you must supply an inductive invariant, and a symbolic starting state includes unreachable states, so a too-weak invariant produces false counterexamples. The other bounds (calldata lengths, loop count, solver time) still apply.

4. How Halmos works#

Halmos is a Python program from a16z crypto. Its README describes it as "a symbolic testing tool for EVM smart contracts".

flowchart LR A["Foundry test<br/>check_ or invariant_ function"] --> B["forge build<br/>EVM bytecode"] B --> C["Halmos symbolic EVM<br/>inputs are symbols"] C --> D{"Branch depends<br/>on a symbol?"} D -->|"follow every feasible side"| C C --> E["Assertion reached:<br/>can the path conditions hold<br/>while the assertion fails?"] E --> F["SMT solver"] F -->|"yes"| G["FAIL with counterexample"] F -->|"no, on every path"| H["PASS within bounds"] F -->|"no answer in time"| I["TIMEOUT"]

Halmos interprets the bytecode itself. When execution reaches a conditional jump whose condition depends on a symbol, it follows every side that the solver says is possible, and each path records the conditions it took. At an assertion, Halmos asks the solver one question per path: is there an assignment of the symbols that satisfies this path's conditions and makes the assertion false? A "yes" is a counterexample. A "no" on every path is a pass.

Its getting-started guide gives the right mental picture. A symbolic test is equivalent to a loop over every combination of inputs (2^160 × 2^160 × 2^256 combinations for a transfer test), carried out by reasoning instead of by running each one.

The bounds, with their defaults#

These are from the 0.3.3 source. A pass is relative to all of them.

BoundDefaultEffect
--loop2Loops are unrolled this many times. Longer paths are dropped with a warning.
--invariant-depth2Length of call sequences in invariant_ tests.
--default-array-lengths0,1,2Lengths tried for dynamic arrays.
--default-bytes-lengths0,65,1024Lengths tried for bytes and string.
--solver-timeout-assertion60 sTime per assertion query. Many projects set it to 0 (no limit).
--solveryicesResults differ by solver, sometimes from timeout to pass.

Three more behaviours are easy to miss:

  • Only assertion failures count. The guide says Halmos "focuses solely on assertion violations (i.e., revert with Panic(1)), disregarding other revert cases". An input that makes the call revert for another reason, such as an arithmetic overflow, is silently dropped. The idiom vm.assume(success) after a low-level call does the same on purpose.
  • Hashes are opaque. keccak256 and ecrecover are modelled as unknown functions. storage-collision-formal-verification builds a contract whose bug is a deliberate storage-slot collision and shows that fuzzing, Certora and Halmos all miss it, because the tools assume hashes do not collide. For the same reason, symbolic v, r, s values never produce a forged signature.
  • Dynamic data has fixed sizes. A symbolic bytes value is one of a few chosen lengths. Farcaster's tests use 65-byte signatures and arrays of length 2.

What a pass rests on#

A Halmos pass depends on the Halmos interpreter matching the real EVM, on the solver's "no solution" answers being correct, and on the bounds being wide enough. None of these is re-checked by a second program. That is a reasonable trade for a testing tool, and it is the reason to report a Halmos result together with its bounds and solver settings.

5. How Lean works#

Lean 4 is a functional programming language and a proof assistant in one. A definition is a program. A theorem is a statement in the same language. A proof is a term that the kernel, a small type checker, verifies.

flowchart LR A["Model<br/>definitions in Lean"] --> C["Theorem statement"] B["Specification<br/>what must hold"] --> C C --> D["Proof script<br/>tactics such as simp, omega, induction"] D --> E["Lean builds a proof term"] E --> F{"Kernel checks<br/>the term"} F -->|"accepts"| G["Theorem, plus the list<br/>of axioms it uses"] F -->|"rejects"| H["Error at a specific goal"] H --> D

Tactics are commands that build the proof. Some are steps you would write on paper (induction, cases, unfold). Some are automation: simp rewrites with a library of lemmas, omega solves linear arithmetic goals over integers and naturals, decide evaluates a finite check, bv_decide hands a bitvector goal to a SAT solver. However a proof was found, by hand, by a tactic or by an AI agent, the kernel checks the final term. A wrong proof is rejected.

Mathlib is the community library of formalised mathematics, which many of the surveyed projects use for algebra, probability and analysis. It is large: without its prebuilt cache, the README of Jaune warns, a build "takes hours rather than the minute the build itself needs".

What "proved" means#

Lean can list the axioms each theorem depends on. Three are standard: propext, Classical.choice and Quot.sound. Anything else is a signal:

  • sorryAx means the proof contains sorry, a placeholder for a missing proof.
  • An entry from native_decide or bv_decide means the result relied on compiled code outside the kernel.
  • A project-specific axiom is an assumption the authors chose to make.

The stricter repositories cited here, the Layr-Labs challenges (eip8200-challenges, sig.golf, evm.fast), accept only the three standard axioms and replay the whole proof in Lean's kernel before believing it. The evm.fast submission guide is blunt about the difference: "Structural or Lean build success must not be described as isolated verification."

The model question#

Lean checks theorems about Lean definitions. A contract is not a Lean definition, so every project has to decide how the thing proved relates to the thing deployed. The surveyed projects use three designs.

flowchart TD SRC["Solidity or Vyper source"] -->|"compiler, trusted"| BC["Deployed bytecode"] HAL["Halmos"] -.->|"runs it symbolically"| BC M1["Design 1: abstract model in Lean<br/>example: split-fv"] -.->|"linked only by tests<br/>and conformance checks"| BC M2["Design 2: contract written in a Lean DSL<br/>example: verity"] -->|"compiler proved correct down to Yul,<br/>then solc, trusted"| BC M3["Design 3: the bytecode itself as Lean data,<br/>under an EVM semantics in Lean<br/>examples: usdt-verify, EquiVM, evm-smith"] -.->|"same bytes"| BC
  1. An abstract model. You write the accounting as a small state machine over natural numbers and prove its invariants. This is cheap (split-fv is 1,742 lines of Lean with no Mathlib dependency) and proves the design. It says nothing about the Solidity until you add a conformance layer.
  2. A verified compiler. You write the contract in a language embedded in Lean and prove that compilation preserves meaning. verity proves its pipeline down to Yul and states that "Yul → bytecode is done by pinned solc and is trusted". solidus is a verified Yul-to-bytecode backend aimed at that remaining step.
  3. The bytecode itself. You load the deployed bytes into Lean and reason against an EVM semantics. usdt-verify does this for the 11,075-byte USDT contract read from mainnet: "the Solidity source was only used as a guide". This removes the compiler from the trust base and is by far the most expensive option.

In designs 2 and 3 the proof is relative to an EVM semantics written in Lean (EVMYulLean, Jaune, EthLib). Those semantics are validated by running Ethereum's official test fixtures. Jaune reports 73,686 of 73,686 cases passing, and its trust document says plainly that this "is evidence from testing, not from proof".

6. What the two have in common#

Both check a universal claim. A fuzz test samples inputs. Halmos and Lean both make a statement about all of them, and that step matters more than any difference between the two.

Both check what you wrote, which may not be what you meant. A weak specification passes in either tool.

  • weth-invariant-testing, a WETH tutorial, has a Halmos check asserting weth.totalSupply() == address(weth).balance. In that contract totalSupply() is defined as address(this).balance, so the assertion is true by definition.
  • usdt-verify's own audit file records a critical finding against an earlier version: two global assumptions about keccak were "almost certainly false for the real keccak, so every theorem that assumes them is, as far as anyone can tell, vacuous". The authors replaced them with a narrower per-call hypothesis.
  • In split-fv, the Lean theorem that settlement reads no price oracle is proved by rfl, meaning "true by definition", because the model's transition function has no price argument. That is a fact about the shape of the model. The repository says so and adds a Halmos check on the bytecode for the real claim.

Over-constraining is the same mistake in both: too many vm.assume calls in Halmos, or too many hypotheses in a Lean theorem, leave a statement that is true and useless.

Both trust a model of the EVM. Halmos trusts its Python interpreter. Lean projects trust a Lean semantics. Neither is proved equal to a production client.

Both treat hashing as an assumption. Halmos assumes no collisions. On the Lean side, evm-smith lists keccak collision resistance as one of its two axioms, and verity and usdt-verify carry it as an explicit hypothesis on the theorems that need it.

Both use automated solvers. Lean has omega, bv_decide and, through the lean-smt project, a tactic that calls cvc5 and replays the solver's proof inside Lean so the kernel still checks it. Halmos, as shown above, can carry a hand-written induction step. The line between the tools is less sharp than it looks.

Both are increasingly driven by AI agents. Several Lean repositories say so outright: usdt-verify ("The proofs were written with Claude Code"), EquiVM (proofs and specifications "were produced by LLMs"), solidus ("no human read or wrote a line of its code"). Agents lower the cost of writing a proof. A person still has to read the theorem statement and decide whether it says the right thing.

7. Where they differ#

The object being checked#

Halmos runs the bytes that forge build produced: your contract after the compiler, the optimiser and any inline assembly. Lean checks a model. If the model is an abstraction, a correct proof and a broken contract can coexist. split-fv documents such a case in the Status section of its README: one liveness theorem is proved for a rule that the Lean model implements and the deployed call vault does not yet implement, so the theorem is "a property of the model, not (yet) of the deployed call contract".

Bounds versus induction#

Halmos explores forward from a starting state to a fixed depth, unrolling loops a fixed number of times. Lean proves statements by induction over unbounded structures: all call sequences, all list lengths, all loop iterations. The README of the system-contract verification concedes the difference for one unbounded loop, which Halmos checked for 16 iterations, "resulting in a weaker correctness guarantee".

Machine integers versus mathematics#

Halmos reasons about 256-bit words exactly as the EVM computes them, including wrap-around. That is ideal for bit tricks and assembly, and poor for mulDiv, square roots and exponentials. Lean reasons about unbounded naturals, integers, rationals and reals, where the algebraic laws are available as lemmas, and it can also reason about fixed-width words when asked to. The solvency of a vault is a statement about numbers. The correctness of a hand-optimised mulDiv in assembly is a statement about numbers and bits together.

What can be stated#

A Halmos property is a Solidity assertion after some calls. There is no way to write "for every address" over a mapping, "the sum of all balances", "with probability at most ε" or "for every adversary" directly. Tests approximate these with a fixed set of holders or with ghost variables. Lean's logic expresses all of them. This statement from sig.golf quantifies over every adversary and bounds a probability:

LEAN
def Submission.Security (submission : Submission) : Prop :=
  ∀ (adversary : Adversary submission.sizes) (Q : Nat), 1 ≤ Q →
    Pr[fun (won, calls) => won = true ∧ calls ≤ Q | submission.securityExperiment adversary]
      ≤ (Q : ENNReal) / 2 ^ SECURITY_BITS

Feedback#

When a property is false, Halmos shows you why in seconds. When a Lean proof fails, you learn only that one goal could not be closed, and deciding whether the cause is a weak proof or a false statement is your job. verity's notes for AI agents put a number on this: "~30–40% of LLM proof time is wasted attempting to prove a false or vacuous helper lemma". When Halmos cannot decide, the result is a timeout and little else. When Lean cannot decide, you still have a goal to work on.

Cost#

Halmos suites are the size of ordinary test suites, typically a few hundred lines per project. The one project that reports its effort, the system-contract verification, reports "a couple of days". Lean proofs are many times the size of the code.

ProjectWhat is verifiedLean lines
split-fvAbstract model of two vaults (407 lines of Solidity)1,742
verity SimpleToken71 lines of contract in the DSLabout 1,150 of specs and proofs
EquiVM ERC2050 lines of Solidity, as compiled bytecode8,512
evm-smith WETH86 bytes of hand-written bytecode17,462
usdt-verify11,075 bytes of deployed bytecode63,958
cedar-specA 2,239-line executable specification97,286 of proofs

Lean builds can also be slow. evm.fast stops outside builds after eight hours.

8. Where Halmos fits, and where it does not#

Good fits#

Pure functions against a reference. This is the most common successful use among the repositories cited here. OpenZeppelin runs 187 symbolic test functions over its utility libraries (Math, Packing, Arrays, SlotDerivation and others) on every pull request, with Halmos pinned to 0.3.3. halmos-solady checks that Solady's assembly mulWad agrees with Solmate's. Cicada checks a bit-length routine against a plain loop.

Single-call state-machine and access-control properties. Farcaster's registries use a pattern worth copying: make one arbitrary call with a symbolic caller, then explain every state change. This excerpt is from Guardians.symbolic.t.sol.

SOLIDITY
// If the paused state is changed by any transaction...
if (newPaused != oldPaused) {
    // If it wasn't paused before...
    if (!oldPaused) {
        // It must be paused now.
        assert(guarded.paused());

        // The function called was pause().
        assert(selector == guarded.pause.selector);

        // The caller must be the owner or a guardian.
        assert(caller == owner || guarded.guardians(caller));
    } // Otherwise, if it *was* paused before...
    else {
        // It must be unpaused now.
        assert(!guarded.paused());

        // The function called was unpause().
        assert(selector == guarded.unpause.selector);

        // The caller must be the owner.
        assert(caller == owner);
    }
}

Snekmate's "no backdoor" test has the same shape: after any call by anyone, your balance fell only if you had approved the caller.

Small low-level bytecode against a specification. a16z verified the Pectra system contracts (EIP-2935, EIP-7002, EIP-7251), which are written in raw assembly, against the EIP texts (write-up). The repository's README says the work took "only a couple of days" and found an off-by-one in the EIP-2935 get() function that "went unnoticed in previous tests". Halmos works on bytecode, so the source language does not matter: the same applies to Snekmate's Vyper.

Differential testing. halmos-differential-erc20 drives the OpenZeppelin, Solady and Solmate ERC-20s with the same symbolic calls and compares every view function afterwards. Its README reports that a manually introduced bug "is quickly detected".

Hunting for a short exploit. The SimpleState example above, and the Damn Vulnerable DeFi side-entrance CTF solved in two symbolic calls in halmos-helpers-examples.

A conformance layer under a stronger proof. See the split-fv section below.

Poor fits#

Nonlinear arithmetic at full width. The section 2 experiment, and the same story in several of the repositories. halmos-solady describes a ladder that ends in "We aren't able to do anything useful :(" for some functions. property-based-testing-benchmark notes that one check "does not finish in 1h using (int256, int256), but it does in 16s using (int64, int96)". OpenZeppelin gives ceilDiv and a few modular inverses symbolic tests and leaves mulDiv, sqrt, log2 and modExp to fuzzing.

Anything unbounded. Sums over all token holders, loops whose trip count depends on input, and "after any number of calls" claims, unless you supply the induction step yourself.

Large stateful systems. Paths multiply with every branch and every call. The differential ERC-20 test needed 15,657 paths and 2,119.80 seconds for sequences of only two calls. The author of halmos-helpers-lib reproduced three audit findings on the Size Credit protocol, estimates one scenario at "half a day on a powerful machine", and says of a fuller two-call scenario that "there is no certainty that this test will be completed even in six months". Farcaster replaced part of its contract with a simplified harness because the original "blew up the state space".

Logic that depends on real hash or signature behaviour. Collisions and forgeries are assumed away.

Probability, incentives, cryptographic soundness. These cannot be written as Solidity assertions.

Any report where "PASS" will be read as "proved". State the bounds next to the result.

Practical cautions#

Halmos is pre-1.0 and sensitive to its environment. Farcaster's CI pins Foundry because a newer version "emits cheatcodes halmos does not support". Snekmate disables the Vyper optimiser for its Halmos runs, so the bytecode checked is not the optimised build. Version 0.3.3 has no fork cheatcode, so tests cannot start from mainnet state. Keep solver, timeout and loop settings in halmos.toml or in @custom:halmos annotations next to each test, so that a result can be reproduced.

OpenZeppelin shows where a large project draws the line. Halmos covers its libraries. Its stateful contracts (access control, tokens, timelocks) are verified with the Certora Prover, an SMT-based tool with its own specification language, run there as a hosted service that needs an API key.

9. Where Lean fits, and where it does not#

Good fits#

Properties over every call sequence. The WETH solvency theorem in evm-smith holds across a whole transaction, "including arbitrary reentrancy". usdt-verify proves, under explicit hypotheses, that a successful call into the deployed USDT bytecode preserves the invariant that all 2^160 balances sum to the total supply. split-fv proves ten accounting theorems over every reachable state. This is the class of property that decides whether a protocol can become insolvent.

Compilers and virtual machines. verity and solidus prove compiler passes correct for every input program. Jaune, EVMYulLean and EthLib are executable EVM semantics. A bounded tool cannot say anything about "every program".

Cryptography and zero knowledge. ArkLib proves knowledge soundness of the sum-check protocol for every finite integral domain, with the error bound in the statement:

LEAN
theorem oracleVerifier_knowledgeSoundness [Fintype R] [IsDomain R] :
    (oracleVerifier R deg D n oSpec).knowledgeSoundness init impl
      (relationRound R n deg D 0) (relationRound R n deg D (.last n))
      (∑ _ : (pSpec R deg n).ChallengeIdx, (deg : ℝ≥0) / Fintype.card R) :=

clean proves a SHA-256 compression circuit sound for every prime field larger than 2^33 and every witness. These statements quantify over fields, provers and probabilities, which is outside what a bounded bytecode checker can express.

Mathematics beyond integers. SampCert proves that a discrete Gaussian sampler has exactly the right distribution, using the Poisson summation formula from Mathlib, and its README says the code is "deployed and used in the AWS Clean Rooms Differential Privacy service".

A specification that doubles as a test oracle. AWS's Cedar keeps an executable Lean model with proofs and runs differential random testing between that model and the production Rust implementation. The proofs are about the model. The testing ties the model to the code.

Claims that strangers must be able to check. The Layr-Labs challenge repositories fix a short statement and let anyone submit a proof, which a verifier replays in the kernel. The statement of the RIPEMD-160 challenge in eip8200-challenges is four lines:

LEAN
def Correct (code : ByteArray) : Prop :=
  ∀ calldata : ByteArray, CalldataFits calldata →
    ∃ g₀ : Nat, ∀ g : Nat, g₀ ≤ g →
    Eval (initialState code calldata g) (.returned (spec calldata))

A reviewer reads this statement and the definitions it mentions, and can ignore the proof behind a submission, which runs to more than a hundred thousand lines of Lean for that challenge. That asymmetry is what makes machine-checked proof useful for bounties and for AI-written code.

Poor fits#

Finding bugs during development. A stuck proof is a slow and indirect way to learn that a property is false.

Code that is still changing. Proofs follow the code line by line and break when it moves. evm-smith warns that a single upstream attribute change "would break every proof simultaneously". Across the Lean repositories cited here, toolchain versions range from 4.15.0 to 4.36.0, each project pinned to its own.

A model with nothing tying it to the code. An abstract proof next to an unverified implementation gives comfort it has not earned.

Properties your model leaves out. Check what each theorem excludes. verity states "Gas is not modeled". EquiVM's notion of equivalence "deliberately does not compare gas consumption, logs and substate, or revert payloads". Several bytecode proofs establish partial correctness only: if the call succeeds, the property holds.

Risks outside any model. Key management, governance, oracle economics and integrations with other protocols. split-fv proves its settlement core and says in its roadmap that the unverified surrounding product "is where economic risk concentrates".

A team that cannot review the statements. AI agents can write the proofs, but someone still has to judge the theorems. Jaune's trust document separates the two questions: it is "about whether the proofs are sound", not "about whether they are the right theorems".

10. Using both: the split-fv layout#

split-fv verifies the settlement core of an options vault. It is alpha-stage and unaudited, and its own documentation is unusually frank about what is missing, which makes it a good study.

flowchart LR SPEC["Math specification<br/>six transitions, ten theorems"] --> LEAN["Lean 4 model and proofs<br/>every reachable state, no bounds"] SPEC --> SOL["Shipped Solidity<br/>SplitVault and PutVault"] LEAN -.->|"same theorem names"| HAL["Halmos<br/>22 symbolic checks,<br/>one selector at a time"] LEAN -.->|"same theorem names"| FND["Foundry stateful invariants<br/>256 runs x depth 64"] HAL --> SOL FND --> SOL

The central artefact is a table with one row per theorem and one column per tool. Each tool does the part it is good at.

Lean holds the argument that needs induction. The model is a record of fourteen fields and six transitions. The proof shows that a well-formedness predicate holds initially and is preserved by every transition, so it holds in every reachable state, and the ten theorems follow from it. The source comments describe the same strengthening step as section 3: the natural invariant "is NOT inductive" and had to be replaced by a stronger one. Writing the proof also exposed a wrong statement. A naive form of the liveness bound is "dimensionally wrong" and false on a reachable state, and the authors record the counterexample next to the corrected theorem.

Halmos holds the link to bytecode. Each check drives one function of the shipped contract with symbolic amounts and asserts the post-condition named after the Lean theorem. For the oracle-independence claim, it makes all vault storage symbolic, makes one call with symbolic calldata to any state-changing function, and asserts that a canary contract imitating a price feed is never touched. The repository's status line counts 25 passing checks. Its three test files hold 22 check_ functions, and the rest of the figure is a static script.

Foundry's stateful fuzzer covers multi-step behaviour on the bytecode, which neither of the other two does.

Each layer has documented limits, and they are different limits:

  • The Lean model summarises per-address balances as totals and models one rounding leg with denominator 1. The decimal scaling between a 6-decimal and an 18-decimal token is listed as future work.
  • The Halmos checks that involve q * strike bound q below 2^32 and fix the strike to a constant. The repository calls this "a solver-tractability limit, not a soundness assumption" and points to the Lean proof for the unbounded statement.
  • One theorem holds for the model and not yet for the deployed call vault.

Neither tool would have been enough alone. Lean would prove a design. Halmos would check single steps on small numbers. Together, with the gaps written down, they give an argument a reviewer can follow row by row.

11. Choosing#

flowchart TD A["What do you need to establish?"] --> B{"Is there a bug within<br/>a few calls?"} B -->|"yes"| H1["Halmos check_ or invariant_ test,<br/>alongside fuzzing"] B -->|"no"| C{"One function or one call,<br/>for all inputs?"} C -->|"yes"| D{"Two unknowns multiplied<br/>or divided at 256 bits?"} D -->|"no"| H2["Halmos"] D -->|"yes"| E["Halmos at reduced width,<br/>and Lean for the general fact"] C -->|"no"| F{"Any number of calls,<br/>iterations or users?"} F -->|"yes, small contract"| H3["Halmos induction step<br/>over symbolic storage"] F -->|"yes, and solvency depends on it"| L1["Lean model with induction,<br/>plus Halmos for conformance"] F -->|"no: a compiler, a VM,<br/>cryptography, probability"| L2["Lean"]

A workable order of adoption for a contract team:

  1. Write fuzz tests first. They are cheap and catch the obvious.
  2. Promote the properties that must never fail to Halmos checks. Start with access control, state transitions and pure helpers. Keep them in CI.
  3. Record the bounds. For every Halmos result, write down the loop bound, input lengths, solver and timeout. When a check only passes at reduced width, say so in the test.
  4. Find the two or three properties the protocol's solvency rests on. If they involve unbounded sequences or real arithmetic, write a small Lean model and prove them by induction. Expect the first attempt at each statement to be wrong, and treat that as part of the value.
  5. Tie the model to the code. Name the Halmos and Foundry checks after the Lean theorems, keep a table, and list every row that is not yet green.

For immutable code that will hold large value, or for a compiler, a VM or a proof system, go further and verify the artefact itself in Lean. Budget for a proof many times the size of the code, and decide who will read the theorem statements before anyone writes a proof.

With either tool, avoid the unqualified claim "formally verified". With Halmos, say what was checked and within which bounds. With Lean, say what the theorem states, which model it is about, and which axioms and hypotheses it uses. A reader who knows those things can judge the result.


Appendix: experiment sources#

Halmos#

The project needs only forge-std. src/Rounding.sol is the library from section 2 with the same licence and pragma header as the tests, and the SimpleState test is the listing in section 3. Commands used: halmos --solver-timeout-assertion 60s (add --solver z3 for the Z3 column), halmos --invariant-depth N and halmos --loop N.

SOLIDITY
// test/Rounding.t.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

import {Test} from "forge-std/Test.sol";
import {Rounding} from "../src/Rounding.sol";

contract RoundingTest is Test {
    // Bit-level fact, full 256-bit width.
    function check_avg_matches_wide_math(uint256 a, uint256 b) public pure {
        uint256 expected;
        unchecked {
            // (a + b) / 2 computed without losing the carry bit
            uint256 sum = a + b;
            uint256 carry = sum < a ? 1 : 0;
            expected = (sum >> 1) | (carry << 255);
        }
        assert(Rounding.avg(a, b) == expected);
    }

    // The buggy rounding: expect a counterexample.
    function check_buggy_never_undercollects(uint256 a, uint256 b) public pure {
        vm.assume(b > 0);
        vm.assume(a < 2 ** 64 && b < 2 ** 64);
        uint256 q = Rounding.ceilDivBuggy(a, b);
        assert(q * b >= a);
    }

    // The correct rounding. Repeated with 2 ** 8, 2 ** 16, 2 ** 32 and 2 ** 128.
    function check_ceil_never_undercollects_8(uint256 a, uint256 b) public pure {
        vm.assume(b > 0);
        vm.assume(a < 2 ** 8 && b < 2 ** 8);
        uint256 q = Rounding.ceilDiv(a, b);
        assert(q * b >= a);
    }

    // Divisor fixed to a constant (basis points).
    function check_fee_never_undercollects(uint256 amount) public pure {
        vm.assume(amount < 2 ** 240);
        uint256 fee = Rounding.ceilDiv(amount * 30, 10_000);
        assert(fee * 10_000 >= amount * 30);
    }
}
SOLIDITY
// test/Stepper.t.sol: the "true at every depth" variant
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

import {Test} from "forge-std/Test.sol";

contract Stepper {
    uint256 public counter;

    function incr(uint256 x) public {
        require(x <= counter);
        counter += 2;
    }

    function decr(uint256 x) public {
        require(x >= counter);
        counter -= 2;
    }
}

contract StepperTest is Test {
    Stepper target;

    function setUp() public {
        target = new Stepper();
    }

    function invariant_never_eleven() public view {
        assert(target.counter() != 11);
    }
}
SOLIDITY
// test/Loop.t.sol: a bug that needs five loop iterations
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

import {Test} from "forge-std/Test.sol";

contract LoopTest is Test {
    function sumOnes(uint256 n) internal pure returns (uint256 s) {
        for (uint256 i = 0; i < n; i++) {
            s += 1;
        }
        if (n == 5) s = 0; // bug that only shows after five iterations
    }

    function check_sumOnes(uint256 n) public pure {
        vm.assume(n < 10);
        assert(sumOnes(n) == n);
    }
}

Lean#

Both files check with plain Lean 4.36.0 and no dependencies: lean Rounding.lean. The Stepper.lean file is the listing in section 3 followed by #print axioms never_eleven, which reports [propext, Quot.sound].

LEAN
-- Rounding.lean
import Std.Tactic.BVDecide

/-- Money coming in: round up. -/
def ceilDiv (a b : Nat) : Nat := (a + b - 1) / b

/-- Ceil never under-collects, for every natural number `a` and every positive `b`. -/
theorem ceil_never_undercollects (a b : Nat) (hb : 0 < b) : a ≤ ceilDiv a b * b := by
  unfold ceilDiv
  have hdm := Nat.div_add_mod (a + b - 1) b   -- b * q + r = a + b - 1
  have hmod : (a + b - 1) % b < b := Nat.mod_lt _ hb
  have hcomm : (a + b - 1) / b * b = b * ((a + b - 1) / b) := Nat.mul_comm _ _
  omega

/-- The buggy version (round down) is refuted by a concrete witness. -/
theorem floor_can_undercollect : ∃ a b : Nat, 0 < b ∧ ¬ (a ≤ a / b * b) :=
  ⟨3, 2, by decide⟩

/-- Fee in basis points with a constant divisor: `omega` handles it alone. -/
theorem fee_never_undercollects (amount : Nat) :
    amount * 30 ≤ (amount * 30 + 10000 - 1) / 10000 * 10000 := by
  omega

/-- The bit trick Halmos checked, on 256-bit words, by SAT inside Lean. -/
theorem avg_no_overflow_256 (a b : BitVec 256) :
    ((a &&& b) + ((a ^^^ b) >>> 1)).zeroExtend 257
      = (a.zeroExtend 257 + b.zeroExtend 257) >>> 1 := by
  bv_decide

#print axioms ceil_never_undercollects
#print axioms avg_no_overflow_256

Repositories cited#

The sources are all public repositories. Halmos side:

Lean side:

All quotations are from the README, documentation or source comments of the named repository as it stood in November 2026.