Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 74 additions & 0 deletions .github/workflows/formal.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
name: Formal model

on:
pull_request:
paths:
- "formal/**"
- ".github/workflows/formal.yml"
push:
branches: [main]
paths:
- "formal/**"
- ".github/workflows/formal.yml"
workflow_dispatch:

concurrency:
group: formal-${{ github.event.number || github.ref }}
cancel-in-progress: true

permissions:
contents: read

jobs:
lean:
name: Lean proofs
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write
steps:
- name: Secure runner
uses: tempoxyz/gh-actions/actions/secure-runner@35019557465e3c38ee3468be171771fd73577584 # 2026-10-20T06-22-38Z-35019557

- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false

# elan, pinned by version and checksum.
- name: Install elan
env:
ELAN_VERSION: v4.2.4
ELAN_SHA256: 42b94d4244e8353142c456ec0e4ca6528fd898a6c604d4059f494e706e431f63
run: |
curl -sSfL -o elan.tar.gz "https://github.com/leanprover/elan/releases/download/${ELAN_VERSION}/elan-x86_64-unknown-linux-gnu.tar.gz"
echo "${ELAN_SHA256} elan.tar.gz" | sha256sum -c -
tar -xzf elan.tar.gz
./elan-init -y --default-toolchain none
rm -f elan.tar.gz elan-init
echo "$HOME/.elan/bin" >> "$GITHUB_PATH"

# The Lean release lean-toolchain names, pinned by checksum and unpacked where elan
# looks for it, so elan never downloads an unchecked toolchain.
- name: Install Lean
env:
LEAN_VERSION: 4.35.0
LEAN_SHA256: 7289597a44543246c9227b8cae501767e095ce17f6d448b95fc4a8dc97268f6d
run: |
for file in formal/*/lean-toolchain; do
test "$(cat "$file")" = "leanprover/lean4:v${LEAN_VERSION}"
done
curl -sSfL -o lean.tar.zst "https://github.com/leanprover/lean4/releases/download/v${LEAN_VERSION}/lean-${LEAN_VERSION}-linux.tar.zst"
echo "${LEAN_SHA256} lean.tar.zst" | sha256sum -c -
dir="$HOME/.elan/toolchains/leanprover--lean4---v${LEAN_VERSION}"
mkdir -p "$dir"
tar --zstd -xf lean.tar.zst -C "$dir" --strip-components=1
rm -f lean.tar.zst

# One Lean project per model: intents, then methods.
- name: Check proofs
run: |
for check in formal/*/check.sh; do
echo "::group::$check"
bash "$check"
echo "::endgroup::"
done
3 changes: 3 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ make check # build every draft to XML/HTML/TXT/PDF in artifacts/, then
make build # build only (scripts/gen.sh in Docker)
make site # build, generate the index and problem pages, serve them locally
make codeowners # regenerate .github/CODEOWNERS from who submitted each spec; needs full git history
bash formal/<model>/check.sh # Lean proofs of one formal model (needs elan; formal.yml runs every model)
```

CI (`pr-check.yml`) runs the same steps inside the Docker image. Run one script test with `docker run --rm -v "$(pwd)":/data -w /data/scripts ietf-spec-tools pytest -v test_lint_frontmatter.py`. Everything runs in Docker; without it, `bundle install` and `pip install -r requirements.txt` and then `./scripts/gen.sh` (or `make build-local`) build locally. No test needs a localnet or secrets.
Expand All @@ -23,6 +24,7 @@ CI (`pr-check.yml`) runs the same steps inside the Docker image. Run one script
- `specs/methods/<network>/`: payment methods, one draft per intent (`draft-{network}-{intent}-NN.md`, such as `tempo/draft-tempo-charge-00.md`).
- `specs/extensions/`: optional extensions (`draft-payment-discovery-NN.md`) and `transports/` (MCP).
- `examples/`: templates for new intents, methods and extensions, with the required sections per track (`examples/README.md`).
- `formal/`: Lean 4 models of drafts (`core` shared, `intent-charge`, `tempo-charge`): proofs of their safety properties and a counterexample per spec gap (`formal/README.md`, each model's GAPS.md).
- `scripts/`: `gen.sh` (Markdown → XML → HTML/TXT/PDF), `check.sh`, the `lint_*.py` linters and their `test_*.py`, `bump_and_rename.sh`, `gen_index.py` and `gen_problems.py` for the site, `serve.py`.
- `pages/templates/`: HTML templates for the paymentauth.org index and `/problems/` pages.
- `artifacts/`: generated output (gitignored).
Expand All @@ -38,6 +40,7 @@ CI (`pr-check.yml`) runs the same steps inside the Docker image. Run one script
- Write in RFC 7322 style with RFC 2119/8174 keywords, terms defined before use, and Security and IANA Considerations in every draft (STYLE.md). Keep Markdown source lines under 72 characters.
- JSON and encoded examples must be valid and decode to what they claim; problem types used in drafts must have pages (`lint_problem_types.py`).
- Cross-references flow downward: core → intents → methods.
- When you change a draft that has a model under `formal/` (the core scheme, the charge intent, tempo-charge), update the model to match and keep its `check.sh` passing.
- Versioning: the core carries no wire version, intents carry none, and methods may add `methodDetails.version` (absent means 1) for breaking changes. Implementations ignore unknown fields.
- Disclose significant AI assistance in the PR description.

Expand Down
14 changes: 14 additions & 0 deletions formal/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Formal models

Lean 4 models of MPP drafts, one Lake project per draft. Each proves the draft's security properties for every reachable state, and shows each rule the draft leaves out with a counterexample (its `GAPS.md`). A model of the Tempo session method follows in a later change.

| Model | Draft |
|---|---|
| [core](./core) | Shared definitions and the proof gate (no draft) |
| [intent-charge](./intent-charge) | Core scheme and the charge intent |
| [tempo-charge](./tempo-charge) | Tempo charge method |

- Run one: `bash formal/<model>/check.sh` (clean build, then the axiom audit).
- CI runs every `formal/*/check.sh` with the Lean release pinned in `.github/workflows/formal.yml`.
- Every model requires [core](./core) (`MppCore`): the state machine harness (`run`, `Reachable`), map updates (`upd`), and the shared gate (`core/check-lib.sh`, `core/Audit.lean`). Each model is audited together with `MppCore`.
- A new model requires `MppCore` in its `lakefile.toml`, has a short `check.sh` that calls `../core/check-lib.sh <Library>`, and keeps the same `lean-toolchain`.
1 change: 1 addition & 0 deletions formal/core/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.lake/
117 changes: 117 additions & 0 deletions formal/core/Audit.lean
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import Lean
/-
Axiom audit, run by each model's check.sh (through ../core/check-lib.sh) after 'lake build',
as a separate program:
lake env lean --run ../core/Audit.lean --lib <Library>... <module>...
It is the only gate on proofs: a text grep for sorry/axiom would have to re-implement Lean's
lexer (nested comments, raw strings, interpolation) and every gap in it would hide code.

It lives outside every library and imports only Lean, so no model module can change how this
file parses (a macro or notation in a model module is never in scope here) or print text in
its place: it loads the modules check-lib.sh names, every file of the model and of MppCore,
from their built .olean files at run time (importModules, without running any initializers),
and reports through its exit code.

It walks every declaration of the libraries named with --lib (any module under one of them,
plus anything named under one), not only theorems:
- a declared 'axiom', used or not, fails the audit;
- for every other declaration (theorem, def, instance, ...) it collects the axioms the
declaration depends on, transitively (Lean.collectAxioms), and fails if any is not one of
Lean's three standard axioms (propext, Classical.choice, Quot.sound). That rules out
'sorry' and 'admit' (sorryAx) and native_decide (Lean.ofReduceBool) anywhere in the
libraries, even in a definition no theorem uses;
- every module of the libraries may import only Init and modules of the libraries;
- every declaration of the libraries is checked again by Lean's kernel, replayed onto a fresh
environment holding only Init (Lean.Kernel.Environment.replay, as lean4checker does), so a
declaration that skipped the kernel when it was built (debug.skipKernelTC, or an unchecked
environment API) fails here;
- it prints how many theorems it audited, which check-lib.sh reports.
Private declarations are audited too (their _private prefix is looked through), and so are
the equation lemmas Lean generates for pattern matches, which is why the theorem count is
larger than the number of theorems written by hand.
-/
open Lean

/-- The only axioms a declaration of the libraries may depend on. -/
def standardAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound]

/-- Whether a module or declaration name lies under one of the libraries. -/
def underLibs (libs : List Name) (name : Name) : Bool := libs.any (·.isPrefixOf name)

/-- The module a declaration comes from. -/
def moduleOf (env : Environment) (name : Name) : Option Name :=
(env.getModuleIdxFor? name).bind fun idx => env.header.moduleNames[idx.toNat]?

/-- Whether a declaration belongs to the libraries: its module or its own name is under one. -/
def inLibrary (libs : List Name) (env : Environment) (name : Name) : Bool :=
underLibs libs (privateToUserName name) || (moduleOf env name).any (underLibs libs)

/-- Audit the loaded environment: an error message, or the number of theorems audited. -/
def audit (libs : List Name) (env : Environment) : IO (Except String Nat) := do
let mut audited : Nat := 0
for (name, info) in env.constants.map₁.toList do
-- Only the libraries; Lean core is skipped. A module from elsewhere can't smuggle in an
-- axiom: collectAxioms follows every dependency of the libraries' declarations.
unless inLibrary libs env name do continue
if let .axiomInfo _ := info then
return .error s!"{name} is an axiom declaration; the libraries may declare none"
let (axioms, _) ← (collectAxioms name : CoreM (Array Name)).toIO
{ fileName := "<audit>", fileMap := default } { env }
for ax in axioms do
unless standardAxioms.contains ax do
return .error s!"{name} depends on non-standard axiom {ax}"
-- A private declaration is stored as _private.<Module>.0.<name>, which Name.isInternal
-- treats as internal, so look through that prefix. Names still internal after it
-- (compiler-generated auxiliaries) are audited above but not counted.
if let .thmInfo _ := info then
unless (privateToUserName name).isInternal do audited := audited + 1
-- Read imports from Lean's own header data, so no spelling of an import (guillemets,
-- comments, line breaks) gets past it. Without Lean, Lake or Std a module cannot reach the
-- elaborator API (addDecl, kernel-check options), so every declaration in it goes through
-- the kernel.
for mod in env.header.moduleNames, data in env.header.moduleData do
unless underLibs libs mod do continue
for imp in data.imports do
unless imp.module == `Init || underLibs libs imp.module do
return .error s!"{mod} imports {imp.module}; library modules may import only Init and {libs}"
return .ok audited

/-- Check every declaration of the libraries' modules again in the kernel, on top of Init alone
(library modules may import nothing else, which audit checks first). -/
def replay (libs : List Name) (env : Environment) : IO (Except String Unit) := do
let mut consts : Std.HashMap Name ConstantInfo := {}
for (name, info) in env.constants.map₁.toList do
if (moduleOf env name).any (underLibs libs) then consts := consts.insert name info
let base ← importModules #[{ module := `Init }] {}
try
discard <| Kernel.Environment.replay consts base.toKernelEnv
return .ok ()
catch e =>
return .error s!"kernel replay failed: {e}"

/-- Split the command line into the --lib names and the modules to load. -/
def parseArgs : List String → List Name × List Name
| "--lib" :: lib :: rest => let (ls, ms) := parseArgs rest; (lib.toName :: ls, ms)
| m :: rest => let (ls, ms) := parseArgs rest; (ls, m.toName :: ms)
| [] => ([], [])

/-- Load the modules named on the command line and audit them; exit code 0 only on success. -/
def main (args : List String) : IO UInt32 := do
let (libs, mods) := parseArgs args
if libs.isEmpty || mods.isEmpty then
IO.eprintln "usage: lake env lean --run Audit.lean --lib <Library>... <module>..."
return 2
initSearchPath (← findSysroot)
let env ← importModules (mods.toArray.map fun m => { module := m }) {}
match ← audit libs env with
| .error msg =>
IO.eprintln s!"axiom audit: {msg}"
return 1
| .ok n =>
match ← replay libs env with
| .error msg =>
IO.eprintln s!"axiom audit: {msg}"
return 1
| .ok () =>
IO.println s!"axiom audit: {n} theorems use only standard axioms, kernel replay passed"
return 0
3 changes: 3 additions & 0 deletions formal/core/MppCore.lean
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
-- Root module: imports the shared definitions every model builds on.
import MppCore.Machine
import MppCore.Fn
22 changes: 22 additions & 0 deletions formal/core/MppCore/Fn.lean
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/-
Point updates of maps modelled as functions (per channel, per challenge id).
-/
namespace MppCore

/-- Point update: k gets b, every other key is unchanged. -/
def upd {κ β : Type} [DecidableEq κ] (f : κ → β) (k : κ) (b : β) : κ → β :=
fun k' => if k' = k then b else f k'

/-- Reading the updated key returns the new value. -/
@[simp] theorem upd_same {κ β : Type} [DecidableEq κ] (f : κ → β) (k : κ) (b : β) :
upd f k b k = b := by simp [upd]

/-- Reading any other key returns the old value: the frame rule that keeps proofs per key. -/
@[simp] theorem upd_other {κ β : Type} [DecidableEq κ] (f : κ → β) (k k' : κ) (b : β)
(h : k' ≠ k) : upd f k b k' = f k' := by simp [upd, h]

/-- Reading an updated map at any key, as one case split (the form grind uses). -/
theorem upd_apply {κ β : Type} [DecidableEq κ] (f : κ → β) (k k' : κ) (b : β) :
upd f k b k' = if k' = k then b else f k' := rfl

end MppCore
31 changes: 31 additions & 0 deletions formal/core/MppCore/Machine.lean
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/-
The state machine every model is: a step function that takes one action and returns the next
state, or none when a guard refuses it. run replays a trace; Reachable is the set of states a
model can reach, and "holds in every reachable state" is proved by induction on it.
-/
namespace MppCore

/-- Run actions in order from st, stopping with none at the first refused one. -/
def run {σ α : Type} (next : σ → α → Option σ) : σ → List α → Option σ
| st, [] => some st
| st, a :: as => match next st a with
| none => none
| some st' => run next st' as

/-- Running no actions returns the state unchanged. -/
@[simp] theorem run_nil {σ α : Type} (next : σ → α → Option σ) (st : σ) :
run next st [] = some st := rfl

/-- Running a, then the rest from wherever a leads. -/
@[simp] theorem run_cons {σ α : Type} (next : σ → α → Option σ) (st : σ) (a : α) (as : List α) :
run next st (a :: as) = (match next st a with
| none => none
| some st' => run next st' as) := rfl

/-- States reachable from start: start, closed under successful steps. -/
inductive Reachable {σ α : Type} (next : σ → α → Option σ) (start : σ) : σ → Prop where
| init : Reachable next start start
| step {s s' : σ} (a : α) : Reachable next start s → next s a = some s' →
Reachable next start s'

end MppCore
14 changes: 14 additions & 0 deletions formal/core/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# MppCore

Definitions every model shares, and the gate that checks every model.

- `MppCore/Machine.lean`: `run` replays a trace through a model's step function; `Reachable` is the set of states a model can reach, which its invariant is proved over by induction.
- `MppCore/Fn.lean`: `upd`, the point update of a map modelled as a function, with its simp lemmas.
- `check-lib.sh`: builds a project from clean, refuses `set_option`, `import Lean`, metaprogramming and `skipKernelTC` in it and in `MppCore`, then runs the audit. Each model's `check.sh` calls it.
- `Audit.lean`: fails on any declared axiom or any axiom beyond Lean's three standard ones (ruling out `sorry`, `admit` and `native_decide`), and replays every declaration of the model and `MppCore` through Lean's kernel.

Domain types (Challenge, Credential, Receipt) stay in each model: each draft abstracts them differently, and sharing them would tie one model's proofs to another's.

```bash
bash formal/core/check.sh # MppCore on its own; every model's check.sh also audits it
```
Loading