From aec4ce9e45f185bd5e26ea4b948fc36f40832070 Mon Sep 17 00:00:00 2001 From: Brendan Ryan <1572504+brendanjryan@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:38:40 +0000 Subject: [PATCH] feat(formal): add Lean models of the charge intent and Tempo charge with a shared core Adds formal/core (MppCore and the shared proof gate), formal/intent-charge and formal/tempo-charge, and a CI workflow that runs every model's check.sh with a pinned, checksummed Lean. --- .github/workflows/formal.yml | 74 ++++ AGENTS.md | 3 + formal/README.md | 14 + formal/core/.gitignore | 1 + formal/core/Audit.lean | 117 ++++++ formal/core/MppCore.lean | 3 + formal/core/MppCore/Fn.lean | 22 + formal/core/MppCore/Machine.lean | 31 ++ formal/core/README.md | 14 + formal/core/check-lib.sh | 85 ++++ formal/core/check.sh | 5 + formal/core/lake-manifest.json | 6 + formal/core/lakefile.toml | 13 + formal/core/lean-toolchain | 1 + formal/intent-charge/.gitignore | 1 + formal/intent-charge/GAPS.md | 19 + formal/intent-charge/IntentCharge.lean | 7 + .../IntentCharge/Counterexamples.lean | 173 ++++++++ .../intent-charge/IntentCharge/Invariant.lean | 164 ++++++++ formal/intent-charge/IntentCharge/Model.lean | 260 ++++++++++++ .../IntentCharge/Properties.lean | 205 ++++++++++ .../intent-charge/IntentCharge/Witnesses.lean | 125 ++++++ formal/intent-charge/README.md | 72 ++++ formal/intent-charge/check.sh | 7 + formal/intent-charge/lake-manifest.json | 14 + formal/intent-charge/lakefile.toml | 18 + formal/intent-charge/lean-toolchain | 1 + formal/tempo-charge/.gitignore | 1 + formal/tempo-charge/GAPS.md | 19 + formal/tempo-charge/README.md | 67 ++++ formal/tempo-charge/TempoCharge.lean | 7 + .../TempoCharge/Counterexamples.lean | 181 +++++++++ .../tempo-charge/TempoCharge/Invariant.lean | 281 +++++++++++++ formal/tempo-charge/TempoCharge/Model.lean | 376 ++++++++++++++++++ .../tempo-charge/TempoCharge/Properties.lean | 238 +++++++++++ .../tempo-charge/TempoCharge/Witnesses.lean | 119 ++++++ formal/tempo-charge/check.sh | 7 + formal/tempo-charge/lake-manifest.json | 14 + formal/tempo-charge/lakefile.toml | 18 + formal/tempo-charge/lean-toolchain | 1 + 40 files changed, 2784 insertions(+) create mode 100644 .github/workflows/formal.yml create mode 100644 formal/README.md create mode 100644 formal/core/.gitignore create mode 100644 formal/core/Audit.lean create mode 100644 formal/core/MppCore.lean create mode 100644 formal/core/MppCore/Fn.lean create mode 100644 formal/core/MppCore/Machine.lean create mode 100644 formal/core/README.md create mode 100644 formal/core/check-lib.sh create mode 100644 formal/core/check.sh create mode 100644 formal/core/lake-manifest.json create mode 100644 formal/core/lakefile.toml create mode 100644 formal/core/lean-toolchain create mode 100644 formal/intent-charge/.gitignore create mode 100644 formal/intent-charge/GAPS.md create mode 100644 formal/intent-charge/IntentCharge.lean create mode 100644 formal/intent-charge/IntentCharge/Counterexamples.lean create mode 100644 formal/intent-charge/IntentCharge/Invariant.lean create mode 100644 formal/intent-charge/IntentCharge/Model.lean create mode 100644 formal/intent-charge/IntentCharge/Properties.lean create mode 100644 formal/intent-charge/IntentCharge/Witnesses.lean create mode 100644 formal/intent-charge/README.md create mode 100644 formal/intent-charge/check.sh create mode 100644 formal/intent-charge/lake-manifest.json create mode 100644 formal/intent-charge/lakefile.toml create mode 100644 formal/intent-charge/lean-toolchain create mode 100644 formal/tempo-charge/.gitignore create mode 100644 formal/tempo-charge/GAPS.md create mode 100644 formal/tempo-charge/README.md create mode 100644 formal/tempo-charge/TempoCharge.lean create mode 100644 formal/tempo-charge/TempoCharge/Counterexamples.lean create mode 100644 formal/tempo-charge/TempoCharge/Invariant.lean create mode 100644 formal/tempo-charge/TempoCharge/Model.lean create mode 100644 formal/tempo-charge/TempoCharge/Properties.lean create mode 100644 formal/tempo-charge/TempoCharge/Witnesses.lean create mode 100644 formal/tempo-charge/check.sh create mode 100644 formal/tempo-charge/lake-manifest.json create mode 100644 formal/tempo-charge/lakefile.toml create mode 100644 formal/tempo-charge/lean-toolchain diff --git a/.github/workflows/formal.yml b/.github/workflows/formal.yml new file mode 100644 index 00000000..42e5f35f --- /dev/null +++ b/.github/workflows/formal.yml @@ -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 diff --git a/AGENTS.md b/AGENTS.md index 521ac40c..85036cb5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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//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. @@ -23,6 +24,7 @@ CI (`pr-check.yml`) runs the same steps inside the Docker image. Run one script - `specs/methods//`: 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). @@ -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. diff --git a/formal/README.md b/formal/README.md new file mode 100644 index 00000000..6c01af93 --- /dev/null +++ b/formal/README.md @@ -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//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 `, and keeps the same `lean-toolchain`. diff --git a/formal/core/.gitignore b/formal/core/.gitignore new file mode 100644 index 00000000..01f8cdb6 --- /dev/null +++ b/formal/core/.gitignore @@ -0,0 +1 @@ +.lake/ diff --git a/formal/core/Audit.lean b/formal/core/Audit.lean new file mode 100644 index 00000000..49070015 --- /dev/null +++ b/formal/core/Audit.lean @@ -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 ... ... + 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 := "", 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..0., 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 ... ..." + 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 diff --git a/formal/core/MppCore.lean b/formal/core/MppCore.lean new file mode 100644 index 00000000..0b3edcec --- /dev/null +++ b/formal/core/MppCore.lean @@ -0,0 +1,3 @@ +-- Root module: imports the shared definitions every model builds on. +import MppCore.Machine +import MppCore.Fn diff --git a/formal/core/MppCore/Fn.lean b/formal/core/MppCore/Fn.lean new file mode 100644 index 00000000..f5d6c3e6 --- /dev/null +++ b/formal/core/MppCore/Fn.lean @@ -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 diff --git a/formal/core/MppCore/Machine.lean b/formal/core/MppCore/Machine.lean new file mode 100644 index 00000000..1c985590 --- /dev/null +++ b/formal/core/MppCore/Machine.lean @@ -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 diff --git a/formal/core/README.md b/formal/core/README.md new file mode 100644 index 00000000..dd5f0f41 --- /dev/null +++ b/formal/core/README.md @@ -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 +``` diff --git a/formal/core/check-lib.sh b/formal/core/check-lib.sh new file mode 100644 index 00000000..f76055ea --- /dev/null +++ b/formal/core/check-lib.sh @@ -0,0 +1,85 @@ +#!/usr/bin/env bash +# Shared gate for every Lean project under formal/: build it from clean and fail unless every +# proof checks and only Lean's standard axioms are used. Each project's check.sh runs +# bash ../core/check-lib.sh +# from its own directory; core/check.sh runs it for MppCore. A model is audited together with +# MppCore, which it requires (lakefile.toml). +set -euo pipefail +lib="$1" +core="$(cd "$(dirname "$0")" && pwd)" + +# The libraries to gate: the project's own and, for a model, MppCore. +dirs=(".") +libs=("$lib") +if [ "$lib" != MppCore ]; then + dirs+=("$core") + libs+=(MppCore) +fi + +modules="" +for i in "${!libs[@]}"; do + dir="${dirs[$i]}" + name="${libs[$i]}" + sources=("$dir/$name.lean" "$dir/$name/"*.lean) + # The modules to audit: the root and every file under /. lakefile.toml builds the + # same set (globs), and Audit.lean loads exactly these, so every built module is audited. + modules="$modules $name $(for file in "$dir/$name/"*.lean; do + echo "$name.$(basename "$file" .lean)" + done | LC_ALL=C sort | tr '\n' ' ' | sed 's/ $//')" + # Lake's globs could also pick up hidden or symlinked files that the list above skips or + # follows differently, so allow only regular, visible files and no symlinks. + if [ -n "$(find "$dir/$name.lean" "$dir/$name" \( -type l -o -name '.*' \) -print)" ]; then + echo "FAIL: no symlinks or hidden files under $name/" + exit 1 + fi + if [ -n "$(find "$dir/$name" -mindepth 2 -name '*.lean')" ]; then + echo "FAIL: keep modules directly under $name/ (the module list reads only that level)" + exit 1 + fi + # Every module must be a regular file: grep exits 2 on a directory named *.lean, which the + # 'if grep' gates below would read as "no match" and pass. + if [ -n "$(find "$dir/$name.lean" "$dir/$name" -maxdepth 1 -name '*.lean' ! -type f -print)" ]; then + echo "FAIL: every module under $name/ must be a regular file" + exit 1 + fi + # The root module holds only imports: allow only whole lines holding one import, a -- comment, + # or both. + if grep -vE '^[[:space:]]*(import[[:space:]]+[A-Za-z0-9_.]+[[:space:]]*)?(--.*)?$' "$dir/$name.lean"; then + echo "FAIL: $name.lean may contain only import lines and -- comments" + exit 1 + fi + # No file may change options: set_option could raise maxHeartbeats or turn off warningAsError + # (lakefile.toml). A match inside a comment or string fails too, which errs on the safe side. + if grep -n 'set_option' "${sources[@]}"; then + echo "FAIL: set_option is not allowed (options live in lakefile.toml)" + exit 1 + fi + # The model and proofs are plain Lean: no module may import Lean or run metaprograms. + # Audit.lean enforces the imports from Lean's own header data and replays every declaration + # in the kernel; the greps below are a quick first pass, and also keep out syntax extensions, + # commands that run code at build time, and initializers. + if grep -n 'skipKernelTC' "${sources[@]}"; then + echo "FAIL: skipKernelTC is not allowed" + exit 1 + fi + for file in "${sources[@]}"; do + if grep -nE '^[[:space:]]*import[[:space:]]+Lean([.[:space:]]|$)' "$file" \ + || grep -nE '#(eval|exit)' "$file" \ + || grep -nE 'decide[[:space:]]*[+]native' "$file" \ + || grep -nwE 'elab|elab_rules|macro|macro_rules|syntax|declare_syntax_cat|notation|infix|infixl|infixr|prefix|postfix|binder_predicate|run_cmd|run_elab|run_meta|native_decide|ofReduceBool|ofReduceNat|initialize|builtin_initialize|unsafe|implemented_by|extern' "$file" \ + || grep -nE '(@\[|attribute[[:space:]]*\[)[^]]*\b(init|builtin_init)\b' "$file"; then + echo "FAIL: $file may not import Lean or use metaprogramming" + exit 1 + fi + done +done + +rm -rf .lake "$core/.lake" +lake build +# Audit.lean imports only Lean and loads the built modules at run time, so nothing in them can +# change how it parses or print in its place; its exit code is the result. +lib_args=() +for name in "${libs[@]}"; do lib_args+=(--lib "$name"); done +# shellcheck disable=SC2086 # the module list is space-separated names +lake env lean --run "$core/Audit.lean" "${lib_args[@]}" $modules || { echo "FAIL: axiom audit"; exit 1; } +echo "OK: audited$modules" diff --git a/formal/core/check.sh b/formal/core/check.sh new file mode 100644 index 00000000..775ff015 --- /dev/null +++ b/formal/core/check.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +# Build MppCore from clean and audit it on its own. CI runs this with every model's check.sh. +set -euo pipefail +cd "$(dirname "$0")" +exec bash ./check-lib.sh MppCore diff --git a/formal/core/lake-manifest.json b/formal/core/lake-manifest.json new file mode 100644 index 00000000..6f67d7fb --- /dev/null +++ b/formal/core/lake-manifest.json @@ -0,0 +1,6 @@ +{"version": "1.3.0", + "packagesDir": ".lake/packages", + "packages": [], + "name": "MppCore", + "lakeDir": ".lake", + "fixedToolchain": false} diff --git a/formal/core/lakefile.toml b/formal/core/lakefile.toml new file mode 100644 index 00000000..16fcc542 --- /dev/null +++ b/formal/core/lakefile.toml @@ -0,0 +1,13 @@ +name = "MppCore" +version = "0.1.0" +defaultTargets = ["MppCore"] + +# Every warning is a build error: a sorry, a deprecated name, an unused variable or simp +# argument fails 'lake build' itself, not only the axiom audit. +[leanOptions] +warningAsError = true + +[[lean_lib]] +name = "MppCore" +# Build every module under MppCore/, even one nothing imports, so no proof goes unchecked. +globs = ["MppCore", "MppCore.+"] diff --git a/formal/core/lean-toolchain b/formal/core/lean-toolchain new file mode 100644 index 00000000..a6aff065 --- /dev/null +++ b/formal/core/lean-toolchain @@ -0,0 +1 @@ +leanprover/lean4:v4.35.0 diff --git a/formal/intent-charge/.gitignore b/formal/intent-charge/.gitignore new file mode 100644 index 00000000..01f8cdb6 --- /dev/null +++ b/formal/intent-charge/.gitignore @@ -0,0 +1 @@ +.lake/ diff --git a/formal/intent-charge/GAPS.md b/formal/intent-charge/GAPS.md new file mode 100644 index 00000000..70268ce7 --- /dev/null +++ b/formal/intent-charge/GAPS.md @@ -0,0 +1,19 @@ +# Spec gaps + +Each row is a rule the drafts leave out. With its guard off, `IntentCharge/Counterexamples.lean` holds a `decide`-checked trace that breaks the named property; with every guard on, the same trace's credential is refused at that step (`rejectedAt`), or for row 5 both clients are served. Rows 6–8 are wording gaps; the model takes the reading in the last column. + +| # | Where | Gap | Guard (`Cfg`) | Breaks | Counterexample | +|---|---|---|---|---|---| +| 1 | core §Challenge Binding, charge §Server Responsibilities | The binding covers no resource (URI, HTTP method), and the server need not check that the echoed request is its price for the current request: a cheap route's challenge buys a dear route | `checkTarget` | P5 | `G1_violates_P5`, `G1_guard_rejects` | +| 2 | charge §Server Responsibilities, §Currency Verification | The server checks amount and recipient, not currency; only clients must check currency: 1 unit of a worthless token pays 1 USD | `checkCurrency` | P5 | `G2_violates_P5`, `G2_guard_rejects` | +| 3 | charge §Server Responsibilities step 3, core §Replay Protection | The proof need not commit to the challenge: a public payment for A's challenge redeems B's, and A is then refused as spent | `bindProof` | P1 | `G3_violates_P1`, `G3_payer_locked_out`, `G3_guard_rejects` | +| 4 | core §Optional Parameters (`expires` SHOULD), charge §Server Responsibilities step 2 | Without `expires` a challenge never expires: it is redeemed 10^6 s later at its old price | `ttl` = `some _` | P3 | `G4_violates_P3`, `G4_guard_rejects` | +| 5 | core §HMAC-SHA256 Binding, §Required Parameters (`id`) | The recommended id has no nonce: identical parameters (same route, same second) give the same id, and the second client pays and is refused as already used | `uniqueIds` (nonce in `opaque`) | P8, payer served | `G5_violates_P8`, `G5_paid_not_served`, `G5_guard_serves_both` | +| 6 | core §Challenge Binding vs §Status Codes, charge §Replay Protection | Stateless HMAC verification is allowed, but single use needs a per-id used store; without `expires` it grows forever | modelled: a used-id store | wording | — | +| 7 | core §Idempotency and Side Effects vs charge §Single-Use | An Idempotency-Key retry "with a valid Payment credential" SHOULD get the original response, but that credential is used and MUST be rejected | modelled: a retry is a cache hit with no new effect (`P7_retry_no_effect`); a resubmit is rejected | wording | — | +| 8 | core §HMAC-SHA256 Binding, §Character Encoding | The `\|`-joined input is ambiguous if a slot contains `\|`; `realm` may. Every collision found needs another slot to be ill-formed, so strict parsing of echoed fields blocks it; the draft doesn't require that | none: the model's MAC is injective | binding | `Gap8_hmac_input_collision` | + +- Row 1: `digest` (SHOULD) binds the body, not the route; a stateful server that stores the target with the id closes the gap the same way as `checkTarget`. +- Row 3: methods that bind the challenge (a memo or the signed authorization naming the id) satisfy the guard; ledger-hash proofs need it stated. +- Row 5: `expires` to the second does not separate concurrent requests; any per-challenge nonce in `opaque` does. + diff --git a/formal/intent-charge/IntentCharge.lean b/formal/intent-charge/IntentCharge.lean new file mode 100644 index 00000000..41b4306a --- /dev/null +++ b/formal/intent-charge/IntentCharge.lean @@ -0,0 +1,7 @@ +-- Root module: imports the whole model. check.sh builds every module under IntentCharge/ and +-- runs the axiom audit (Audit.lean) over each of them. +import IntentCharge.Model +import IntentCharge.Invariant +import IntentCharge.Properties +import IntentCharge.Counterexamples +import IntentCharge.Witnesses diff --git a/formal/intent-charge/IntentCharge/Counterexamples.lean b/formal/intent-charge/IntentCharge/Counterexamples.lean new file mode 100644 index 00000000..34176bf4 --- /dev/null +++ b/formal/intent-charge/IntentCharge/Counterexamples.lean @@ -0,0 +1,173 @@ +import IntentCharge.Model +/- + Spec gaps as machine-checked counterexamples. Each trace runs on the executable model with + ONE guard off and shows a property broken; with every guard on (guarded), the same trace is + rejected at the step the guard blocks: every action before it happens and the credential at + that step gets a 402 (rejectedAt). All checked by decide (kernel evaluation, no native code). + Traces are functions of the Cfg, since the challenge a server issues depends on its flags. + GAPS.md maps each flag to its section. +-/ +namespace IntentCharge.Examples +open IntentCharge + +-- One server: realm 7, method 3; two routes, one cheap and one dear, both paid in USD to MERCH. +def REALM : Nat := 7 +def METHOD : Nat := 3 +def USD : Nat := 840 +def JUNK : Nat := 999 +def MERCH : Nat := 5 + +/-- A cheap route (price 1) and a dear one (price 100), both GET with an empty body. -/ +def CHEAP : Target := ⟨1, 0⟩ +def DEAR : Target := ⟨2, 0⟩ + +/-- The server's route table. -/ +def price (t : Target) : Req := if t.route = 2 then ⟨100, USD, MERCH⟩ else ⟨1, USD, MERCH⟩ + +/-- All guards on (the model the theorems are about), challenges live 300 s. -/ +def guarded : Cfg := { realm := REALM, method := METHOD, price := price } + +/-- The parameters (= id) the server issues for t at time now with nonce n. -/ +def P (cfg : Cfg) (now n : Nat) (t : Target) : Params := (issue cfg now n t).p + +/-- Pay r for challenge p. -/ +def payFor (p : Params) (r : Req) : Act := .pay p r.amount r.currency r.recipient + +/-- The payment record that pay makes as the ref-th payment. -/ +def pmt (ref : Nat) (p : Params) (r : Req) : Payment := ⟨ref, p, r.amount, r.currency, r.recipient⟩ + +/-- A credential for challenge p, echoing it unchanged, in Authorization, sent to t. -/ +def cred (p : Params) (proof : Payment) (t : Target) : Cred := ⟨p, p, false, proof, t⟩ + +-- Bool versions of the properties, for decide. +/-- P5_matches_target_price: every delivery paid its target's price, recipient and currency. -/ +def pTarget (cfg : Cfg) (st : St) : Bool := st.deliveries.all fun d => + d.pmt.amount == (cfg.price d.target).amount && d.pmt.currency == (cfg.price d.target).currency && + d.pmt.recipient == (cfg.price d.target).recipient +/-- P5_matches_request (currency part). -/ +def pCurrency (st : St) : Bool := st.deliveries.all fun d => d.pmt.currency == d.id.req.currency +/-- P1_pays_own_challenge. -/ +def pBind (st : St) : Bool := st.deliveries.all fun d => d.pmt.chal == d.id +/-- P3_delivered_before_expiry: every delivered challenge had an expiry and was live. -/ +def pLive (st : St) : Bool := st.deliveries.all fun d => match d.id.expires with + | some e => decide (d.time < e) + | none => false +/-- P8_unique_ids. -/ +def pUnique (st : St) : Bool := decide (st.issued.map (·.p)).Nodup + +/-- Run tr from St.init and evaluate prop on the final state; none if a step cannot happen. -/ +def outcome (cfg : Cfg) (tr : List Act) (prop : St → Bool) : Option Bool := + (run cfg St.init tr).map prop + +/-- cfg rejects tr exactly at action n: the first n actions happen, action n submits a + credential, and the server's check refuses it (402, no delivery). -/ +def rejectedAt (cfg : Cfg) (tr : List Act) (n : Nat) : Bool := + match run cfg St.init (tr.take n), tr[n]? with + | some st, some (.submit c) => (IntentCharge.check cfg st c).isSome + | _, _ => false + +/-! ### G1 — the binding covers no resource (core §Challenge Binding; charge §Server + Responsibilities). A challenge for the cheap route, paid 1, is presented on the dear route: + every listed check passes, since the echoed request matches the payment. -/ +def trG1 (cfg : Cfg) : List Act := + let c := P cfg 1 0 CHEAP + [.request CHEAP, payFor c (price CHEAP), .submit (cred c (pmt 0 c (price CHEAP)) DEAR)] +def cfgG1 : Cfg := { guarded with checkTarget := false } +/-- G1: with the guard off, the dear route is delivered for a payment of 1. -/ +theorem G1_violates_P5 : outcome cfgG1 (trG1 cfgG1) (pTarget cfgG1) = some false := by decide +/-- G1: with every guard on, the credential on the dear route is rejected. -/ +theorem G1_guard_rejects : rejectedAt guarded (trG1 guarded) 2 = true := by decide + +/-! ### G2 — the server's checks omit currency (charge §Server Responsibilities lists amount + and recipient; §Currency Verification binds only clients). 1 unit of a worthless token + pays a challenge for 1 USD. -/ +def trG2 (cfg : Cfg) : List Act := + let c := P cfg 1 0 CHEAP + let junk : Req := ⟨1, JUNK, MERCH⟩ + [.request CHEAP, payFor c junk, .submit (cred c (pmt 0 c junk) CHEAP)] +def cfgG2 : Cfg := { guarded with checkCurrency := false } +/-- G2: with the guard off, the resource is delivered for a payment in the wrong currency. -/ +theorem G2_violates_P5 : outcome cfgG2 (trG2 cfgG2) pCurrency = some false := by decide +/-- G2: with every guard on, that credential is rejected. -/ +theorem G2_guard_rejects : rejectedAt guarded (trG2 guarded) 2 = true := by decide + +/-! ### G3 — the proof need not commit to the challenge (charge §Server Responsibilities + step 3, core §Replay Protection). Payer A pays for its challenge a; the payment is public + (a ledger transaction). B obtains its own challenge b for the same route and presents A's + payment first: B gets the resource, and A's own credential is then refused as spent. -/ +def trG3 (cfg : Cfg) : List Act := + let a := P cfg 1 0 CHEAP + let b := P cfg 1 1 CHEAP + [.request CHEAP, payFor a (price CHEAP), .request CHEAP, + .submit (cred b (pmt 0 a (price CHEAP)) CHEAP), .submit (cred a (pmt 0 a (price CHEAP)) CHEAP)] +def cfgG3 : Cfg := { guarded with bindProof := false } +/-- G3: with the guard off, B's delivery is paid by a payment made for A's challenge. -/ +theorem G3_violates_P1 : outcome cfgG3 (trG3 cfgG3) pBind = some false := by decide +/-- G3: and A, who paid, is refused: one delivery (B's), and A's credential got 402 + verification-failed. -/ +theorem G3_payer_locked_out : + outcome cfgG3 (trG3 cfgG3) (fun st => st.deliveries.length == 1 && + st.resps.head?.map (·.problem) == some (some .verificationFailed)) = some true := by decide +/-- G3: with every guard on, B's credential is rejected. -/ +theorem G3_guard_rejects : rejectedAt guarded (trG3 guarded) 3 = true := by decide +/-- G3: and with every guard on, A's credential then succeeds. -/ +theorem G3_guard_payer_served : + outcome guarded (trG3 guarded) (fun st => st.deliveries.length == 1 && pBind st) = some true := by + decide + +/-! ### G4 — expires is optional (core §Optional Parameters: SHOULD). A challenge with no + expires never expires, so charge §Server Responsibilities step 2 checks nothing: a challenge + is redeemed 10^6 s after it was issued, at its old price. -/ +def trG4 (cfg : Cfg) : List Act := + let c := P cfg 1 0 CHEAP + [.request CHEAP, payFor c (price CHEAP), .tick 1000000, .submit (cred c (pmt 0 c (price CHEAP)) CHEAP)] +def cfgG4 : Cfg := { guarded with ttl := none } +/-- G4: with the guard off, a challenge with no expiry is redeemed 10^6 s later. -/ +theorem G4_violates_P3 : outcome cfgG4 (trG4 cfgG4) pLive = some false := by decide +/-- G4: with every guard on (300 s lifetime), the late credential is rejected. -/ +theorem G4_guard_rejects : rejectedAt guarded (trG4 guarded) 3 = true := by decide + +/-! ### G5 — the recommended HMAC id has no nonce (core §HMAC-SHA256 Binding), so two + challenges with the same parameters share an id, which core §Required Parameters calls + unique. Two clients ask for the same route in the same second; both pay; the second is + refused as already used. -/ +def trG5 (cfg : Cfg) : List Act := + let a := P cfg 1 0 CHEAP + let b := P cfg 1 1 CHEAP + [.request CHEAP, .request CHEAP, payFor a (price CHEAP), .submit (cred a (pmt 0 a (price CHEAP)) CHEAP), + payFor b (price CHEAP), .submit (cred b (pmt 1 b (price CHEAP)) CHEAP)] +def cfgG5 : Cfg := { guarded with uniqueIds := false } +/-- G5: with the guard off, the two challenges share an id. -/ +theorem G5_violates_P8 : outcome cfgG5 (trG5 cfgG5) pUnique = some false := by decide +/-- G5: and the second client paid but got nothing: two payments, one delivery, and its + credential got 402 invalid-challenge. -/ +theorem G5_paid_not_served : + outcome cfgG5 (trG5 cfgG5) (fun st => st.payments.length == 2 && st.deliveries.length == 1 && + st.resps.head?.map (·.problem) == some (some .invalidChallenge)) = some true := by decide +/-- G5: with every guard on, both clients are served. -/ +theorem G5_guard_serves_both : + outcome guarded (trG5 guarded) (fun st => st.deliveries.length == 2 && pUnique st) = some true := by + decide + +/-! ### Gap 8 (wording) — the HMAC input is ambiguous when a slot contains "|" (core + §HMAC-SHA256 Binding). realm is a quoted-string, which may contain "|" (core §Character + Encoding only asks for ASCII, SHOULD). The model's MAC is injective over the tuple, so it + does not see this; hmacInput follows the draft's pseudo-code on strings. -/ + +/-- The draft's HMAC input: six fixed slots, then header when present, then opaque. -/ +def hmacInput (realm method intent request expires digest : String) (header opq : Option String) : + String := + String.intercalate "|" + ([realm, method, intent, request, expires, digest] ++ header.toList ++ [opq.getD ""]) + +/-- A challenge with header and a challenge without it, whose realm contains "|", have the + same HMAC input, so the same id. The second has method "charge" and an empty request, so a + server that parses the echoed parameters strictly still rejects it; the draft does not say + to, nor that realm excludes "|". -/ +theorem Gap8_hmac_input_collision : + hmacInput "api" "tempo" "charge" "eyJ9" "" "" (some "Payment-Authorization") none = + hmacInput "api|tempo" "charge" "eyJ9" "" "" "Payment-Authorization" none none := by + decide + +end IntentCharge.Examples + diff --git a/formal/intent-charge/IntentCharge/Invariant.lean b/formal/intent-charge/IntentCharge/Invariant.lean new file mode 100644 index 00000000..b89736b8 --- /dev/null +++ b/formal/intent-charge/IntentCharge/Invariant.lean @@ -0,0 +1,164 @@ +import IntentCharge.Model +/- + Inductive invariant over all reachable states. + + Proof plan + * Inv cfg st: every issued challenge is one the server built (issue), ids are unique (with + uniqueIds), every delivery passed verification (DelInv), used ids and spent payments are + duplicate-free, and every response is a 200 with a receipt for a delivery or a 402 with a + fresh challenge and no receipt. + * inv_init, inv_step, reachable_inv: induction on Reachable. Most fields need no guard; the + guard-dependent ones are implications from the flag, so Inv holds for every Cfg and the + properties take Cfg.Guarded only to discharge them. +-/ +namespace IntentCharge + +/-- What every delivery satisfied when it was made (check returned none), kept as the state + grows. Its fields are the properties of Properties.lean, before the guard flags discharge + their premises. -/ +structure DelInv (cfg : Cfg) (st : St) (d : Delivery) : Prop where + issued : ∃ ch ∈ st.issued, ch.p = d.id + paid : d.pmt ∈ st.payments + time_le : d.time ≤ st.now + live : live d.id.expires d.time = true + digest : digestOk d.id.digest d.target.body = true + amount : d.pmt.amount = d.id.req.amount + recipient : d.pmt.recipient = d.id.req.recipient + bind : cfg.bindProof = true → d.pmt.chal = d.id + currency : cfg.checkCurrency = true → d.pmt.currency = d.id.req.currency + target : cfg.checkTarget = true → d.id.req = cfg.price d.target + +/-- Every response is a 200 carrying the receipt of a delivery, or a 402 carrying a problem + and a challenge the server issued, and no receipt (core §Receipt Status Semantics). -/ +def RespInv (cfg : Cfg) (st : St) (r : Resp) : Prop := + (r.status = 200 ∧ r.problem = none ∧ ∃ d ∈ st.deliveries, r.receipt = some (receiptOf cfg d)) ∨ + (r.status = 402 ∧ r.receipt = none ∧ r.problem.isSome = true ∧ + ∃ ch ∈ st.issued, r.challenge = some ch.p) + +/-- The global invariant. -/ +structure Inv (cfg : Cfg) (st : St) : Prop where + chal : ∀ ch ∈ st.issued, ∃ now n t, now ≤ st.now ∧ n < st.next ∧ ch = issue cfg now n t + uniq : cfg.uniqueIds = true → st.issued.Pairwise (fun a b => a.p ≠ b.p) + del : ∀ d ∈ st.deliveries, DelInv cfg st d + used : st.used.Nodup + spent : st.spent.Nodup + resp : ∀ r ∈ st.resps, RespInv cfg st r + +/-- Base case: nothing issued, delivered or answered. -/ +theorem inv_init (cfg : Cfg) : Inv cfg St.init := + ⟨by simp [St.init], by simp [St.init], by simp [St.init], by simp [St.init, St.used], + by simp [St.init, St.spent], by simp [St.init]⟩ + +/-- What a valid credential satisfies: check returned none. -/ +theorem check_none {cfg : Cfg} {st : St} {c : Cred} (h : check cfg st c = none) : + c.echo = c.id ∧ (∃ ch ∈ st.issued, ch.p = c.id) ∧ c.id ∉ st.used ∧ + live c.echo.expires st.now = true ∧ c.altField = c.echo.header ∧ + digestOk c.echo.digest c.target.body = true ∧ + (cfg.checkTarget = true → c.echo.req = cfg.price c.target) ∧ + c.proof ∈ st.payments ∧ c.proof.ref ∉ st.spent ∧ + (cfg.bindProof = true → c.proof.chal = c.id) ∧ + c.proof.amount = c.echo.req.amount ∧ c.proof.recipient = c.echo.req.recipient ∧ + (cfg.checkCurrency = true → c.proof.currency = c.echo.req.currency) := by + unfold check at h + (repeat' split at h) <;> grind + +/-- DelInv survives any step that only adds challenges and payments and moves time forward. -/ +theorem DelInv.mono {cfg : Cfg} {s s' : St} {d : Delivery} (h : DelInv cfg s d) + (hi : ∀ x ∈ s.issued, x ∈ s'.issued) (hp : ∀ x ∈ s.payments, x ∈ s'.payments) + (hn : s.now ≤ s'.now) : DelInv cfg s' d := by + obtain ⟨⟨ch, hm, he⟩, h1, h2, h3, h4, h5, h6, h7, h8, h9⟩ := h + exact ⟨⟨ch, hi ch hm, he⟩, hp _ h1, by omega, h3, h4, h5, h6, h7, h8, h9⟩ + +/-- RespInv survives any step that only adds challenges and deliveries. -/ +theorem RespInv.mono {cfg : Cfg} {s s' : St} {r : Resp} (h : RespInv cfg s r) + (hi : ∀ x ∈ s.issued, x ∈ s'.issued) (hd : ∀ x ∈ s.deliveries, x ∈ s'.deliveries) : + RespInv cfg s' r := by + unfold RespInv at *; grind + +/-- A rejection (or an unpaid request) preserves Inv: it adds one fresh challenge, built by + issue with nonce next, and a 402 that carries it. -/ +theorem inv_reject {cfg : Cfg} {s : St} (t : Target) (pr : Problem) (hI : Inv cfg s) : + Inv cfg (reject cfg s t pr) := by + obtain ⟨hc, hu, hd, hus, hsp, hr⟩ := hI + refine ⟨?_, ?_, ?_, hus, hsp, ?_⟩ + · intro ch hm + simp only [reject, List.mem_cons] at hm + rcases hm with rfl | hm + · exact ⟨s.now, s.next, t, by simp [reject], by simp [reject], rfl⟩ + · obtain ⟨now, n, t', h1, h2, h3⟩ := hc ch hm + exact ⟨now, n, t', by simp [reject]; omega, by simp [reject]; omega, h3⟩ + · intro hq + simp only [reject, List.pairwise_cons] + refine ⟨?_, hu hq⟩ + intro b hb + obtain ⟨now, n, t', _, h2, rfl⟩ := hc b hb + simp [issue, hq]; omega + · intro d hm + exact (hd d hm).mono (by simp [reject]; grind) (by simp [reject]) (by simp [reject]) + · intro r hm + simp only [reject, List.mem_cons] at hm + rcases hm with rfl | hm + · right; simp [reject] + · exact (hr r hm).mono (by simp [reject]; grind) (by simp [reject]) + +/-- Inductive step: every step preserves Inv, for every Cfg. -/ +theorem inv_step {cfg : Cfg} {s s' : St} {a : Act} (hI : Inv cfg s) (h : step cfg s a = some s') : + Inv cfg s' := by + obtain ⟨hc, hu, hd, hus, hsp, hr⟩ := hI + cases a with + | tick dt => + simp only [step, Option.some.injEq] at h; subst h + exact ⟨fun ch hm => by grind, hu, fun d hm => (hd d hm).mono (by simp) (by simp) (by simp), + hus, hsp, fun r hm => (hr r hm).mono (by simp) (by simp)⟩ + | request t => + simp only [step, Option.some.injEq] at h; subst h + exact inv_reject t _ ⟨hc, hu, hd, hus, hsp, hr⟩ + | pay chal am cu re => + simp only [step, Option.some.injEq] at h; subst h + exact ⟨hc, hu, fun d hm => (hd d hm).mono (by simp) (by simp; grind) (by simp), + hus, hsp, fun r hm => (hr r hm).mono (by simp) (by simp)⟩ + | submit c => + simp only [step] at h + split at h + · rename_i hck + simp only [Option.some.injEq] at h; subst h + obtain ⟨he, ⟨ch, hm, hp⟩, hnu, hl, _, hdg, htg, hpm, hns, hb, ham, hre, hcu⟩ := check_none hck + refine ⟨hc, hu, ?_, ?_, ?_, ?_⟩ + · intro d hm' + simp only [List.mem_cons] at hm' + rcases hm' with rfl | hm' + · exact ⟨⟨ch, hm, hp⟩, hpm, Nat.le_refl _, he ▸ hl, he ▸ hdg, he ▸ ham, he ▸ hre, hb, + fun hq => he ▸ hcu hq, fun hq => he ▸ htg hq⟩ + · exact (hd d hm').mono (by simp) (by simp) (by simp) + · simp only [St.used, List.map_cons, List.nodup_cons] + exact ⟨hnu, hus⟩ + · simp only [St.spent, List.map_cons, List.nodup_cons] + exact ⟨hns, hsp⟩ + · intro r hm' + simp only [List.mem_cons] at hm' + rcases hm' with rfl | hm' + · left; simp + · exact (hr r hm').mono (by simp) (by simp; grind) + · simp only [Option.some.injEq] at h; subst h + exact inv_reject _ _ ⟨hc, hu, hd, hus, hsp, hr⟩ + | retry c rc => + simp only [step] at h + split at h + · rename_i hx + simp only [Option.some.injEq] at h; subst h + refine ⟨hc, hu, fun d hm => (hd d hm).mono (by simp) (by simp) (by simp), hus, hsp, ?_⟩ + intro r hm + simp only [List.mem_cons] at hm + rcases hm with rfl | hm + · left; grind + · exact (hr r hm).mono (by simp) (by simp) + · cases h + +/-- Every reachable state satisfies Inv. -/ +theorem reachable_inv {cfg : Cfg} {s : St} (h : Reachable cfg s) : Inv cfg s := by + induction h with + | init => exact inv_init cfg + | step a _ hs ih => exact inv_step ih hs + +end IntentCharge + diff --git a/formal/intent-charge/IntentCharge/Model.lean b/formal/intent-charge/IntentCharge/Model.lean new file mode 100644 index 00000000..ccda7d85 --- /dev/null +++ b/formal/intent-charge/IntentCharge/Model.lean @@ -0,0 +1,260 @@ +import MppCore +/- + Charge intent over the Payment HTTP authentication scheme, method-agnostic. + § references: "core §X" is specs/core/draft-httpauth-payment-01.md, "charge §X" is + specs/intents/draft-payment-intent-charge-00.md. + + Abstractions + * The challenge-binding MAC (core §Challenge Binding, HMAC-SHA256) is perfect: the id is the + bound parameter tuple itself (Params), and a client can only hold ids the server issued, so + "the id verifies" means "some issued challenge has these parameters". A stateless HMAC server + and a stateful one are the same model. + * The payment method is an opaque verifier: a payment (Payment) is a record of what was + really paid (amount, currency, recipient) and of the challenge the payer paid for (chal). + Anyone may make any payment (Act.pay); payments are public (core §Threat Model: attackers + observe all traffic, and ledger proofs are public). The method's own single-use rule (core + §Replay Protection) is a check that no delivery used the payment's ref yet. + * Network, TLS, parsing (malformed credentials), 401/403 policy and caching are not modelled. + Each step is atomic, which is what core §Concurrent Request Handling asks for. + * Ghost data: each challenge remembers the target and time it was issued for; deliveries and + responses are logs. + + Rules the drafts leave out are Cfg flags (Cfg.Guarded turns them all on); Counterexamples.lean + breaks a property with each one off, Witnesses.lean runs legitimate flows with all of them on. +-/ +namespace IntentCharge + +/-- What a request targets: its route (HTTP method and URI) and its body digest. -/ +structure Target where + route : Nat + body : Nat +deriving DecidableEq, Repr + +/-- The charge request object's shared fields (charge §Request Schema). -/ +structure Req where + amount : Nat + currency : Nat + recipient : Nat +deriving DecidableEq, Repr + +/-- The challenge parameters the id binds (core §Challenge Binding): realm, method, intent, + request, and expires, digest, opaque, header when present. description is not bound and + not modelled. With a perfect MAC this tuple is the id. -/ +structure Params where + realm : Nat + method : Nat + intent : Nat + req : Req + expires : Option Nat + digest : Option Nat + /-- server correlation data; carries the per-challenge nonce when Cfg.uniqueIds is on -/ + opaqueData : Option Nat + /-- header="Payment-Authorization" present -/ + header : Bool +deriving DecidableEq, Repr + +/-- An issued challenge. target and time are ghost: a stateless server does not keep them. -/ +structure Challenge where + p : Params + target : Target + time : Nat +deriving DecidableEq, Repr + +/-- A payment made through the method's infrastructure: what was paid, and the challenge the + payer paid for (what a binding method's proof commits to). ref is unique per payment. -/ +structure Payment where + ref : Nat + chal : Params + amount : Nat + currency : Nat + recipient : Nat +deriving DecidableEq, Repr + +/-- A request carrying a Payment credential (core §Credentials): + * id and echo: the echoed challenge id and parameters; + * altField: sent in Payment-Authorization rather than Authorization; + * proof: the payment the payload proves; + * target: the request the credential arrives with. -/ +structure Cred where + id : Params + echo : Params + altField : Bool + proof : Payment + target : Target +deriving DecidableEq, Repr + +/-- Payment-Receipt (core §Payment-Receipt Header); status is always "success". -/ +structure Receipt where + method : Nat + ref : Nat + time : Nat +deriving DecidableEq, Repr + +/-- Ghost log entry: a resource was delivered for challenge id, on target, paid by pmt. -/ +structure Delivery where + id : Params + target : Target + pmt : Payment + time : Nat +deriving DecidableEq, Repr + +/-- Problem types of core §Status Codes and §Error Codes that the model produces. -/ +inductive Problem where + | paymentRequired + | invalidChallenge + | paymentExpired + | verificationFailed +deriving DecidableEq, Repr + +/-- An HTTP response: status, problem type, the challenge in WWW-Authenticate, the receipt. -/ +structure Resp where + status : Nat + problem : Option Problem + challenge : Option Params + receipt : Option Receipt +deriving DecidableEq, Repr + +/-- The registered intent identifier "charge". -/ +def CHARGE : Nat := 1 + +/-- One server and its guard flags. Bool flags default to the guarded reading. -/ +structure Cfg where + realm : Nat + method : Nat + /-- what the server charges for each target (its route table) -/ + price : Target → Req + /-- challenge lifetime; none: the server omits expires, which core §Optional Parameters + allows (SHOULD). Cfg.Guarded asks for some (GAPS.md row 4). -/ + ttl : Option Nat := some 300 + /-- include digest in challenges (core §Request Body Digest Binding, SHOULD) -/ + useDigest : Bool := true + /-- select Payment-Authorization (core §Credentials) -/ + altHeader : Bool := false + /-- put a fresh nonce in each challenge (in opaque), so ids are unique (GAPS.md row 5) -/ + uniqueIds : Bool := true + /-- the echoed request must be what the server charges for the credential's own target + (GAPS.md row 1) -/ + checkTarget : Bool := true + /-- the paid currency must match the request (GAPS.md row 2) -/ + checkCurrency : Bool := true + /-- the proof must be for the challenge it is presented with (GAPS.md row 3) -/ + bindProof : Bool := true + +/-- The guarded reading: every rule the drafts leave out is on. -/ +structure Cfg.Guarded (cfg : Cfg) : Prop where + expiry : cfg.ttl.isSome = true + unique : cfg.uniqueIds = true + target : cfg.checkTarget = true + currency : cfg.checkCurrency = true + bind : cfg.bindProof = true + +/-- Global state. used ids and spent payment refs are read off the delivery log. -/ +structure St where + now : Nat + /-- nonce counter for fresh challenges -/ + next : Nat + issued : List Challenge + payments : List Payment + deliveries : List Delivery + resps : List Resp + +/-- Time 1, nothing issued, paid, delivered or answered. -/ +def St.init : St := ⟨1, 0, [], [], [], []⟩ + +/-- Challenge ids already answered (core §Status Codes "already-used", charge §Replay). -/ +def St.used (st : St) : List Params := st.deliveries.map (·.id) +/-- Payment refs already redeemed (core §Replay Protection: a proof is usable once). -/ +def St.spent (st : St) : List Nat := st.deliveries.map (·.pmt.ref) + +/-- A challenge with this expiry is still live at time now; none never expires. -/ +def live : Option Nat → Nat → Bool + | none, _ => true + | some e, now => decide (now < e) + +/-- A body matches the challenge's digest, if it has one (core §Request Body Digest Binding). -/ +def digestOk : Option Nat → Nat → Bool + | none, _ => true + | some d, b => d == b + +/-- The challenge the server issues for target t at time now with nonce n. -/ +def issue (cfg : Cfg) (now n : Nat) (t : Target) : Challenge := + ⟨⟨cfg.realm, cfg.method, CHARGE, cfg.price t, cfg.ttl.map (now + ·), + if cfg.useDigest then some t.body else none, if cfg.uniqueIds then some n else none, + cfg.altHeader⟩, t, now⟩ + +/-- The receipt for a delivery. -/ +def receiptOf (cfg : Cfg) (d : Delivery) : Receipt := ⟨cfg.method, d.pmt.ref, d.time⟩ + +/-- Server verification of a credential, in the order of core §Status Codes and charge + §Server Responsibilities; none = valid. + 1. the echoed parameters verify against the id, and the id was issued (binding); + 2. the id is not already used (single use); + 3. the challenge has not expired; + 4. the credential is in the field the challenge selected (else it is no credential); + 5. the body matches the digest, if bound; + 6. (checkTarget) the request is what the server charges for this target; + 7. the method verifies the proof: a real, unspent payment, (bindProof) made for this + challenge, with the requested amount and recipient and (checkCurrency) currency. -/ +def check (cfg : Cfg) (st : St) (c : Cred) : Option Problem := + if ¬ (c.echo = c.id ∧ ∃ ch ∈ st.issued, ch.p = c.id) then some .invalidChallenge + else if c.id ∈ st.used then some .invalidChallenge + else if live c.echo.expires st.now = false then some .paymentExpired + else if c.altField ≠ c.echo.header then some .paymentRequired + else if digestOk c.echo.digest c.target.body = false then some .verificationFailed + else if cfg.checkTarget = true ∧ c.echo.req ≠ cfg.price c.target then some .verificationFailed + else if ¬ (c.proof ∈ st.payments ∧ c.proof.ref ∉ st.spent ∧ + (cfg.bindProof = true → c.proof.chal = c.id) ∧ + c.proof.amount = c.echo.req.amount ∧ c.proof.recipient = c.echo.req.recipient ∧ + (cfg.checkCurrency = true → c.proof.currency = c.echo.req.currency)) then + some .verificationFailed + else none + +/-- Every action. -/ +inductive Act where + /-- time advances by d -/ + | tick (d : Nat) + /-- an unpaid request for t: 402 with a fresh challenge (core §Status Codes) -/ + | request (t : Target) + /-- someone pays through the method, for challenge chal (charge §Flow step 2) -/ + | pay (chal : Params) (amount currency recipient : Nat) + /-- a request carrying a credential (charge §Flow steps 3-5) -/ + | submit (c : Cred) + /-- an Idempotency-Key retry served from the cached response r (core §Idempotency) -/ + | retry (c : Cred) (r : Receipt) +deriving Repr + +/-- Record a fresh challenge for t and answer 402 with it and problem pr. -/ +def reject (cfg : Cfg) (st : St) (t : Target) (pr : Problem) : St := + let ch := issue cfg st.now st.next t + { st with issued := ch :: st.issued, next := st.next + 1, + resps := ⟨402, some pr, some ch.p, none⟩ :: st.resps } + +/-- The protocol as a transition function; none = the action cannot happen. -/ +def step (cfg : Cfg) (st : St) : Act → Option St + | .tick d => some { st with now := st.now + d } + -- core §Idempotency and Side Effects: an unpaid request records the challenge and nothing else + | .request t => some (reject cfg st t .paymentRequired) + | .pay chal amount currency recipient => + some { st with payments := ⟨st.payments.length, chal, amount, currency, recipient⟩ :: st.payments } + -- valid: settle, deliver, answer 200 with a receipt; invalid: 402, fresh challenge, no receipt + | .submit c => + match check cfg st c with + | none => + let d : Delivery := ⟨c.id, c.target, c.proof, st.now⟩ + some { st with deliveries := d :: st.deliveries, + resps := ⟨200, none, none, some (receiptOf cfg d)⟩ :: st.resps } + | some pr => some (reject cfg st c.target pr) + -- the same credential again with its Idempotency-Key: the original response, no new effect + | .retry c r => + if ∃ d ∈ st.deliveries, d.id = c.id ∧ d.target = c.target ∧ d.pmt = c.proof ∧ r = receiptOf cfg d then + some { st with resps := ⟨200, none, none, some r⟩ :: st.resps } + else none + +/-- Run a list of actions; none if any step cannot happen. -/ +abbrev run (cfg : Cfg) : St → List Act → Option St := MppCore.run (step cfg) + +/-- States reachable from St.init. -/ +abbrev Reachable (cfg : Cfg) : St → Prop := MppCore.Reachable (step cfg) St.init + +end IntentCharge + diff --git a/formal/intent-charge/IntentCharge/Properties.lean b/formal/intent-charge/IntentCharge/Properties.lean new file mode 100644 index 00000000..3d197e54 --- /dev/null +++ b/formal/intent-charge/IntentCharge/Properties.lean @@ -0,0 +1,205 @@ +import IntentCharge.Model +import IntentCharge.Invariant +/- + Properties P1-P8; README.md lists each with its theorems. State properties hold in every + reachable state and are read off Inv (Invariant.lean); those that need a rule the drafts + leave out take Cfg.Guarded and name the guard (hg.bind, hg.currency, hg.target, hg.expiry, + hg.unique). One-step theorems check that step and check encode a rule as the drafts state it. +-/ +namespace IntentCharge + +variable {cfg : Cfg} {s s' : St} + +/-! ## P1 — a Credential only pays the Challenge it answers (charge §Server Responsibilities) -/ + +/-- P1: every delivery was paid by a payment made for that very challenge, so a payment made + for one challenge never buys another (GAPS.md row 3). -/ +theorem P1_pays_own_challenge (hg : cfg.Guarded) (hr : Reachable cfg s) : + ∀ d ∈ s.deliveries, d.pmt.chal = d.id := + fun d hm => ((reachable_inv hr).del d hm).bind hg.bind + +/-- P1: every delivery was paid by a payment that really happened (the method verified it). -/ +theorem P1_payment_real (hr : Reachable cfg s) : ∀ d ∈ s.deliveries, d.pmt ∈ s.payments := + fun d hm => ((reachable_inv hr).del d hm).paid + +/-! ## P2 — challenge binding (core §Challenge Binding) -/ + +/-- P2: every delivery answers a challenge this server issued, with this realm and method and + the charge intent: a client cannot alter a bound parameter, since echoed parameters must + verify against the id. -/ +theorem P2_binding (hr : Reachable cfg s) : + ∀ d ∈ s.deliveries, (∃ ch ∈ s.issued, ch.p = d.id) ∧ + d.id.realm = cfg.realm ∧ d.id.method = cfg.method ∧ d.id.intent = CHARGE := by + intro d hm + have hi := reachable_inv hr + obtain ⟨ch, hc, he⟩ := (hi.del d hm).issued + obtain ⟨now, n, t, -, -, rfl⟩ := hi.chal ch hc + rw [← he] + exact ⟨⟨_, hc, rfl⟩, rfl, rfl, rfl⟩ + +/-- P2 (one step): echoed parameters that differ from the id's are rejected as + invalid-challenge (core §Challenge Binding: "MUST reject"). -/ +theorem P2_tampered_rejected {c : Cred} (h : c.echo ≠ c.id) : + check cfg s c = some .invalidChallenge := by + simp [check, h] + +/-- P2 (one step): an id the server never issued is rejected as invalid-challenge. -/ +theorem P2_unknown_rejected {c : Cred} (h : ∀ ch ∈ s.issued, ch.p ≠ c.id) : + check cfg s c = some .invalidChallenge := by + unfold check; grind + +/-! ## P3 — expiry (core §Optional Parameters, charge §Server Responsibilities step 2) -/ + +/-- P3: every delivery happened before its challenge expired, and its challenge had an expiry + at most ttl after it was issued (GAPS.md row 4). -/ +theorem P3_delivered_before_expiry (hg : cfg.Guarded) (hr : Reachable cfg s) : + ∀ d ∈ s.deliveries, ∃ ttl, cfg.ttl = some ttl ∧ + ∃ ch ∈ s.issued, ch.p = d.id ∧ d.id.expires = some (ch.time + ttl) ∧ d.time < ch.time + ttl := by + intro d hm + have hi := reachable_inv hr + have hdl := hi.del d hm + obtain ⟨ch, hc, he⟩ := hdl.issued + obtain ⟨now, n, t, -, -, rfl⟩ := hi.chal ch hc + have hl := hdl.live + have hx := hg.expiry + rw [← he] at hl ⊢ + cases hq : cfg.ttl with + | none => simp [hq] at hx + | some ttl => + refine ⟨ttl, rfl, _, hc, rfl, by simp [issue, hq], ?_⟩ + simp [issue, hq, live] at hl + simpa [issue] using hl + +/-- P3 (one step): a credential for an expired challenge is rejected as payment-expired + (core §Status Codes). -/ +theorem P3_expired_rejected {c : Cred} {e : Nat} (hb : c.echo = c.id ∧ ∃ ch ∈ s.issued, ch.p = c.id) + (hu : c.id ∉ s.used) (he : c.echo.expires = some e) (hn : e ≤ s.now) : + check cfg s c = some .paymentExpired := by + unfold check; grind [live] + +/-! ## P4 — single use, no double spend, no replay (core §Replay Protection, §Concurrent + Request Handling, charge §Single-Use, §Replay Protection) -/ + +/-- P4: at most one delivery per challenge id. -/ +theorem P4_single_use (hr : Reachable cfg s) : (s.deliveries.map (·.id)).Nodup := + (reachable_inv hr).used + +/-- P4: at most one delivery per payment: a payment is never redeemed twice. -/ +theorem P4_no_double_spend (hr : Reachable cfg s) : (s.deliveries.map (·.pmt.ref)).Nodup := + (reachable_inv hr).spent + +/-- P4 (one step): a replayed credential (its id already used) delivers nothing and gets 402 + invalid-challenge. -/ +theorem P4_replay_rejected {c : Cred} (hb : c.echo = c.id ∧ ∃ ch ∈ s.issued, ch.p = c.id) + (hu : c.id ∈ s.used) : check cfg s c = some .invalidChallenge := by + unfold check; grind + +/-! ## P5 — amount, recipient and currency match (charge §Server Responsibilities steps 4-5, + §Currency Verification) -/ + +/-- P5: every delivery was paid exactly the requested amount, to the requested recipient, in + the requested currency (GAPS.md row 2). -/ +theorem P5_matches_request (hg : cfg.Guarded) (hr : Reachable cfg s) : + ∀ d ∈ s.deliveries, d.pmt.amount = d.id.req.amount ∧ d.pmt.recipient = d.id.req.recipient ∧ + d.pmt.currency = d.id.req.currency := by + intro d hm + have hdl := (reachable_inv hr).del d hm + exact ⟨hdl.amount, hdl.recipient, hdl.currency hg.currency⟩ + +/-- P5: every delivery of a target was paid what the server charges for that target, so a + challenge issued for a cheap resource never buys a dear one (GAPS.md row 1). -/ +theorem P5_matches_target_price (hg : cfg.Guarded) (hr : Reachable cfg s) : + ∀ d ∈ s.deliveries, d.pmt.amount = (cfg.price d.target).amount ∧ + d.pmt.recipient = (cfg.price d.target).recipient ∧ + d.pmt.currency = (cfg.price d.target).currency := by + intro d hm + have hdl := (reachable_inv hr).del d hm + have ht := hdl.target hg.target + exact ⟨ht ▸ hdl.amount, ht ▸ hdl.recipient, ht ▸ hdl.currency hg.currency⟩ + +/-- P5: every delivery's body matches its challenge's digest, when one is bound + (core §Request Body Digest Binding). -/ +theorem P5_digest (hr : Reachable cfg s) : + ∀ d ∈ s.deliveries, digestOk d.id.digest d.target.body = true := + fun d hm => ((reachable_inv hr).del d hm).digest + +/-- P5 (one step): a credential sent in another field than the one its challenge selected + does not satisfy it (core §Credentials). -/ +theorem P5_wrong_field_rejected {c : Cred} (h : c.altField ≠ c.echo.header) : + check cfg s c ≠ none := by + unfold check; grind + +/-! ## P6 — receipts only after verified payment (core §Receipt Status Semantics, §Status + Codes, charge §Atomicity) -/ + +/-- P6: every receipt is on a 200 and is the receipt of a delivery, which passed verification + (P1, P2, P3, P5). -/ +theorem P6_receipt_only_after_payment (hr : Reachable cfg s) : + ∀ r ∈ s.resps, ∀ x, r.receipt = some x → r.status = 200 ∧ ∃ d ∈ s.deliveries, x = receiptOf cfg d := by + intro r hm x hx + have := (reachable_inv hr).resp r hm + unfold RespInv at this; grind + +/-- P6: every non-200 response is a 402 with a problem type, a challenge the server issued, + and no receipt (core §Status Codes: "Fresh challenge"). -/ +theorem P6_error_is_402_with_challenge (hr : Reachable cfg s) : + ∀ r ∈ s.resps, r.status ≠ 200 → + r.status = 402 ∧ r.receipt = none ∧ r.problem.isSome = true ∧ ∃ ch ∈ s.issued, r.challenge = some ch.p := by + intro r hm hne + have := (reachable_inv hr).resp r hm + unfold RespInv at this; grind + +/-- P6: a delivery (resource access) only ever comes from a submitted credential that check + accepted; every other step leaves the deliveries unchanged. -/ +theorem P6_delivery_only_after_check {a : Act} (h : step cfg s a = some s') : + s'.deliveries = s.deliveries ∨ + ∃ c, a = .submit c ∧ check cfg s c = none ∧ s'.deliveries = ⟨c.id, c.target, c.proof, s.now⟩ :: s.deliveries := by + cases a with + | submit c => + simp only [step] at h + split at h <;> simp only [Option.some.injEq] at h <;> subst h + · right; exact ⟨c, rfl, by assumption, rfl⟩ + · left; rfl + | retry c rc => + simp only [step] at h; split at h + · simp only [Option.some.injEq] at h; subst h; left; rfl + · cases h + | _ => simp only [step, Option.some.injEq] at h; subst h; left; rfl + +/-! ## P7 — side effects and idempotency (core §Idempotency and Side Effects) -/ + +/-- P7: an unpaid request records the challenge and its 402, and nothing else: no delivery, + no payment, no time. -/ +theorem P7_unpaid_request_only_records_challenge {t : Target} (h : step cfg s (.request t) = some s') : + s'.deliveries = s.deliveries ∧ s'.payments = s.payments ∧ s'.now = s.now ∧ + s'.issued = issue cfg s.now s.next t :: s.issued := by + simp only [step, Option.some.injEq] at h; subst h; simp [reject] + +/-- P7: a failed verification records a fresh challenge and its 402, and nothing else + (charge §Atomicity: no partial access). -/ +theorem P7_failed_no_effect {c : Cred} {pr : Problem} (hc : check cfg s c = some pr) + (h : step cfg s (.submit c) = some s') : + s'.deliveries = s.deliveries ∧ s'.payments = s.payments ∧ + s'.resps = ⟨402, some pr, some (issue cfg s.now s.next c.target).p, none⟩ :: s.resps := by + simp only [step, hc, Option.some.injEq] at h; subst h; simp [reject] + +/-- P7: an Idempotency-Key retry returns the original receipt and settles and delivers + nothing new. -/ +theorem P7_retry_no_effect {c : Cred} {rc : Receipt} (h : step cfg s (.retry c rc) = some s') : + s'.deliveries = s.deliveries ∧ s'.payments = s.payments ∧ + ∃ d ∈ s.deliveries, d.id = c.id ∧ rc = receiptOf cfg d := by + simp only [step] at h; split at h + · simp only [Option.some.injEq] at h; subst h; grind + · cases h + +/-! ## P8 — unique challenge ids (core §Required Parameters, id) -/ + +/-- P8: no two issued challenges share an id, so one client's payment can never find its + challenge already used by another's (GAPS.md row 5). -/ +theorem P8_unique_ids (hg : cfg.Guarded) (hr : Reachable cfg s) : (s.issued.map (·.p)).Nodup := by + unfold List.Nodup + rw [List.pairwise_map] + exact (reachable_inv hr).uniq hg.unique + +end IntentCharge + diff --git a/formal/intent-charge/IntentCharge/Witnesses.lean b/formal/intent-charge/IntentCharge/Witnesses.lean new file mode 100644 index 00000000..cdde5603 --- /dev/null +++ b/formal/intent-charge/IntentCharge/Witnesses.lean @@ -0,0 +1,125 @@ +import IntentCharge.Model +import IntentCharge.Counterexamples +/- + Witnesses: the guarded model is not vacuous. Each theorem runs the guarded model on one + fixed trace and checks by decide that its legitimate requests succeed, so a guard written + too strictly (rejecting what the drafts allow) breaks the build. They cover only these + traces. Also checked: the configurations satisfy Cfg.Guarded, and the boundary cases just + outside the rules (one second late, the wrong field, the wrong body, a replay) are refused. +-/ +namespace IntentCharge.Witnesses +open IntentCharge IntentCharge.Examples + +/-- The configuration the counterexamples use satisfies every guard. -/ +theorem guarded_ok : guarded.Guarded := ⟨rfl, rfl, rfl, rfl, rfl⟩ + +/-- A guarded server that selects Payment-Authorization (core §Credentials). -/ +def alt : Cfg := { guarded with altHeader := true } +/-- alt satisfies every guard. -/ +theorem alt_ok : alt.Guarded := ⟨rfl, rfl, rfl, rfl, rfl⟩ + +/-- The challenge the first request at time 1 gets. -/ +def c0 : Params := P guarded 1 0 CHEAP +/-- Its payment, the first one made. -/ +def p0 : Payment := pmt 0 c0 (price CHEAP) +/-- The one-time charge of core §Examples: 402 with a challenge, payment, credential, 200. -/ +def flow : List Act := [.request CHEAP, payFor c0 (price CHEAP), .submit (cred c0 p0 CHEAP)] + +/-- The charge flow succeeds: one delivery, and the last response is a 200 with the receipt + for payment 0, the first a 402 payment-required carrying c0. -/ +theorem W_charge_flow : + outcome guarded flow (fun st => st.deliveries.length == 1 && + st.resps == [⟨200, none, none, some ⟨METHOD, 0, 1⟩⟩, ⟨402, some .paymentRequired, some c0, none⟩]) + = some true := by decide + +/-- The dear route, paid 100 on its own challenge, is served. -/ +theorem W_dear_route : + let c := P guarded 1 0 DEAR + outcome guarded [.request DEAR, payFor c (price DEAR), .submit (cred c (pmt 0 c (price DEAR)) DEAR)] + (fun st => st.deliveries.length == 1) = some true := by decide + +/-- An Idempotency-Key retry gets the original receipt and no new delivery. -/ +theorem W_retry : + outcome guarded (flow ++ [.retry (cred c0 p0 CHEAP) ⟨METHOD, 0, 1⟩]) + (fun st => st.deliveries.length == 1 && st.resps.head? == some ⟨200, none, none, some ⟨METHOD, 0, 1⟩⟩) + = some true := by decide + +/-- Replaying the credential is refused with invalid-challenge (charge §Single-Use). -/ +theorem W_replay_rejected : + rejectedAt guarded (flow ++ [.submit (cred c0 p0 CHEAP)]) 3 = true ∧ + outcome guarded (flow ++ [.submit (cred c0 p0 CHEAP)]) + (fun st => st.resps.head?.map (·.problem) == some (some .invalidChallenge)) = some true := by + decide + +/-- A credential at the last second of the challenge's 300 s life is served (issued at 1, + expires at 301, submitted at 300). -/ +theorem W_last_second : + outcome guarded [.request CHEAP, payFor c0 (price CHEAP), .tick 299, .submit (cred c0 p0 CHEAP)] + (fun st => st.deliveries.length == 1) = some true := by decide + +/-- One second later (at 301) it is refused with payment-expired. -/ +theorem W_expired : + outcome guarded [.request CHEAP, payFor c0 (price CHEAP), .tick 300, .submit (cred c0 p0 CHEAP)] + (fun st => st.deliveries.length == 0 && + st.resps.head?.map (·.problem) == some (some .paymentExpired)) = some true := by decide + +/-- After a failed verification, the client pays the fresh challenge from the 402 and is + served (core §Failed Payment Verification). -/ +theorem W_fresh_challenge_after_failure : + let junk : Req := ⟨1, JUNK, MERCH⟩ + let c1 := P guarded 1 1 CHEAP + outcome guarded [.request CHEAP, payFor c0 junk, .submit (cred c0 (pmt 0 c0 junk) CHEAP), + payFor c1 (price CHEAP), .submit (cred c1 (pmt 1 c1 (price CHEAP)) CHEAP)] + (fun st => st.deliveries.length == 1 && st.issued.length == 2) = some true := by decide + +/-- With Payment-Authorization selected, a credential in that field is served. -/ +theorem W_alt_header : + let c := P alt 1 0 CHEAP + outcome alt [.request CHEAP, payFor c (price CHEAP), .submit ⟨c, c, true, pmt 0 c (price CHEAP), CHEAP⟩] + (fun st => st.deliveries.length == 1) = some true := by decide + +/-- The same credential in Authorization is refused (core §Credentials). -/ +theorem W_wrong_field : + let c := P alt 1 0 CHEAP + rejectedAt alt [.request CHEAP, payFor c (price CHEAP), .submit (cred c (pmt 0 c (price CHEAP)) CHEAP)] 2 + = true := by decide + +/-- A credential sent with another body than the challenge's digest is refused (core + §Request Body Digest Binding). -/ +theorem W_wrong_body : + rejectedAt guarded [.request CHEAP, payFor c0 (price CHEAP), .submit (cred c0 p0 ⟨1, 9⟩)] 2 = true := by + decide + +/-- An underpayment (0 instead of 1) is refused (charge §Server Responsibilities step 4). -/ +theorem W_underpaid : + let low : Req := ⟨0, USD, MERCH⟩ + rejectedAt guarded [.request CHEAP, payFor c0 low, .submit (cred c0 (pmt 0 c0 low) CHEAP)] 2 = true := by + decide + +/-- A payment to another recipient is refused (charge §Server Responsibilities step 5). -/ +theorem W_wrong_recipient : + let other : Req := ⟨1, USD, 6⟩ + rejectedAt guarded [.request CHEAP, payFor c0 other, .submit (cred c0 (pmt 0 c0 other) CHEAP)] 2 = true := by + decide + +/-- A credential that alters the echoed request (amount 0) under c0's id is refused. -/ +theorem W_tampered : + let forged : Params := { c0 with req := ⟨0, USD, MERCH⟩ } + rejectedAt guarded [.request CHEAP, .pay c0 0 USD MERCH, .submit ⟨c0, forged, false, ⟨0, c0, 0, USD, MERCH⟩, CHEAP⟩] 2 + = true := by decide + +/-- hmacInput reproduces the three HMAC inputs of core §HMAC-SHA256 Test Vectors, so the + collision in Gap8_hmac_input_collision uses the draft's own layout. -/ +theorem W_hmac_test_vector_inputs : + hmacInput "api.example.com" "tempo" "charge" "eyJhbW91bnQiOiIxMDAwMDAwIn0" "" "" none none = + "api.example.com|tempo|charge|eyJhbW91bnQiOiIxMDAwMDAwIn0|||" ∧ + hmacInput "api.example.com" "tempo" "charge" "eyJhbW91bnQiOiIxMDAwMDAwIn0" "" "" + (some "Payment-Authorization") none = + "api.example.com|tempo|charge|eyJhbW91bnQiOiIxMDAwMDAwIn0|||Payment-Authorization|" ∧ + hmacInput "api.example.com" "tempo" "charge" "eyJhbW91bnQiOiIxMDAwMDAwIn0" "" "" + (some "Payment-Authorization") (some "eyJwaSI6InBpXzEyMyJ9") = + "api.example.com|tempo|charge|eyJhbW91bnQiOiIxMDAwMDAwIn0|||Payment-Authorization|eyJwaSI6InBpXzEyMyJ9" := by + decide + +end IntentCharge.Witnesses + diff --git a/formal/intent-charge/README.md b/formal/intent-charge/README.md new file mode 100644 index 00000000..e7003a8c --- /dev/null +++ b/formal/intent-charge/README.md @@ -0,0 +1,72 @@ +# Charge intent formal model + +A Lean 4 model of the Payment HTTP authentication scheme ([draft-httpauth-payment-01](../../specs/core/draft-httpauth-payment-01.md)) with the charge intent ([draft-payment-intent-charge-00](../../specs/intents/draft-payment-intent-charge-00.md)), independent of any payment method. Lean checks every proof. + +## Run + +Install elan from a release, checking its SHA-256 as `.github/workflows/formal.yml` does (it pins the version and checksum), then: + +~~~bash +bash formal/intent-charge/check.sh # clean build plus axiom audit; prints OK +~~~ + +- `lean-toolchain` pins Lean (the same as every model under `formal/`). Requires only `MppCore` from `../core`; no Mathlib. +- A clean build takes about 5 s. + +## What it checks + +- `lakefile.toml` sets `warningAsError`: a `sorry` or an unused hypothesis fails the build. +- `check.sh` runs the shared gate in [`../core`](../core): a clean build, then an axiom audit with kernel replay over every module of the model and `MppCore`, which rules out `sorry`, `admit` and `native_decide`. It refuses `set_option`, `import Lean`, metaprogramming and `skipKernelTC`. + +## Files + +| File | Contents | +|---|---| +| `Model.lean` | Challenge, Credential, Receipt, the server's `check` and `step`, with § citations; `Reachable` | +| `Invariant.lean` | Inductive invariant `Inv`, proved for every reachable state and every `Cfg` | +| `Properties.lean` | P1–P8, below | +| `Counterexamples.lean` | One trace per gap with its guard off, checked by `decide` ([GAPS.md](./GAPS.md)) | +| `Witnesses.lean` | Legitimate flows that succeed with every guard on, and boundary cases that fail | +| `../core` | Shared `run`, `Reachable`, `upd`, and the gate `check.sh` runs | + +## What is modelled + +- Unpaid request: 402 with a fresh challenge, and no other state change. +- Challenge parameters bound to the id: realm, method, intent, request (amount, currency, recipient), expires, digest, opaque, header. +- Credential verification in the order of core §Status Codes and charge §Server Responsibilities: binding, single use, expiry, credential field, body digest, then the method's proof check (amount, recipient, currency). +- 200 with a Payment-Receipt, or 402 with a problem type and a fresh challenge. +- Idempotency-Key retries served from the cached response. +- Anyone can make any payment, and payments are public (core §Threat Model). + +## What is abstracted + +- Crypto is perfect: the challenge id *is* its bound parameter tuple (an injective, unforgeable MAC), so a stateless HMAC server and a stateful one are the same model. `hmacInput` models the draft's string encoding separately (gap 8). +- The payment method is an opaque verifier: a payment is a record of what was paid and for which challenge. The method's own single-use rule (core §Replay Protection) is a check on spent payment refs. +- Network, TLS, parsing (`malformed-credential`), 401/403, caching, finality and chargebacks are not modelled. +- Each step is atomic, as core §Concurrent Request Handling requires. + +## Properties + +Every theorem holds for all reachable states with the guards on (`Cfg.Guarded`: five flags, [GAPS.md](./GAPS.md)). + +| # | Property | Theorems | +|---|---|---| +| P1 | A Credential only pays the Challenge it answers, with a real payment | `P1_pays_own_challenge`, `P1_payment_real` | +| P2 | Every delivery answers a challenge this server issued (realm, method, charge); altered or unknown ids are refused | `P2_binding`, `P2_tampered_rejected`, `P2_unknown_rejected` | +| P3 | Every delivery is before its challenge's expiry, at most `ttl` after issue; expired ones get `payment-expired` | `P3_delivered_before_expiry`, `P3_expired_rejected` | +| P4 | At most one delivery per challenge and per payment; a replay gets `invalid-challenge` | `P4_single_use`, `P4_no_double_spend`, `P4_replay_rejected` | +| P5 | Amount, recipient and currency match the request and the target's price; body matches the digest; wrong field refused | `P5_matches_request`, `P5_matches_target_price`, `P5_digest`, `P5_wrong_field_rejected` | +| P6 | Receipts only on a 200 after verified payment; every error is a 402 with a fresh issued challenge and no receipt; deliveries only from an accepted credential | `P6_receipt_only_after_payment`, `P6_error_is_402_with_challenge`, `P6_delivery_only_after_check` | +| P7 | Unpaid requests and failed verifications only record a challenge; retries add no settlement or delivery | `P7_unpaid_request_only_records_challenge`, `P7_failed_no_effect`, `P7_retry_no_effect` | +| P8 | Challenge ids are unique | `P8_unique_ids` | + +- One-step theorems (`*_rejected`, P6 delivery, P7) check that `check` and `step` encode each rule as the drafts state it. + +## Modelling choices + +- Used ids and spent payments are read off the delivery log, so single use cannot drift from what was delivered. +- The server keeps a used-id store even when it binds with HMAC: core §Status Codes requires `invalid-challenge` for an already-used id (gap 6). +- A credential in the wrong field counts as no credential (`payment-required`). +- A payment matches when the amount is equal, not greater. +- One server, one realm and method; `Cfg.price` is its route table. Clients' own checks (core §Amount Verification) are not modelled: the properties hold whatever clients pay. + diff --git a/formal/intent-charge/check.sh b/formal/intent-charge/check.sh new file mode 100644 index 00000000..c8ccc919 --- /dev/null +++ b/formal/intent-charge/check.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +# Build the model from clean and fail unless every proof checks and only Lean's standard axioms +# are used. CI runs this; so can you (needs elan, see README.md). The gates live in +# ../core/check-lib.sh, shared by every model. +set -euo pipefail +cd "$(dirname "$0")" +exec bash ../core/check-lib.sh IntentCharge diff --git a/formal/intent-charge/lake-manifest.json b/formal/intent-charge/lake-manifest.json new file mode 100644 index 00000000..4f614b13 --- /dev/null +++ b/formal/intent-charge/lake-manifest.json @@ -0,0 +1,14 @@ +{"version": "1.3.0", + "packagesDir": ".lake/packages", + "packages": + [{"type": "path", + "scope": "", + "name": "MppCore", + "manifestFile": "lake-manifest.json", + "inherited": false, + "dir": "../core", + "copy": false, + "configFile": "lakefile.toml"}], + "name": "IntentCharge", + "lakeDir": ".lake", + "fixedToolchain": false} diff --git a/formal/intent-charge/lakefile.toml b/formal/intent-charge/lakefile.toml new file mode 100644 index 00000000..c3ca2e09 --- /dev/null +++ b/formal/intent-charge/lakefile.toml @@ -0,0 +1,18 @@ +name = "IntentCharge" +version = "0.1.0" +defaultTargets = ["IntentCharge"] + +# Every warning is a build error: a sorry, a deprecated name, an unused variable or simp +# argument fails 'lake build' itself, not only the axiom audit. +# The shared definitions in ../core (run, Reachable, upd), audited with this model. +[[require]] +name = "MppCore" +path = "../core" + +[leanOptions] +warningAsError = true + +[[lean_lib]] +name = "IntentCharge" +# Build every module under IntentCharge/, even one nothing imports, so no proof goes unchecked. +globs = ["IntentCharge", "IntentCharge.+"] diff --git a/formal/intent-charge/lean-toolchain b/formal/intent-charge/lean-toolchain new file mode 100644 index 00000000..a6aff065 --- /dev/null +++ b/formal/intent-charge/lean-toolchain @@ -0,0 +1 @@ +leanprover/lean4:v4.35.0 diff --git a/formal/tempo-charge/.gitignore b/formal/tempo-charge/.gitignore new file mode 100644 index 00000000..01f8cdb6 --- /dev/null +++ b/formal/tempo-charge/.gitignore @@ -0,0 +1 @@ +.lake/ diff --git a/formal/tempo-charge/GAPS.md b/formal/tempo-charge/GAPS.md new file mode 100644 index 00000000..5ebeb055 --- /dev/null +++ b/formal/tempo-charge/GAPS.md @@ -0,0 +1,19 @@ +# Spec gaps + +Each row is a rule draft-tempo-charge-00 leaves out. With its guard off, `TempoCharge/Counterexamples.lean` holds a `decide`-checked trace that breaks the named property; with the guard on, the same trace is rejected at the guarded step (`rejectedAt`), or for row 2 runs without a receipt. Rows 5 and 7 hold with every guard on; row 6 is wording. + +| # | Where | Gap | Guard (`Cfg`) | Breaks | Counterexample | +|---|---|---|---|---|---| +| 1 | §Hash Verification; core §Replay Protection, §Concurrent Request Handling | A spent transaction's hash is not refused again: one payment settles a pull challenge and a hash challenge with the same request, after the pull settles or in the window between its broadcast and its settlement | `txSingleUse` | P3 | `G1_violates_P3`, `G1_guard_rejects`, `G1_race_window`, `G1_race_violates_P3`, `G1_race_guard_rejects` | +| 2 | §Settlement Procedure, §Transaction Verification | Pull settlement never requires the broadcast transaction to succeed (only hash settlement does); a reverted transfer gets a receipt | `pullNeedsSuccess` | P1 | `G2_violates_P1`, `G2_guard_no_receipt` | +| 3 | §Proof Verification | No amount check: a free proof settles a non-zero challenge (only clients are told not to) | `proofOnlyZero` | P1 | `G3_violates_P1`, `G3_guard_rejects` | +| 4 | §Ordering, §Transaction Verification step 6, §Hash Verification | Required transfers are not matched one-to-one: two identical splits are satisfied by one transfer, so less than `amount` is paid | `splitsOneToOne` | P1 | `G4_violates_P1`, `G4_guard_rejects` | +| 5 | §Hash Verification, §Hash Payload | A hash credential is bound to neither payer nor challenge: an observer claims another client's public transfer (even one older than its challenge) and the payer's own credential is then refused | none: every guard on | payer gets nothing for its payment | `Gap5_observer_claims_payment`, `Gap5_payer_rejected` | +| 6 | §Shared Fields, §Method Details; intent §Shared Fields | `expires` stays optional (core SHOULD), though the intent calls it REQUIRED for blockchain methods and `validBefore` "no later than `expires`" needs it | modelled: `expires` always present | wording | — | +| 7 | §Transaction Verification, §Transaction Payload | A pull transaction is not bound to its challenge: a holder of the credential submits the transaction signed for one challenge with another same-terms challenge's echo, which settles; the original challenge is then refused | none: every guard on | payer's payment settles a challenge it didn't sign for | `Gap7_pull_rebinds`, `Gap7_payer_rejected` | + +- Row 1: with the guard, the server records a pull transaction when it broadcasts it, before settling it, and a hash transaction when it settles it, and refuses a hash credential naming any recorded transaction. Recording a pull transaction only at settlement is too late: core §Concurrent Request Handling serializes only identical credentials, so a hash credential for another challenge can arrive after the transaction is on chain and before it is recorded (`G1_race_*`). Nonce consumption only stops a second broadcast. +- Row 2: with the guard, a reverted pull transaction leaves the challenge open and issues no receipt; the sponsor still paid its fee (§Server-Paid Fees, Denial of Service). +- Row 4: `splits[i]` entries with equal recipient and amount are allowed (only sum < `amount` and each > 0 are required). A split recipient equal to the primary recipient with an equal amount fails the same way. +- Row 5: closing it needs the transfer to commit to the challenge (for example a memo derived from the challenge id) or to the `source` account with `source` authenticated; the draft requires neither. Proof credentials are not affected; pull credentials have the narrower row 7. +- Row 7: a pull transaction reaches only the server, so only a holder of the credential (a proxy, a client library, a compromised client) can rebind it, not an observer of the chain. Closing it needs the same commitment as row 5, such as a memo derived from the challenge id. diff --git a/formal/tempo-charge/README.md b/formal/tempo-charge/README.md new file mode 100644 index 00000000..b8012854 --- /dev/null +++ b/formal/tempo-charge/README.md @@ -0,0 +1,67 @@ +# Tempo charge formal model + +A Lean 4 model of [draft-tempo-charge-00](../../specs/methods/tempo/draft-tempo-charge-00.md): pull (transaction), push (hash) and zero-amount proof credentials, fee sponsorship, splits, expiry and validBefore, replay rules and receipts, on top of the core scheme's challenge binding and the charge intent's single-use rule. Lean checks every proof. + +## Run + +Install elan from a release, checking its SHA-256 as `.github/workflows/formal.yml` does (it pins the version and checksum), then: + +~~~bash +bash formal/tempo-charge/check.sh # clean build plus axiom audit; prints OK +~~~ + +- `lean-toolchain` pins Lean (the same as every model under `formal/`). Requires only `MppCore` from `../core`; no Mathlib. +- `check.sh` runs the shared gate in [`../core`](../core): `warningAsError`, no `set_option`, no metaprogramming or `import Lean`, and an axiom audit with kernel replay that rules out `sorry`, `admit`, `native_decide` and declared axioms. + +## Files + +| File | Contents | +|---|---| +| `Model.lean` | Requests, challenges, credentials, transactions, the computable `step` with § citations, `Reachable` | +| `Invariant.lean` | Inductive invariant `SysInv`, proved for every reachable state | +| `Properties.lean` | P1–P9, below, and the split arithmetic (`matchOne_amount`) | +| `Counterexamples.lean` | One `decide`-checked trace per gap ([GAPS.md](./GAPS.md)) | +| `Witnesses.lean` | Legitimate flows that succeed with every guard on, and boundary calls that fail | +| `../core` | Shared `run`, `Reachable`, `upd`, and the gate `check.sh` runs | + +## What is modelled + +- Server: issues challenges (fresh id, its realm, valid request: splits each > 0 with sum < amount, at least one mode), and checks each credential: binding (echo = issued), unused, not pending, not expired, then the method checks. +- Pull: two steps. `submit` runs §Transaction Verification steps 2–7 and broadcasts (with the server's fee payer signature when `feePayer`), leaving the settlement pending; `settlePull` later settles and issues the receipt (only for a successful transaction, G2). Other credentials interleave between the two. +- Push: §Hash Settlement limitations (no `feePayer`, `push` allowed) and §Hash Verification (successful receipt, matching Transfer events). +- Proof: §Proof Verification steps 1–4 with domain version 3 (account, challengeId, realm, chainId). +- Chain: TIP-20 balances, atomic transfers, 2D nonce consumption (a revert still consumes it), validBefore, chain id, fee sponsorship. + +## What is abstracted + +- Crypto is perfect: hashes are injective (a transaction is its hash; the challenge binding is equality), signatures unforgeable (only `signTx` / `signProof` add). +- Network: one server; hash and proof credentials are handled in one step (verify, settle, deliver), a pull credential in two (verify and broadcast, then settle and deliver), with any other action between them, since core §Concurrent Request Handling serializes only identical credentials. `eth_sendRawTxSync` returns once the transaction is on chain, so broadcast and inclusion are one step. A receipt stands for 200 + `Payment-Receipt` + resource. +- Chain: one chain, immediate finality, no reorgs; a transaction's calls are its transfers and their events (no swaps or smart wallets); fee amounts and fee tokens are not tracked, only who paid (`sponsored`). +- Not modelled: access-key proof signers (§Proof Verification step 5), ERC-1271, `Idempotency-Key`, `digest` / `opaque` / `header`, `externalId`, `description`. + +## Properties + +State properties hold for all reachable states with every guard on (`Cfg.Guarded`, four flags). + +| # | Property | Theorems | +|---|---|---| +| P1 | A receipt means its challenge was paid: a successful on-chain transaction matching the request one-to-one, moving at least `amount` of `currency`; or, for a proof, a free challenge and a version 3 proof binding its id, realm and chain | `P1_receipt_paid`, `matchOne_amount` | +| P2 | At most one receipt per challenge (single use, no double delivery) | `P2_one_receipt_per_challenge` | +| P3 | At most one challenge per transaction, across pull and push (no double counting) | `P3_one_challenge_per_tx` | +| P4 | A receipt answers the submitted credential's challenge, which was issued with that exact echo, unused and unexpired (for pull, when it was broadcast); nothing else issues receipts; replayed, expired and tampered credentials are rejected | `P4_receipt_answers_challenge`, `P4_pending_answers_challenge`, `P4_replay_rejected`, `P4_expired_rejected`, `P4_unbound_rejected` | +| P5 | Receipts and used challenges are permanent | `P5_monotone` | +| P6 | The server pays fees only for challenges with `feePayer: true`; hash credentials for those are rejected | `P6_sponsor_only_feePayer`, `P6_hash_feePayer_rejected` | +| P7 | A transaction lands only before its `validBefore`, so a client following §Method Details is never charged after `expires` | `P7_included_before_validBefore`, `P7_no_charge_after_expiry` | +| P8 | Proofs need `source` and must bind challenge id, realm, chain, signer = account and version 3 | `P8_proof_needs_source`, `P8_proof_binding` | +| P9 | Pull needs `pull` and push needs `push` in `supportedModes` | `P9_pull_needs_pull_mode`, `P9_hash_needs_push_mode` | + +The one-step `*_rejected`, `P8` and `P9` theorems are sanity checks that `step` encodes the rule as the draft states it. + +## Modelling choices + +- Guards for rules the draft leaves out are `Cfg` flags, default on; each has a counterexample with it off ([GAPS.md](./GAPS.md)). +- `splits = []` means absent; `pull` / `push` stand for `supportedModes` (both true when omitted). +- A pull transaction that reverts stays on chain (nonce used, fee paid by the sponsor); its settlement issues no receipt and the challenge reopens, so a client can retry; §Server-Paid Fees accepts that fee risk. +- The server sponsors any pull transaction for a `feePayer` challenge; one with `sponsor = false` needs no fee payer. +- `expires` is always present (see GAPS.md row 6). +- `Challenge.client` is a ghost field (who asked), used only to state Gap 5. diff --git a/formal/tempo-charge/TempoCharge.lean b/formal/tempo-charge/TempoCharge.lean new file mode 100644 index 00000000..af842c3b --- /dev/null +++ b/formal/tempo-charge/TempoCharge.lean @@ -0,0 +1,7 @@ +-- Root module: imports the whole model. check.sh builds every module under TempoCharge/ and +-- runs the axiom audit (Audit.lean) over each of them. +import TempoCharge.Model +import TempoCharge.Invariant +import TempoCharge.Properties +import TempoCharge.Counterexamples +import TempoCharge.Witnesses diff --git a/formal/tempo-charge/TempoCharge/Counterexamples.lean b/formal/tempo-charge/TempoCharge/Counterexamples.lean new file mode 100644 index 00000000..84228d47 --- /dev/null +++ b/formal/tempo-charge/TempoCharge/Counterexamples.lean @@ -0,0 +1,181 @@ +import TempoCharge.Model +import TempoCharge.Properties +/- + Spec gaps as machine-checked counterexamples. Each trace runs on the executable model with + ONE guard off and shows a property broken; with every guard on the same trace is rejected at + the step the guard blocks (rejectedAt), or, for G2, runs without issuing a receipt. Gaps 5 + and 7 hold with every guard on. All checked by 'decide' (kernel evaluation, no native code). + GAPS.md maps each one to its section. +-/ +namespace TempoCharge.Examples +open TempoCharge + +-- Concrete instance: one server realm, one chain, one token. +def REALM : Nat := 1 +def CHAIN : Nat := 4217 +def TOKEN : Nat := 0x20c0 +def PAYER : Nat := 2 +def OBSERVER : Nat := 3 +def MERCHANT : Nat := 10 +def PLATFORM : Nat := 11 + +/-- Every guard on (the model the theorems are about). -/ +def guarded : Cfg := { realm := REALM, chainId := CHAIN } + +/-- 100 base units of TOKEN to MERCHANT, both modes, client pays fees. -/ +def req : Request := { amount := 100, currency := TOKEN, recipient := MERCHANT, chainId := CHAIN } +/-- A challenge issued to PAYER. -/ +def chA : Challenge := { id := 1, realm := REALM, request := req, expires := 100, client := PAYER } +/-- The same request issued to someone else under another id (a fixed-price resource). -/ +def chB : Challenge := { chA with id := 2, client := OBSERVER } +/-- The payment for req, signed by PAYER. -/ +def pay : Transfer := { token := TOKEN, dst := MERCHANT, amount := 100 } +def tx1 : Tx := { sender := PAYER, chainId := CHAIN, nonce := 0, calls := [pay] } + +/-- Run tr from St.init and evaluate prop on the final state; none if a step fails. -/ +def check (cfg : Cfg) (tr : List Act) (prop : St → Bool) : Option Bool := + (run cfg St.init tr).map prop + +/-- cfg rejects tr exactly at action n: the first n actions succeed and action n fails. -/ +def rejectedAt (cfg : Cfg) (tr : List Act) (n : Nat) : Bool := + match run cfg St.init (tr.take n), tr[n]? with + | some st, some a => (step cfg st a).isNone + | _, _ => false + +-- Bool forms of the properties, so decide can evaluate them. +/-- P3: no transaction backs two receipts. -/ +def p3 (st : St) : Bool := decide (st.receipts.filterMap (fun r => r.ref.txOf)).Nodup +/-- P1 (transaction part): every transaction receipt's transaction succeeded on chain. -/ +def p1ok (st : St) : Bool := + st.receipts.all fun r => match r.ref with + | .tx t => succeeded st t + | .challenge _ => true +/-- P1 (proof part): every proof receipt is for a free challenge. -/ +def p1free (st : St) : Bool := + st.receipts.all fun r => match r.ref, st.issued r.cid with + | .challenge _, some c => c.request.amount == 0 + | _, _ => true +/-- P1 (amount part): every transaction receipt's transaction moved at least amount. -/ +def p1amount (st : St) : Bool := + st.receipts.all fun r => match r.ref, st.issued r.cid with + | .tx t, some c => decide (c.request.amount ≤ sumOn c.request.currency t.calls) + | _, _ => true + +/-! ### G1 — §Hash Verification: a spent transaction's hash is not refused again. + The hash checks (successful receipt, matching Transfer events, push allowed, no feePayer) + hold for any challenge with the same request, so one payment settles two challenges: here + by pull for chA, then by hash for chB. Core §Replay Protection wants single-use proofs; + the draft relies on nonce consumption, which stops a second broadcast, not a second claim. -/ +def trG1 : List Act := + [.fund TOKEN PAYER 100, .issue chA, .issue chB, .signTx tx1, + .submit { echo := chA, payload := .transaction tx1 }, .settlePull 1, + .submit { echo := chB, payload := .hash tx1 }] +def cfgG1 : Cfg := { guarded with txSingleUse := false } +/-- G1: with the guard off, one transaction backs two receipts (P3 broken). -/ +theorem G1_violates_P3 : check cfgG1 trG1 p3 = some false := by decide +/-- G1: with every guard on, the second claim is rejected. -/ +theorem G1_guard_rejects : rejectedAt guarded trG1 6 = true := by decide + +/-! ### G1, the race — recording a pull transaction only at settlement is too late. + Core §Concurrent Request Handling serializes only identical credentials, so a hash + credential for chB can arrive after the server broadcast tx1 for chA (it is on chain) and + before it settles chA. A server that records transactions only when it settles them has not + recorded tx1 yet, so even refusing recorded hashes would accept chB's claim. -/ +def trRace : List Act := + [.fund TOKEN PAYER 100, .issue chA, .issue chB, .signTx tx1, + .submit { echo := chA, payload := .transaction tx1 }, .submit { echo := chB, payload := .hash tx1 }, + .settlePull 1] +/-- G1 race: after the broadcast tx1 succeeded on chain, but a server recording at settlement + has not recorded it and issued no receipt yet. -/ +theorem G1_race_window : + check cfgG1 (trRace.take 5) + (fun st => succeeded st tx1 && decide (tx1 ∉ st.consumedTx) && st.receipts.isEmpty) = some true := by + decide +/-- G1 race: with the guard off, chB settles by hash, then chA's pull settles: one transaction + backs two receipts (P3 broken). -/ +theorem G1_race_violates_P3 : check cfgG1 trRace p3 = some false := by decide +/-- G1 race: with every guard on, tx1 was recorded at broadcast and the hash claim is + rejected. -/ +theorem G1_race_guard_rejects : rejectedAt guarded trRace 5 = true := by decide + +/-! ### G2 — §Settlement Procedure: no rule that a pull transaction succeeded. + §Hash Verification requires a successful receipt; the pull steps only say the transaction + was "included in block". PAYER has no balance, so the transfer reverts (the sponsoring + server even pays its fee), and a server that only checks inclusion delivers unpaid. -/ +def reqF : Request := { req with feePayer := true, push := false } +def chF : Challenge := { chA with request := reqF } +def txF : Tx := { tx1 with sponsor := true } +def trG2 : List Act := + [.issue chF, .signTx txF, .submit { echo := chF, payload := .transaction txF }, .settlePull 1] +def cfgG2 : Cfg := { guarded with pullNeedsSuccess := false } +/-- G2: with the guard off, a receipt backs a reverted transaction (P1 broken). -/ +theorem G2_violates_P1 : check cfgG2 trG2 p1ok = some false := by decide +/-- G2: with every guard on, the same trace runs (the revert is on chain, the server paid the + fee, as §Server-Paid Fees warns) but issues no receipt, and the challenge reopens. -/ +theorem G2_guard_no_receipt : + check guarded trG2 (fun st => st.receipts.isEmpty && st.sponsored == [1] && !st.used 1 && + (st.pending 1).isNone) = some true := by + decide + +/-! ### G3 — §Proof Verification: no amount check. + Clients MUST NOT use a proof for a non-zero amount, but the server's five steps never look at + the amount, so a free signature settles a paid challenge. -/ +def proofA : ProofSig := + { signer := PAYER, account := PAYER, challengeId := 1, realm := REALM, chainId := CHAIN, version := 3 } +def trG3 : List Act := + [.issue chA, .signProof proofA, .submit { echo := chA, payload := .proof proofA, source := some (CHAIN, PAYER) }] +def cfgG3 : Cfg := { guarded with proofOnlyZero := false } +/-- G3: with the guard off, a 100-unit challenge gets a receipt for a proof (P1 broken), and + MERCHANT received nothing. -/ +theorem G3_violates_P1 : + check cfgG3 trG3 (fun st => !p1free st && st.bal TOKEN MERCHANT == 0) = some true := by decide +/-- G3: with every guard on, the proof is rejected. -/ +theorem G3_guard_rejects : rejectedAt guarded trG3 2 = true := by decide + +/-! ### G4 — §Ordering, §Transaction Verification step 6: matching is not one-to-one. + Two identical splits (10 each to PLATFORM, allowed: sum 20 < 30) are both "present" in one + transfer of 10, so a transaction paying 20 passes a 30-unit challenge. -/ +def reqS : Request := + { req with amount := 30, splits := [{ recipient := PLATFORM, amount := 10 }, { recipient := PLATFORM, amount := 10 }] } +def chS : Challenge := { chA with request := reqS } +def txS : Tx := { tx1 with calls := [{ pay with amount := 10 }, { pay with dst := PLATFORM, amount := 10 }] } +def trG4 : List Act := + [.fund TOKEN PAYER 30, .issue chS, .signTx txS, .submit { echo := chS, payload := .transaction txS }, .settlePull 1] +def cfgG4 : Cfg := { guarded with splitsOneToOne := false } +/-- G4: with the guard off, a receipt backs a transaction that moved 20 of 30 (P1 broken). -/ +theorem G4_violates_P1 : + check cfgG4 trG4 (fun st => !p1amount st && st.bal TOKEN PAYER == 10) = some true := by decide +/-- G4: with every guard on, the transaction is rejected. -/ +theorem G4_guard_rejects : rejectedAt guarded trG4 3 = true := by decide + +/-! ### Gap 5 — §Hash Verification: a hash credential is bound to neither payer nor challenge. + With every guard on: PAYER broadcasts tx1 for chA; before PAYER submits it, OBSERVER (who + asked for chB, the same request) submits tx1's public hash and gets the resource; PAYER's own + credential is then refused, since tx1 is spent. The transaction even predates chB. -/ +def trGap5 : List Act := + [.fund TOKEN PAYER 100, .issue chA, .signTx tx1, .broadcast tx1, .issue chB, + .submit { echo := chB, payload := .hash tx1 }, .submit { echo := chA, payload := .hash tx1 }] +/-- Gap 5: with every guard on, OBSERVER's claim of PAYER's transfer succeeds. -/ +theorem Gap5_observer_claims_payment : + check guarded (trGap5.take 6) (fun st => st.receipts == [⟨2, .tx tx1, 1⟩] && + tx1.sender != chB.client) = some true := by decide +/-- Gap 5: and PAYER's own credential for chA is then rejected. -/ +theorem Gap5_payer_rejected : rejectedAt guarded trGap5 6 = true := by decide + +/-! ### Gap 7 — §Transaction Verification: a pull transaction is not bound to its challenge. + With every guard on: PAYER signs tx1 to pay chA. Its transfers match any challenge with the + same request, so whoever holds the credential (it reaches only the server, so a proxy, a + client library or a compromised client) submits tx1 with chB's echo instead and chB settles; + PAYER's credential for chA is then refused, since tx1's nonce is spent. -/ +def trGap7 : List Act := + [.fund TOKEN PAYER 100, .issue chA, .issue chB, .signTx tx1, + .submit { echo := chB, payload := .transaction tx1 }, .settlePull 2, + .submit { echo := chA, payload := .transaction tx1 }] +/-- Gap 7: with every guard on, the transaction PAYER signed for chA settles chB. -/ +theorem Gap7_pull_rebinds : + check guarded (trGap7.take 6) (fun st => st.receipts == [⟨2, .tx tx1, 1⟩] && + st.bal TOKEN MERCHANT == 100) = some true := by decide +/-- Gap 7: and the credential for chA is then rejected. -/ +theorem Gap7_payer_rejected : rejectedAt guarded trGap7 6 = true := by decide + +end TempoCharge.Examples diff --git a/formal/tempo-charge/TempoCharge/Invariant.lean b/formal/tempo-charge/TempoCharge/Invariant.lean new file mode 100644 index 00000000..6248f51b --- /dev/null +++ b/formal/tempo-charge/TempoCharge/Invariant.lean @@ -0,0 +1,281 @@ +import TempoCharge.Model +/- + Inductive invariant over all reachable states (every guard on), and the arithmetic lemma that + turns a one-to-one match into "at least amount was transferred". + + Proof plan + * SysInv: what the server's records and the chain satisfy together. + * inv_init / inv_step / reachable_inv: induction on Reachable. inv_step dispatches to one + lemma per action (inv_pull and inv_settlePull for the two pull steps), each splitting step + into one goal per guard outcome and letting grind rebuild SysInv in each. +-/ +namespace TempoCharge + +/-- What a receipt's reference proves about challenge c (the facts P1 reads off). + * a transaction: it is on chain and succeeded, the server recorded it, and its transfers + match the request one-to-one; + * a proof: it names this challenge, the request was free, and a version 3 proof signed by + its account binds this challenge id, realm and chain. -/ +structure RefOk (st : St) (c : Challenge) (r : Receipt) : Prop where + tx : ∀ t, r.ref = .tx t → + succeeded st t = true ∧ t ∈ st.consumedTx ∧ matchOne t.calls c.request.required = true + proof : ∀ id, r.ref = .challenge id → + id = r.cid ∧ c.request.amount = 0 ∧ + ∃ p ∈ st.proofSigs, p.signer = p.account ∧ p.challengeId = c.id ∧ p.realm = c.realm ∧ + p.chainId = c.request.chainId ∧ p.version = 3 + +/-- The global invariant. -/ +structure SysInv (cfg : Cfg) (st : St) : Prop where + /-- Every issued challenge sits under its own id, in this realm, with a valid request. -/ + issued_ok : ∀ id c, st.issued id = some c → + c.id = id ∧ c.realm = cfg.realm ∧ c.request.valid cfg.chainId = true + /-- Every receipt names a used, issued challenge, and its reference proves the payment. -/ + receipts_ok : ∀ r ∈ st.receipts, st.used r.cid = true ∧ + ∃ c, st.issued r.cid = some c ∧ RefOk st c r + /-- A transaction-referenced receipt's transaction was recorded. -/ + consumed_ok : ∀ r ∈ st.receipts, ∀ t, r.ref = .tx t → t ∈ st.consumedTx + /-- At most one receipt per challenge. -/ + cids_nodup : (st.receipts.map Receipt.cid).Nodup + /-- At most one receipt per transaction. -/ + txs_nodup : (st.receipts.filterMap fun r => r.ref.txOf).Nodup + /-- The server paid fees only for challenges that offered it. -/ + sponsored_ok : ∀ id ∈ st.sponsored, ∃ c, st.issued id = some c ∧ c.request.feePayer = true + /-- Every included transaction landed before its validBefore. -/ + validBefore_ok : ∀ i ∈ st.included, ∀ vb, i.tx.validBefore = some vb → i.time < vb + /-- A pending pull settlement names an unused, issued challenge its transaction matches + one-to-one; the transaction is on chain with the recorded outcome, recorded as spent (G1), + and no receipt references it yet (what its receipt's RefOk and P3 need). -/ + pending_ok : ∀ cid t ok, st.pending cid = some (t, ok) → + st.used cid = false ∧ (∃ c, st.issued cid = some c ∧ matchOne t.calls c.request.required = true) ∧ + (∃ i ∈ st.included, i.tx = t ∧ i.ok = ok) ∧ t ∈ st.consumedTx ∧ ∀ r ∈ st.receipts, r.ref ≠ .tx t + /-- No transaction is pending for two challenges. -/ + pending_tx : ∀ cid cid' t ok ok', st.pending cid = some (t, ok) → st.pending cid' = some (t, ok') → + cid = cid' + +/-- The empty chain and server satisfy SysInv. -/ +theorem inv_init (cfg : Cfg) : SysInv cfg St.init := by + constructor <;> simp [St.init] + +/-- A transaction on chain has a used nonce, so the chain refuses it again. -/ +theorem not_nonceFree_of_succeeded {st : St} {t : Tx} (h : succeeded st t = true) : + nonceFree st t = false := by + simp only [succeeded, List.any_eq_true, Bool.and_eq_true, beq_iff_eq] at h + obtain ⟨i, hi, he, _⟩ := h + simp only [nonceFree, Bool.not_eq_false', List.any_eq_true, Bool.and_eq_true, beq_iff_eq] + exact ⟨i, hi, by rw [he]; exact ⟨rfl, rfl⟩⟩ + +/-- A filterMap member came from some element. -/ +theorem txOf_mem {l : List Receipt} {t : Tx} (h : t ∈ l.filterMap fun r => r.ref.txOf) : + ∃ r ∈ l, r.ref = .tx t := by + simp only [List.mem_filterMap] at h + obtain ⟨r, hr, he⟩ := h + refine ⟨r, hr, ?_⟩ + cases hx : r.ref <;> simp_all [Ref.txOf] + +/-- RefOk survives any step that keeps successful transactions, recorded transactions and + signed proofs (all three only grow). -/ +theorem RefOk.mono {st st' : St} {c : Challenge} {r : Receipt} (h : RefOk st c r) + (hs : ∀ t, succeeded st t = true → succeeded st' t = true) + (hc : ∀ t ∈ st.consumedTx, t ∈ st'.consumedTx) + (hp : ∀ p ∈ st.proofSigs, p ∈ st'.proofSigs) : RefOk st' c r := by + obtain ⟨htx, hpf⟩ := h + constructor + · intro t ht + obtain ⟨a, b, d⟩ := htx t ht + exact ⟨hs t a, hc t b, d⟩ + · intro id hid + obtain ⟨a, b, p, hp1, hp2⟩ := hpf id hid + exact ⟨a, b, p, hp p hp1, hp2⟩ + +/-- RefOk for a transaction reference, from the three facts about it. -/ +theorem RefOk.ofTx {st : St} {c : Challenge} {t : Tx} {cid time : Nat} + (hs : succeeded st t = true) (hc : t ∈ st.consumedTx) + (hm : matchOne t.calls c.request.required = true) : RefOk st c ⟨cid, .tx t, time⟩ := + ⟨fun t' ht => (by cases ht; exact ⟨hs, hc, hm⟩), fun _ ht => (by cases ht)⟩ + +/-- RefOk for a proof reference, from the amount and a binding proof. -/ +theorem RefOk.ofProof {st : St} {c : Challenge} {cid time : Nat} (ha : c.request.amount = 0) + (hp : ∃ p ∈ st.proofSigs, p.signer = p.account ∧ p.challengeId = c.id ∧ p.realm = c.realm ∧ + p.chainId = c.request.chainId ∧ p.version = 3) : RefOk st c ⟨cid, .challenge cid, time⟩ := + ⟨fun _ ht => (by cases ht), fun _ ht => (by cases ht; exact ⟨rfl, ha, hp⟩)⟩ + +/-- Time advancing preserves SysInv (it issues no receipt). -/ +theorem inv_tick {cfg : Cfg} {s s' : St} {d : Nat} + (hI : SysInv cfg s) (h : step cfg s (.tick d) = some s') : SysInv cfg s' := by + obtain ⟨h1, h2, h3, h4, h5, h6, h7, h8, h9⟩ := hI + simp only [step] at h + (repeat' split at h) <;> cases h <;> constructor <;> + first + | grind [RefOk, succeeded, upd_apply, chainOk, nonceFree, not_nonceFree_of_succeeded, + List.mem_cons_self, txOf_mem, RefOk.mono, Ref.txOf] + | -- receipts_ok with receipts unchanged: RefOk.mono + intro r hr + obtain ⟨hu, c, hc, hrc⟩ := h2 r hr + exact ⟨hu, c, hc, hrc.mono (by grind [succeeded]) (by grind) (by grind)⟩ + +/-- Funding an account preserves SysInv (it issues no receipt). -/ +theorem inv_fund {cfg : Cfg} {s s' : St} {tok acct amt : Nat} + (hI : SysInv cfg s) (h : step cfg s (.fund tok acct amt) = some s') : SysInv cfg s' := by + obtain ⟨h1, h2, h3, h4, h5, h6, h7, h8, h9⟩ := hI + simp only [step] at h + (repeat' split at h) <;> cases h <;> constructor <;> + first + | grind [RefOk, succeeded, upd_apply, chainOk, nonceFree, not_nonceFree_of_succeeded, + List.mem_cons_self, txOf_mem, RefOk.mono, Ref.txOf] + | -- receipts_ok with receipts unchanged: RefOk.mono + intro r hr + obtain ⟨hu, c, hc, hrc⟩ := h2 r hr + exact ⟨hu, c, hc, hrc.mono (by grind [succeeded]) (by grind) (by grind)⟩ + +/-- Signing a transaction preserves SysInv (it issues no receipt). -/ +theorem inv_signTx {cfg : Cfg} {s s' : St} {t : Tx} + (hI : SysInv cfg s) (h : step cfg s (.signTx t) = some s') : SysInv cfg s' := by + obtain ⟨h1, h2, h3, h4, h5, h6, h7, h8, h9⟩ := hI + simp only [step] at h + (repeat' split at h) <;> cases h <;> constructor <;> + first + | grind [RefOk, succeeded, upd_apply, chainOk, nonceFree, not_nonceFree_of_succeeded, + List.mem_cons_self, txOf_mem, RefOk.mono, Ref.txOf] + | -- receipts_ok with receipts unchanged: RefOk.mono + intro r hr + obtain ⟨hu, c, hc, hrc⟩ := h2 r hr + exact ⟨hu, c, hc, hrc.mono (by grind [succeeded]) (by grind) (by grind)⟩ + +/-- Signing a proof preserves SysInv (it issues no receipt). -/ +theorem inv_signProof {cfg : Cfg} {s s' : St} {p : ProofSig} + (hI : SysInv cfg s) (h : step cfg s (.signProof p) = some s') : SysInv cfg s' := by + obtain ⟨h1, h2, h3, h4, h5, h6, h7, h8, h9⟩ := hI + simp only [step] at h + (repeat' split at h) <;> cases h <;> constructor <;> + first + | grind [RefOk, succeeded, upd_apply, chainOk, nonceFree, not_nonceFree_of_succeeded, + List.mem_cons_self, txOf_mem, RefOk.mono, Ref.txOf] + | -- receipts_ok with receipts unchanged: RefOk.mono + intro r hr + obtain ⟨hu, c, hc, hrc⟩ := h2 r hr + exact ⟨hu, c, hc, hrc.mono (by grind [succeeded]) (by grind) (by grind)⟩ + +/-- A client broadcast preserves SysInv (it issues no receipt). -/ +theorem inv_broadcast {cfg : Cfg} {s s' : St} {t : Tx} + (hI : SysInv cfg s) (h : step cfg s (.broadcast t) = some s') : SysInv cfg s' := by + obtain ⟨h1, h2, h3, h4, h5, h6, h7, h8, h9⟩ := hI + simp only [step] at h + (repeat' split at h) <;> cases h <;> constructor <;> + first + | grind [RefOk, succeeded, upd_apply, chainOk, nonceFree, not_nonceFree_of_succeeded, + List.mem_cons_self, txOf_mem, RefOk.mono, Ref.txOf] + | -- receipts_ok with receipts unchanged: RefOk.mono + intro r hr + obtain ⟨hu, c, hc, hrc⟩ := h2 r hr + exact ⟨hu, c, hc, hrc.mono (by grind [succeeded]) (by grind) (by grind)⟩ + +/-- Issuing a challenge preserves SysInv (it issues no receipt). -/ +theorem inv_issue {cfg : Cfg} {s s' : St} {c : Challenge} + (hI : SysInv cfg s) (h : step cfg s (.issue c) = some s') : SysInv cfg s' := by + obtain ⟨h1, h2, h3, h4, h5, h6, h7, h8, h9⟩ := hI + simp only [step] at h + (repeat' split at h) <;> cases h <;> constructor <;> + first + | grind [RefOk, succeeded, upd_apply, chainOk, nonceFree, not_nonceFree_of_succeeded, + List.mem_cons_self, txOf_mem, RefOk.mono, Ref.txOf] + | -- receipts_ok with receipts unchanged: RefOk.mono + intro r hr + obtain ⟨hu, c, hc, hrc⟩ := h2 r hr + exact ⟨hu, c, hc, hrc.mono (by grind [succeeded]) (by grind) (by grind)⟩ + +/-- A pull broadcast (Act.submit with a transaction) preserves SysInv: it issues no receipt and + leaves a pending settlement whose facts come from its checks. -/ +theorem inv_pull {cfg : Cfg} (hg : cfg.Guarded) {s s' : St} {cr : Cred} {t : Tx} + (hI : SysInv cfg s) (hp : cr.payload = .transaction t) (h : step cfg s (.submit cr) = some s') : + SysInv cfg s' := by + obtain ⟨h1, h2, h3, h4, h5, h6, h7, h8, h9⟩ := hI + simp only [step, hp, hg.txSingleUse, ↓reduceIte] at h + (repeat' split at h) <;> cases h <;> simp only [sponsorFor] <;> constructor <;> + grind [RefOk, succeeded, upd_apply, chainOk, nonceFree, not_nonceFree_of_succeeded, + List.mem_cons_self, txOf_mem, RefOk.mono, Ref.txOf, hg.splitsOneToOne, Pays] + +/-- Settling a pending pull credential preserves SysInv: the receipt's facts are the pending + entry's (G2 makes its transaction a successful one). -/ +theorem inv_settlePull {cfg : Cfg} (hg : cfg.Guarded) {s s' : St} {cid : Nat} + (hI : SysInv cfg s) (h : step cfg s (.settlePull cid) = some s') : SysInv cfg s' := by + obtain ⟨h1, h2, h3, h4, h5, h6, h7, h8, h9⟩ := hI + simp only [step, hg.txSingleUse, hg.pullNeedsSuccess, ↓reduceIte] at h + (repeat' split at h) <;> cases h <;> constructor <;> + first + | grind [RefOk, succeeded, upd_apply, txOf_mem, RefOk.mono, Ref.txOf, List.mem_cons_self] + | -- receipts_ok: the new receipt's facts are the pending entry's, old receipts keep theirs + intro r hr + simp only [List.mem_cons] at hr + rcases hr with rfl | hr + · obtain ⟨-, ⟨c, hc, hm⟩, ⟨i, hi, hit, hio⟩, hct, -⟩ := h8 _ _ _ ‹s.pending _ = some _› + have hok : i.ok = true := by grind + refine ⟨by grind [upd_apply], c, hc, RefOk.ofTx ?_ hct hm⟩ + simp only [succeeded, List.any_eq_true, Bool.and_eq_true, beq_iff_eq] + exact ⟨i, hi, hit, hok⟩ + · obtain ⟨hu, c, hc, hrc⟩ := h2 r hr + refine ⟨by grind [upd_apply], c, hc, hrc.mono ?_ ?_ ?_⟩ <;> grind [succeeded] + +/-- A hash credential preserves SysInv: an old receipt keeps its facts (RefOk.mono), the new + one is built from the branch's checks (RefOk.ofTx); G1 keeps its transaction fresh. -/ +theorem inv_hash {cfg : Cfg} (hg : cfg.Guarded) {s s' : St} {cr : Cred} {t : Tx} + (hI : SysInv cfg s) (hp : cr.payload = .hash t) (h : step cfg s (.submit cr) = some s') : + SysInv cfg s' := by + obtain ⟨h1, h2, h3, h4, h5, h6, h7, h8, h9⟩ := hI + simp only [step, hp] at h + (repeat' split at h) <;> cases h <;> simp only [settleTx] <;> constructor <;> + first + | grind [RefOk, succeeded, upd_apply, txOf_mem, RefOk.mono, Ref.txOf, hg.txSingleUse, + hg.splitsOneToOne, Pays] + | intro r hr + simp only [List.mem_cons] at hr + rcases hr with rfl | hr + · obtain ⟨hiss, -, -⟩ := ‹s.issued _ = some _ ∧ _› + refine ⟨by grind [upd_apply], _, hiss, ?_⟩ + exact RefOk.ofTx (by grind [succeeded]) (by grind) (by grind [Pays, hg.splitsOneToOne]) + · obtain ⟨hu, c, hc, hrc⟩ := h2 r hr + refine ⟨by grind [upd_apply], c, hc, hrc.mono ?_ ?_ ?_⟩ <;> grind [succeeded] + +/-- A proof credential preserves SysInv: the new receipt is built from the branch's checks + (RefOk.ofProof); G3 makes the request free. -/ +theorem inv_proof {cfg : Cfg} (hg : cfg.Guarded) {s s' : St} {cr : Cred} {p : ProofSig} + (hI : SysInv cfg s) (hp : cr.payload = .proof p) (h : step cfg s (.submit cr) = some s') : + SysInv cfg s' := by + obtain ⟨h1, h2, h3, h4, h5, h6, h7, h8, h9⟩ := hI + simp only [step, hp] at h + (repeat' split at h) <;> cases h <;> constructor <;> + first + | grind [RefOk, succeeded, upd_apply, txOf_mem, RefOk.mono, Ref.txOf, hg.proofOnlyZero] + | intro r hr + simp only [List.mem_cons] at hr + rcases hr with rfl | hr + · obtain ⟨hiss, -, -⟩ := ‹s.issued _ = some _ ∧ _› + refine ⟨by grind [upd_apply], _, hiss, ?_⟩ + exact RefOk.ofProof (by grind [hg.proofOnlyZero]) (by grind) + · obtain ⟨hu, c, hc, hrc⟩ := h2 r hr + refine ⟨by grind [upd_apply], c, hc, hrc.mono ?_ ?_ ?_⟩ <;> grind [succeeded] + +/-- Inductive step: with every guard on, every successful step preserves SysInv. -/ +theorem inv_step {cfg : Cfg} (hg : cfg.Guarded) {s s' : St} {a : Act} + (hI : SysInv cfg s) (h : step cfg s a = some s') : SysInv cfg s' := by + cases a with + | tick => exact inv_tick hI h + | fund => exact inv_fund hI h + | signTx => exact inv_signTx hI h + | signProof => exact inv_signProof hI h + | broadcast => exact inv_broadcast hI h + | issue => exact inv_issue hI h + | settlePull => exact inv_settlePull hg hI h + | submit cr => + cases hp : cr.payload with + | transaction t => exact inv_pull hg hI hp h + | hash t => exact inv_hash hg hI hp h + | proof p => exact inv_proof hg hI hp h + +/-- Every reachable state satisfies SysInv (every guard on). -/ +theorem reachable_inv {cfg : Cfg} (hg : cfg.Guarded) {s : St} (h : Reachable cfg s) : + SysInv cfg s := by + induction h with + | init => exact inv_init cfg + | step a _ hs ih => exact inv_step hg ih hs + +end TempoCharge diff --git a/formal/tempo-charge/TempoCharge/Model.lean b/formal/tempo-charge/TempoCharge/Model.lean new file mode 100644 index 00000000..2ad4e0c4 --- /dev/null +++ b/formal/tempo-charge/TempoCharge/Model.lean @@ -0,0 +1,376 @@ +import MppCore +/- + Tempo charge payment method (draft-tempo-charge-00): one server, its challenges and + credentials, and the Tempo chain the payments land on. Section names (§) refer to + specs/methods/tempo/draft-tempo-charge-00.md; "core" is draft-httpauth-payment-01 and + "intent" is draft-payment-intent-charge-00. + + Abstractions + * Hashes are injective: a transaction *is* its hash, and the challenge binding (core + §Challenge Binding, HMAC or a lookup) is modelled as equality between the echoed challenge + and the one issued under its id. + * Signatures are unforgeable: St.signed holds exactly the transactions their senders signed, + St.proofSigs the EIP-712 proofs their signers signed; only Act.signTx / Act.signProof add. + * The chain: one chain (Cfg.chainId), TIP-20 balances per token and account, 2D nonces as one + (sender, nonce) pair, validBefore, and atomic execution (all transfers or none). A reverted + transaction is still included and consumes its nonce (fees are paid). Finality is immediate. + * A transaction's calls are its transfer / transferWithMemo calls; their Transfer events are + the calls themselves when it succeeds. Other call shapes (swaps, smart wallets) are omitted. + * Server handling of a pull credential takes two steps: Act.submit verifies it and + broadcasts the transaction (eth_sendRawTxSync, so it is on chain when the step ends) and + leaves the settlement pending (St.pending); Act.settlePull later settles and delivers. + Other credentials interleave between the two, since core §Concurrent Request Handling only + serializes identical credentials. Hash and proof credentials verify, settle and deliver in + one step. A receipt in St.receipts stands for "200 + Payment-Receipt + resource + delivered". + * Access-key proof signers (§Proof Verification step 5), ERC-1271, fee token choice and fee + amounts, Idempotency-Key replays, digest/opaque/header parameters are not modelled. + + Rules the draft leaves out are Cfg flags (all on in Cfg.Guarded); Counterexamples.lean breaks + a property with each one off, Witnesses.lean shows legitimate flows succeed with all on. +-/ +namespace TempoCharge + +export MppCore (upd upd_same upd_other upd_apply) + +/-- One TIP-20 transfer call, or the Transfer / TransferWithMemo event it emits. + The sender is the transaction's sender. memo = none is transfer, some m transferWithMemo. -/ +structure Transfer where + token : Nat + dst : Nat + amount : Nat + memo : Option Nat := none +deriving DecidableEq, Repr + +/-- A Tempo Transaction (type 0x76, §Terminology), as far as the charge rules read it. + * sponsor: signed with the fee_payer_signature placeholder (feePayer: true, §Fee Payment), + so it needs a fee payer's 0x78 signature before the chain accepts it. -/ +structure Tx where + sender : Nat + chainId : Nat + nonce : Nat + validBefore : Option Nat := none + calls : List Transfer + sponsor : Bool := false +deriving DecidableEq, Repr + +/-- One methodDetails.splits entry (§Split Payments). -/ +structure Split where + recipient : Nat + amount : Nat + memo : Option Nat := none +deriving DecidableEq, Repr + +/-- The charge request (§Request Schema). splits = [] means absent; pull / push say which + non-zero modes supportedModes allows (both when omitted). -/ +structure Request where + amount : Nat + currency : Nat + recipient : Nat + chainId : Nat + memo : Option Nat := none + splits : List Split := [] + feePayer : Bool := false + pull : Bool := true + push : Bool := true +deriving DecidableEq, Repr + +/-- A challenge as issued (core §WWW-Authenticate): id, realm, request, expires. + * client: ghost, who asked for it (no protocol field; used only to state Gap 5). -/ +structure Challenge where + id : Nat + realm : Nat + request : Request + expires : Nat + client : Nat := 0 +deriving DecidableEq, Repr + +/-- EIP-712 Proof message with its domain (§Proof Payload) and who signed it. -/ +structure ProofSig where + signer : Nat + account : Nat + challengeId : Nat + realm : Nat + chainId : Nat + version : Nat +deriving DecidableEq, Repr + +/-- Credential payloads (§Credential Schema): pull, push and zero-amount proof. -/ +inductive Payload where + | transaction (t : Tx) + | hash (t : Tx) + | proof (p : ProofSig) +deriving DecidableEq, Repr + +/-- A credential: the echoed challenge, the payload and source as (chainId, address). -/ +structure Cred where + echo : Challenge + payload : Payload + source : Option (Nat × Nat) := none +deriving DecidableEq, Repr + +/-- A receipt's reference (§Receipt Generation, §Proof Receipt): a transaction hash or, for a + proof, the challenge id. -/ +inductive Ref where + | tx (t : Tx) + | challenge (id : Nat) +deriving DecidableEq, Repr + +/-- The transaction a reference names, if any. -/ +def Ref.txOf : Ref → Option Tx + | .tx t => some t + | .challenge _ => none + +/-- A Payment-Receipt with status "success" for challenge cid, issued at time `time`. -/ +structure Receipt where + cid : Nat + ref : Ref + time : Nat +deriving DecidableEq, Repr + +/-- A transaction included on chain: ok is the receipt status, time the block time. -/ +structure Incl where + tx : Tx + ok : Bool + time : Nat +deriving DecidableEq, Repr + +/-- The server and chain configuration and the guard flags (default on). -/ +structure Cfg where + /-- this server's realm -/ + realm : Nat + /-- the Tempo chain the server settles on -/ + chainId : Nat + /-- G1: the server records a pull transaction when it broadcasts it, before settlement, and + a hash transaction when it settles it, and rejects a hash credential naming any recorded + transaction (§Hash Verification is silent). Recording a pull transaction only at + settlement leaves a window, after broadcast, in which a hash credential for another + challenge can claim it. With the guard off the server records at settlement and refuses + nothing. -/ + txSingleUse : Bool := true + /-- G2: a pull credential settles only when the broadcast transaction succeeded + (§Settlement Procedure says so only for hash credentials). -/ + pullNeedsSuccess : Bool := true + /-- G3: a proof credential is accepted only for amount "0" (§Proof Verification has no + amount check; only clients are told not to use it otherwise). -/ + proofOnlyZero : Bool := true + /-- G4: each required transfer (primary and every split) is matched by a distinct transfer + (§Ordering, §Transaction Verification step 6 don't say one-to-one). -/ + splitsOneToOne : Bool := true +deriving Repr + +/-- The guarded reading: every flag on. -/ +structure Cfg.Guarded (cfg : Cfg) : Prop where + txSingleUse : cfg.txSingleUse = true + pullNeedsSuccess : cfg.pullNeedsSuccess = true + proofOnlyZero : cfg.proofOnlyZero = true + splitsOneToOne : cfg.splitsOneToOne = true + +/-- Sum of the split amounts. -/ +def sumSplits : List Split → Nat + | [] => 0 + | s :: ss => s.amount + sumSplits ss + +/-- A request the server may issue (§Split Payments Constraints, §Submission Modes): on the + server's chain, at least one mode, and splits absent or each > 0 with sum < amount. -/ +def Request.valid (r : Request) (chain : Nat) : Bool := + r.chainId == chain && (r.pull || r.push) && + (r.splits.isEmpty || (r.splits.all (fun s => decide (0 < s.amount)) && + decide (sumSplits r.splits < r.amount))) + +/-- The transfers a request requires (§Split Payments Client Behavior): the primary recipient + gets amount - sum(splits) with the top-level memo, each split recipient its amount and memo, + all in currency. -/ +def Request.required (r : Request) : List Transfer := + { token := r.currency, dst := r.recipient, amount := r.amount - sumSplits r.splits, memo := r.memo } :: + r.splits.map fun s => { token := r.currency, dst := s.recipient, amount := s.amount, memo := s.memo } + +/-- Transfer c satisfies required transfer r (§Transaction Verification steps 2-6): same token, + recipient and amount, and the memo when one is required. -/ +def fits (r c : Transfer) : Bool := + c.token == r.token && c.dst == r.dst && c.amount == r.amount && (r.memo.isNone || c.memo == r.memo) + +/-- Every way to remove one transfer that fits r (empty when none does). -/ +def takeAll (r : Transfer) : List Transfer → List (List Transfer) + | [] => [] + | c :: cs => (if fits r c then [cs] else []) ++ (takeAll r cs).map (c :: ·) + +/-- One-to-one matching: some assignment gives every required transfer its own distinct + transfer, whatever the order of the calls (§Ordering). -/ +def matchOne : List Transfer → List Transfer → Bool + | _, [] => true + | calls, r :: rs => (takeAll r calls).any fun rest => matchOne rest rs + +/-- The payment check of §Transaction Verification / §Hash Verification. With G4 off it is the + literal "each required effect is present", which one transfer can satisfy twice. -/ +def Pays (cfg : Cfg) (r : Request) (calls : List Transfer) : Bool := + if cfg.splitsOneToOne then matchOne calls r.required + else r.required.all fun q => calls.any (fits q) + +/-- One TIP-20 transfer of amt of token tok from src to dst (caller checks the balance). -/ +def move (bal : Nat → Nat → Nat) (tok src dst amt : Nat) : Nat → Nat → Nat := + fun t a => if t = tok then (if a = src then bal t a - amt else bal t a) + (if a = dst then amt else 0) + else bal t a + +/-- Execute a transaction's transfers atomically; none (revert) if any lacks balance. -/ +def exec (bal : Nat → Nat → Nat) (sender : Nat) : List Transfer → Option (Nat → Nat → Nat) + | [] => some bal + | c :: cs => if c.amount ≤ bal c.token sender then exec (move bal c.token sender c.dst c.amount) sender cs + else none + +/-- Global state: chain, signatures and server records. -/ +structure St where + /-- block time -/ + now : Nat + /-- TIP-20 balances: token → account → amount -/ + bal : Nat → Nat → Nat + /-- transactions their senders signed -/ + signed : List Tx + /-- proofs their signers signed -/ + proofSigs : List ProofSig + /-- transactions on chain, newest first -/ + included : List Incl + /-- server: challenges issued, by id -/ + issued : Nat → Option Challenge + /-- server: challenge ids already used (core §Replay Protection) -/ + used : Nat → Bool + /-- server: receipts issued (and resources delivered), newest first -/ + receipts : List Receipt + /-- server: transactions recorded as spent (used by G1): broadcast pull transactions (G1) or + settled ones -/ + consumedTx : List Tx + /-- server: pull settlements broadcast but not yet settled, by challenge id: the transaction + and whether it succeeded -/ + pending : Nat → Option (Tx × Bool) + /-- ghost: challenge ids whose transaction fees the server paid -/ + sponsored : List Nat + +/-- Empty chain and server at time 1. -/ +def St.init : St := + ⟨1, fun _ _ => 0, [], [], [], fun _ => none, fun _ => false, [], [], fun _ => none, []⟩ + +/-- No included transaction used t's (sender, nonce) (2D nonce consumption). -/ +def nonceFree (st : St) (t : Tx) : Bool := + !st.included.any fun i => i.tx.sender == t.sender && i.tx.nonce == t.nonce + +/-- The chain accepts t now: right chain, nonce unused, before validBefore. -/ +def chainOk (cfg : Cfg) (st : St) (t : Tx) : Bool := + t.chainId == cfg.chainId && nonceFree st t && (t.validBefore.all fun vb => decide (st.now < vb)) + +/-- t was included and succeeded (§Hash Verification: receipt indicates success). -/ +def succeeded (st : St) (t : Tx) : Bool := + st.included.any fun i => i.tx == t && i.ok + +/-- Record a hash settlement: mark the challenge used, issue the receipt, remember the + transaction. -/ +def settleTx (st : St) (cid : Nat) (t : Tx) : St := + { st with used := upd st.used cid true, receipts := ⟨cid, .tx t, st.now⟩ :: st.receipts, + consumedTx := t :: st.consumedTx } + +/-- The server pays fees for challenge cid when its request says feePayer (§Server-Paid Fees). -/ +def sponsorFor (st : St) (r : Request) (cid : Nat) : List Nat := + if r.feePayer then cid :: st.sponsored else st.sponsored + +/-- Every action. -/ +inductive Act where + /-- block time advances -/ + | tick (d : Nat) + /-- tokens arrive at an account (outside the model) -/ + | fund (tok acct amt : Nat) + /-- t.sender signs t -/ + | signTx (t : Tx) + /-- p.signer signs a proof -/ + | signProof (p : ProofSig) + /-- anyone broadcasts a signed transaction paying its own fees (push mode, §Hash Settlement) -/ + | broadcast (t : Tx) + /-- the server issues a challenge (402) -/ + | issue (c : Challenge) + /-- the server receives a credential -/ + | submit (cr : Cred) + /-- the server settles the pull credential it broadcast for challenge cid -/ + | settlePull (cid : Nat) +deriving Repr + +/-- The protocol as a computable transition function; none = reverted or rejected. -/ +def step (cfg : Cfg) (st : St) : Act → Option St + | .tick d => some { st with now := st.now + d } + | .fund tok acct amt => some { st with bal := fun t a => if t = tok ∧ a = acct then st.bal t a + amt else st.bal t a } + | .signTx t => some { st with signed := t :: st.signed } + | .signProof p => some { st with proofSigs := p :: st.proofSigs } + -- the client pays its own fees (sponsor = false); a revert still consumes the nonce + | .broadcast t => + if t ∈ st.signed ∧ chainOk cfg st t = true ∧ t.sponsor = false then + match exec st.bal t.sender t.calls with + | some b => some { st with bal := b, included := ⟨t, true, st.now⟩ :: st.included } + | none => some { st with included := ⟨t, false, st.now⟩ :: st.included } + else none + -- a fresh id, this realm, a valid request (§Split Payments Constraints: servers MUST NOT + -- generate a request whose splits sum to amount or more) + | .issue c => + if st.issued c.id = none ∧ c.realm = cfg.realm ∧ c.request.valid cfg.chainId = true then + some { st with issued := upd st.issued c.id (some c) } + else none + -- intent §Server Responsibilities: an outstanding (issued, unused, not pending) challenge + -- whose echo matches the binding (core §Challenge Binding), not expired; then the method's + -- checks + | .submit cr => + if st.issued cr.echo.id = some cr.echo ∧ st.used cr.echo.id = false ∧ st.pending cr.echo.id = none ∧ + st.now < cr.echo.expires then + match cr.payload with + -- §Transaction Verification steps 2-7 (the fee payer placeholder exactly when feePayer, + -- §Client Requirements), then broadcast (adding the fee payer signature + -- when feePayer, §Server-Paid Fees); settlement is left pending (Act.settlePull). G1 + -- records the transaction now. + | .transaction t => + if cr.echo.request.pull = true ∧ t ∈ st.signed ∧ Pays cfg cr.echo.request t.calls = true ∧ + chainOk cfg st t = true ∧ t.sponsor = cr.echo.request.feePayer then + match exec st.bal t.sender t.calls with + | some b => some { st with bal := b, included := ⟨t, true, st.now⟩ :: st.included, + sponsored := sponsorFor st cr.echo.request cr.echo.id, + pending := upd st.pending cr.echo.id (some (t, true)), + consumedTx := if cfg.txSingleUse then t :: st.consumedTx else st.consumedTx } + | none => some { st with included := ⟨t, false, st.now⟩ :: st.included, + sponsored := sponsorFor st cr.echo.request cr.echo.id, + pending := upd st.pending cr.echo.id (some (t, false)), + consumedTx := if cfg.txSingleUse then t :: st.consumedTx else st.consumedTx } + else none + -- §Hash Settlement Limitations (no feePayer, push allowed), §Hash Verification + -- (successful receipt, matching Transfer events); G1 refuses an already settled hash + | .hash t => + if cr.echo.request.push = true ∧ cr.echo.request.feePayer = false ∧ succeeded st t = true ∧ + Pays cfg cr.echo.request t.calls = true ∧ (cfg.txSingleUse = true → t ∉ st.consumedTx) then + some (settleTx st cr.echo.id t) + else none + -- §Proof Verification steps 1-4 with domain version "3"; G3 asks for amount 0 + | .proof p => + match cr.source with + | none => none + | some (ch, acct) => + if ch = cr.echo.request.chainId ∧ p ∈ st.proofSigs ∧ p.signer = acct ∧ p.account = acct ∧ + p.challengeId = cr.echo.id ∧ p.realm = cr.echo.realm ∧ p.chainId = cr.echo.request.chainId ∧ + p.version = 3 ∧ (cfg.proofOnlyZero = true → cr.echo.request.amount = 0) then + some { st with used := upd st.used cr.echo.id true, + receipts := ⟨cr.echo.id, .challenge cr.echo.id, st.now⟩ :: st.receipts } + else none + else none + -- §Settlement Procedure: settle a pending pull credential and deliver; G2 asks for success + -- first (otherwise the challenge reopens without a receipt). Without G1 the transaction is + -- recorded only now. + | .settlePull cid => + match st.pending cid with + | none => none + | some (t, ok) => + if ok = true ∨ cfg.pullNeedsSuccess = false then + some { st with pending := upd st.pending cid none, used := upd st.used cid true, + receipts := ⟨cid, .tx t, st.now⟩ :: st.receipts, + consumedTx := if cfg.txSingleUse then st.consumedTx else t :: st.consumedTx } + else some { st with pending := upd st.pending cid none } + +/-- Run a list of actions; none if any step fails. -/ +abbrev run (cfg : Cfg) : St → List Act → Option St := MppCore.run (step cfg) + +/-- States reachable from St.init. -/ +abbrev Reachable (cfg : Cfg) : St → Prop := MppCore.Reachable (step cfg) St.init + +end TempoCharge + diff --git a/formal/tempo-charge/TempoCharge/Properties.lean b/formal/tempo-charge/TempoCharge/Properties.lean new file mode 100644 index 00000000..0d6c25c5 --- /dev/null +++ b/formal/tempo-charge/TempoCharge/Properties.lean @@ -0,0 +1,238 @@ +import TempoCharge.Model +import TempoCharge.Invariant +/- + Properties P1-P9; README.md lists each with its theorems. State properties hold in every + reachable state with every guard on (Cfg.Guarded) and are read off SysInv (Invariant.lean). + One-step theorems that only read a rule back (P4 replay/expiry/binding, P6 hash with + feePayer, P8, P9) are sanity checks that step encodes the rule as the draft states it. +-/ +namespace TempoCharge + +variable {cfg : Cfg} {s s' : St} + +/-! ## Arithmetic: a one-to-one match transfers at least the requested amount -/ + +/-- Total of a list of transfers in token tok. -/ +def sumOn (tok : Nat) : List Transfer → Nat + | [] => 0 + | c :: cs => (if c.token = tok then c.amount else 0) + sumOn tok cs + +/-- Total amount of a list of transfers, whatever the token. -/ +def sumAll : List Transfer → Nat + | [] => 0 + | c :: cs => c.amount + sumAll cs + +/-- Taking out a fitting transfer removes exactly r.amount from the total in r.token. -/ +theorem takeAll_sum (r : Transfer) : ∀ (l l' : List Transfer), l' ∈ takeAll r l → + sumOn r.token l = r.amount + sumOn r.token l' + | [], _, h => by simp [takeAll] at h + | c :: cs, l', h => by + simp only [takeAll, List.mem_append, List.mem_map] at h + rcases h with h | ⟨l'', h', rfl⟩ + · split at h + · simp only [List.mem_singleton] at h + subst h + rename_i hf + simp only [fits, Bool.and_eq_true, beq_iff_eq] at hf + simp [sumOn, hf] + · simp at h + · have := takeAll_sum r cs l'' h' + simp only [sumOn] + omega + +/-- If every required transfer is in token tok and they match one-to-one, the calls move at + least their total in tok. -/ +theorem matchOne_sum (tok : Nat) : ∀ (rs calls : List Transfer), (∀ r ∈ rs, r.token = tok) → + matchOne calls rs = true → sumAll rs ≤ sumOn tok calls + | [], _, _, _ => by simp [sumAll] + | r :: rs, calls, ht, h => by + simp only [matchOne, List.any_eq_true] at h + obtain ⟨rest, hrest, h⟩ := h + have hr : r.token = tok := ht r (by simp) + have h1 := takeAll_sum r calls rest hrest + have h2 := matchOne_sum tok rs rest (fun q hq => ht q (by simp [hq])) h + rw [hr] at h1 + simp only [sumAll] + omega + +/-- The split transfers total sumSplits. -/ +theorem sumAll_splits (cur : Nat) : ∀ ss : List Split, + sumAll (ss.map fun s => ({ token := cur, dst := s.recipient, amount := s.amount, memo := s.memo } : Transfer)) = + sumSplits ss + | [] => rfl + | s :: ss => by simp [sumAll, sumSplits, sumAll_splits cur ss] + +/-- A valid request's required transfers total exactly amount, all in currency. -/ +theorem required_total (r : Request) (chain : Nat) (hv : r.valid chain = true) : + sumAll r.required = r.amount ∧ ∀ q ∈ r.required, q.token = r.currency := by + constructor + · simp only [Request.required, sumAll, sumAll_splits] + simp only [Request.valid, Bool.and_eq_true, Bool.or_eq_true, List.isEmpty_iff, + List.all_eq_true, decide_eq_true_eq] at hv + rcases hv.2 with h | h + · simp [h, sumSplits] + · omega + · intro q hq + simp only [Request.required, List.mem_cons, List.mem_map] at hq + rcases hq with rfl | ⟨_, _, rfl⟩ <;> rfl + +/-- One-to-one matching against a valid request transfers at least amount in currency. -/ +theorem matchOne_amount {r : Request} {chain : Nat} {calls : List Transfer} + (hv : r.valid chain = true) (hm : matchOne calls r.required = true) : + r.amount ≤ sumOn r.currency calls := by + obtain ⟨h1, h2⟩ := required_total r chain hv + have := matchOne_sum r.currency r.required calls h2 hm + omega + +/-! ## P1 — a receipt means the challenge it names was paid -/ + +/-- P1: every receipt names an issued challenge of this realm, and + * a transaction reference: that transaction is on chain, succeeded, matches the request's + transfers one-to-one and so moved at least amount of currency; + * a proof reference: the request was free (amount 0) and a version 3 proof signed by its + account binds this challenge id, realm and chain. + * Why it matters: core §Receipt Status Semantics and intent §Atomicity: a receipt (and the + resource) only follows a verified payment for that very challenge. + * Rests on G2 (pull success), G3 (proof only for 0) and G4 (one-to-one). -/ +theorem P1_receipt_paid (hg : cfg.Guarded) (hr : Reachable cfg s) {r : Receipt} + (hrm : r ∈ s.receipts) : + ∃ c, s.issued r.cid = some c ∧ c.id = r.cid ∧ c.realm = cfg.realm ∧ + (∀ t, r.ref = .tx t → succeeded s t = true ∧ matchOne t.calls c.request.required = true ∧ + c.request.amount ≤ sumOn c.request.currency t.calls) ∧ + (∀ id, r.ref = .challenge id → id = r.cid ∧ c.request.amount = 0 ∧ + ∃ p ∈ s.proofSigs, p.signer = p.account ∧ p.challengeId = c.id ∧ p.realm = c.realm ∧ + p.chainId = c.request.chainId ∧ p.version = 3) := by + have hi := reachable_inv hg hr + obtain ⟨_, c, hc, htx, hpf⟩ := hi.receipts_ok r hrm + obtain ⟨hid, hrealm, hv⟩ := hi.issued_ok _ c hc + refine ⟨c, hc, hid, hrealm, fun t ht => ?_, hpf⟩ + obtain ⟨a, _, m⟩ := htx t ht + exact ⟨a, m, matchOne_amount hv m⟩ + +/-! ## P2 / P3 — single use: one receipt per challenge, one challenge per transaction -/ + +/-- P2: no challenge gets two receipts (intent §Single-Use, core §Replay Protection, + §Concurrent Request Handling: at most one settlement and one delivery). -/ +theorem P2_one_receipt_per_challenge (hg : cfg.Guarded) (hr : Reachable cfg s) : + (s.receipts.map Receipt.cid).Nodup := + (reachable_inv hg hr).cids_nodup + +/-- P3: no transaction settles two challenges, across pull and push (no double counting of one + payment; rests on G1). -/ +theorem P3_one_challenge_per_tx (hg : cfg.Guarded) (hr : Reachable cfg s) : + (s.receipts.filterMap fun r => r.ref.txOf).Nodup := + (reachable_inv hg hr).txs_nodup + +/-! ## P4 — a receipt answers an outstanding, matching, unexpired challenge -/ + +/-- P4: a step that issues a receipt either is the submission of a hash or proof credential + whose echoed challenge is the one issued under its id (core §Challenge Binding), unused and + not expired (intent §Server Responsibilities steps 1-2), or settles the pull credential + pending for that challenge (P4_pending_answers_challenge says when that one was accepted); + the receipt names that challenge. No other action issues a receipt (core §Idempotency and + Side Effects), and old receipts stay. -/ +theorem P4_receipt_answers_challenge {a : Act} (h : step cfg s a = some s') {r : Receipt} + (hnew : r ∈ s'.receipts) (hold : r ∉ s.receipts) : + (∃ cr, a = .submit cr ∧ r.cid = cr.echo.id ∧ s.issued cr.echo.id = some cr.echo ∧ + s.used cr.echo.id = false ∧ s.now < cr.echo.expires) ∨ + (a = .settlePull r.cid ∧ ∃ t ok, s.pending r.cid = some (t, ok)) := by + cases a <;> simp only [step] at h <;> (repeat' split at h) <;> cases h <;> + simp only [settleTx, List.mem_cons] at hnew <;> grind + +/-- P4: a step that leaves a pull settlement pending is the submission of a credential whose + echoed challenge is the one issued under its id, unused, not pending and not expired. -/ +theorem P4_pending_answers_challenge {a : Act} (h : step cfg s a = some s') {cid : Nat} + {e : Tx × Bool} (hnew : s'.pending cid = some e) (hold : s.pending cid = none) : + ∃ cr, a = .submit cr ∧ cid = cr.echo.id ∧ s.issued cr.echo.id = some cr.echo ∧ + s.used cr.echo.id = false ∧ s.now < cr.echo.expires := by + cases a <;> simp only [step] at h <;> (repeat' split at h) <;> cases h <;> + simp only [settleTx] at hnew <;> grind [upd_apply] + +/-- P4 (sanity): a credential for a used challenge is rejected (replay). -/ +theorem P4_replay_rejected {cr : Cred} (hu : s.used cr.echo.id = true) : + step cfg s (.submit cr) = none := by + simp [step, hu] + +/-- P4 (sanity): a credential for an expired challenge is rejected. -/ +theorem P4_expired_rejected {cr : Cred} (he : cr.echo.expires ≤ s.now) : + step cfg s (.submit cr) = none := by + simp only [step] + grind + +/-- P4 (sanity): a credential whose echoed challenge differs from the one issued under its id + (another amount, recipient, realm, expiry) is rejected. -/ +theorem P4_unbound_rejected {cr : Cred} (hb : s.issued cr.echo.id ≠ some cr.echo) : + step cfg s (.submit cr) = none := by + simp only [step] + grind + +/-! ## P5 — receipts and used challenges are permanent -/ + +/-- P5: a step never removes a receipt and never frees a used challenge. -/ +theorem P5_monotone {a : Act} (h : step cfg s a = some s') : + (∀ r ∈ s.receipts, r ∈ s'.receipts) ∧ (∀ id, s.used id = true → s'.used id = true) := by + cases a <;> simp only [step] at h <;> (repeat' split at h) <;> cases h <;> + simp only [settleTx] <;> grind [upd_apply] + +/-! ## P6 — the server pays fees only where it offered to -/ + +/-- P6: every challenge whose fees the server paid offered feePayer: true (§Fee Payment). -/ +theorem P6_sponsor_only_feePayer (hg : cfg.Guarded) (hr : Reachable cfg s) {id : Nat} + (hs : id ∈ s.sponsored) : ∃ c, s.issued id = some c ∧ c.request.feePayer = true := + (reachable_inv hg hr).sponsored_ok id hs + +/-- P6 (sanity): a hash credential for a feePayer challenge is rejected (§Hash Settlement). -/ +theorem P6_hash_feePayer_rejected {cr : Cred} {t : Tx} (hp : cr.payload = .hash t) + (hf : cr.echo.request.feePayer = true) : step cfg s (.submit cr) = none := by + simp only [step, hp] + grind + +/-! ## P7 — validBefore bounds when a signed transaction can land -/ + +/-- P7: every included transaction landed before its validBefore. -/ +theorem P7_included_before_validBefore (hg : cfg.Guarded) (hr : Reachable cfg s) {i : Incl} + (hi : i ∈ s.included) {vb : Nat} (hv : i.tx.validBefore = some vb) : i.time < vb := + (reachable_inv hg hr).validBefore_ok i hi vb hv + +/-- P7: a client that follows §Method Details (validBefore no later than expires) is never + charged by that transaction after the challenge expired. -/ +theorem P7_no_charge_after_expiry (hg : cfg.Guarded) (hr : Reachable cfg s) {i : Incl} + (hi : i ∈ s.included) {c : Challenge} {vb : Nat} (hv : i.tx.validBefore = some vb) + (hle : vb ≤ c.expires) : i.time < c.expires := by + have := P7_included_before_validBefore hg hr hi hv + omega + +/-! ## P8 — proof credentials (§Proof Verification) -/ + +/-- P8 (sanity): a proof without source is rejected (step 1). -/ +theorem P8_proof_needs_source {cr : Cred} {p : ProofSig} (hp : cr.payload = .proof p) + (hs : cr.source = none) : step cfg s (.submit cr) = none := by + simp only [step, hp, hs] + grind + +/-- P8 (sanity): a proof for another challenge id, realm or chain, by another signer, or under + domain version "1" or "2" is rejected (steps 2-4). -/ +theorem P8_proof_binding {cr : Cred} {p : ProofSig} {ch acct : Nat} (hp : cr.payload = .proof p) + (hs : cr.source = some (ch, acct)) + (hbad : p.challengeId ≠ cr.echo.id ∨ p.realm ≠ cr.echo.realm ∨ + p.chainId ≠ cr.echo.request.chainId ∨ ch ≠ cr.echo.request.chainId ∨ p.signer ≠ acct ∨ + p.account ≠ acct ∨ p.version ≠ 3) : + step cfg s (.submit cr) = none := by + simp only [step, hp, hs] + grind + +/-! ## P9 — submission modes (§Submission Modes) -/ + +/-- P9 (sanity): a transaction credential is rejected when supportedModes omits pull. -/ +theorem P9_pull_needs_pull_mode {cr : Cred} {t : Tx} (hp : cr.payload = .transaction t) + (hm : cr.echo.request.pull = false) : step cfg s (.submit cr) = none := by + simp only [step, hp] + grind + +/-- P9 (sanity): a hash credential is rejected when supportedModes omits push. -/ +theorem P9_hash_needs_push_mode {cr : Cred} {t : Tx} (hp : cr.payload = .hash t) + (hm : cr.echo.request.push = false) : step cfg s (.submit cr) = none := by + simp only [step, hp] + grind + +end TempoCharge diff --git a/formal/tempo-charge/TempoCharge/Witnesses.lean b/formal/tempo-charge/TempoCharge/Witnesses.lean new file mode 100644 index 00000000..547f2f72 --- /dev/null +++ b/formal/tempo-charge/TempoCharge/Witnesses.lean @@ -0,0 +1,119 @@ +import TempoCharge.Model +import TempoCharge.Counterexamples +/- + Witnesses: the guarded model is not vacuous. Each theorem runs the guarded model on one fixed + trace and checks by 'decide' that its legitimate calls succeed, so a guard that rejects one of + them breaks the build. Also checked: the boundary calls just outside the rules are rejected. +-/ +namespace TempoCharge.Witnesses +open TempoCharge TempoCharge.Examples + +/-- The configuration the counterexamples use satisfies every guard. -/ +theorem guarded_ok : guarded.Guarded := ⟨rfl, rfl, rfl, rfl⟩ + +/-- Pull with server-paid fees (§Server-Paid Fees): the merchant gets 100, the server pays the + fee, the receipt references the transaction. -/ +theorem W_pull_sponsored : + check guarded [.fund TOKEN PAYER 100, .issue chF, .signTx txF, + .submit { echo := chF, payload := .transaction txF }, .settlePull 1] + (fun st => st.bal TOKEN MERCHANT == 100 && st.sponsored == [1] && + st.receipts == [⟨1, .tx txF, 1⟩]) = some true := by decide + +/-- A split request (platform fee and an affiliate with a memo), paid by transfers in another + order (§Ordering): 85 / 10 / 5. -/ +def reqSplit : Request := + { req with splits := [{ recipient := PLATFORM, amount := 10 }, { recipient := 12, amount := 5, memo := some 7 }] } +def chSplit : Challenge := { chA with request := reqSplit } +def txSplit : Tx := { tx1 with calls := [{ pay with dst := 12, amount := 5, memo := some 7 }, + { pay with amount := 85 }, { pay with dst := PLATFORM, amount := 10 }] } +theorem W_pull_splits : + check guarded [.fund TOKEN PAYER 100, .issue chSplit, .signTx txSplit, + .submit { echo := chSplit, payload := .transaction txSplit }, .settlePull 1] + (fun st => st.bal TOKEN MERCHANT == 85 && st.bal TOKEN PLATFORM == 10 && st.bal TOKEN 12 == 5 && + st.receipts.length == 1) = some true := by decide + +/-- The split payment without the affiliate's memo is rejected (§Transaction Verification). -/ +theorem W_split_memo_required : + rejectedAt guarded [.fund TOKEN PAYER 100, .issue chSplit, + .signTx { txSplit with calls := [{ pay with dst := 12, amount := 5 }, { pay with amount := 85 }, + { pay with dst := PLATFORM, amount := 10 }] }, + .submit { echo := chSplit, payload := .transaction { txSplit with calls := [{ pay with dst := 12, amount := 5 }, + { pay with amount := 85 }, { pay with dst := PLATFORM, amount := 10 }] } }] 3 = true := by decide + +/-- Order does not matter (§Ordering): with a primary transfer needing no memo and a split of + the same recipient and amount needing memo 7, the calls settle in either order. -/ +def reqSameDst : Request := + { req with amount := 10, splits := [{ recipient := MERCHANT, amount := 5, memo := some 7 }] } +def chSameDst : Challenge := { chA with request := reqSameDst } +def txMemoFirst : Tx := { tx1 with calls := [{ pay with amount := 5, memo := some 7 }, { pay with amount := 5 }] } +def txMemoLast : Tx := { tx1 with calls := [{ pay with amount := 5 }, { pay with amount := 5, memo := some 7 }] } +theorem W_split_order_memo_first : + check guarded [.fund TOKEN PAYER 10, .issue chSameDst, .signTx txMemoFirst, + .submit { echo := chSameDst, payload := .transaction txMemoFirst }, .settlePull 1] + (fun st => st.bal TOKEN MERCHANT == 10 && st.receipts.length == 1) = some true := by decide +theorem W_split_order_memo_last : + check guarded [.fund TOKEN PAYER 10, .issue chSameDst, .signTx txMemoLast, + .submit { echo := chSameDst, payload := .transaction txMemoLast }, .settlePull 1] + (fun st => st.bal TOKEN MERCHANT == 10 && st.receipts.length == 1) = some true := by decide + +/-- Push (§Hash Settlement): the client broadcasts, then submits the hash. -/ +theorem W_push : + check guarded [.fund TOKEN PAYER 100, .issue chA, .signTx tx1, .broadcast tx1, + .submit { echo := chA, payload := .hash tx1 }] + (fun st => st.bal TOKEN MERCHANT == 100 && st.receipts == [⟨1, .tx tx1, 1⟩]) = some true := by + decide + +/-- A zero-amount charge settles with a proof; the receipt references the challenge id + (§Proof Receipt). -/ +def chZero : Challenge := { chA with request := { req with amount := 0 } } +theorem W_proof : + check guarded [.issue chZero, .signProof proofA, + .submit { echo := chZero, payload := .proof proofA, source := some (CHAIN, PAYER) }] + (fun st => st.receipts == [⟨1, .challenge 1, 1⟩]) = some true := by decide + +/-- A proof under domain version "2" is rejected (§Proof Contract Versions). -/ +theorem W_proof_v2_rejected : + rejectedAt guarded [.issue chZero, .signProof { proofA with version := 2 }, + .submit { echo := chZero, payload := .proof { proofA with version := 2 }, source := some (CHAIN, PAYER) }] 2 = true := by + decide + +/-- Pull is two steps: broadcast, then settlement. The pull credential, resubmitted while its + settlement is pending or replayed after it settled, is rejected (intent §Single-Use), and a + settlement can't be completed twice. -/ +def trPull : List Act := + [.fund TOKEN PAYER 100, .issue chA, .signTx tx1, .submit { echo := chA, payload := .transaction tx1 }, + .settlePull 1] +theorem W_pull : + check guarded trPull (fun st => st.bal TOKEN MERCHANT == 100 && st.receipts == [⟨1, .tx tx1, 1⟩] && + (st.pending 1).isNone) = some true := by decide +theorem W_pull_pending_no_receipt : + check guarded (trPull.take 4) (fun st => st.receipts.isEmpty && !st.used 1 && + st.pending 1 == some (tx1, true)) = some true := by decide +theorem W_pending_resubmit_rejected : + rejectedAt guarded (trPull.take 4 ++ [.submit { echo := chA, payload := .transaction tx1 }]) 4 = true := by + decide +theorem W_replay_rejected : + rejectedAt guarded (trPull ++ [.submit { echo := chA, payload := .transaction tx1 }]) 5 = true := by decide +theorem W_settle_twice_rejected : + rejectedAt guarded (trPull ++ [.settlePull 1]) 5 = true := by decide + +/-- At expires the credential is rejected; one second earlier it settles. -/ +theorem W_expired_rejected : + rejectedAt guarded [.fund TOKEN PAYER 100, .issue chA, .signTx tx1, .tick 99, + .submit { echo := chA, payload := .transaction tx1 }] 4 = true := by decide +theorem W_before_expiry : + (run guarded St.init [.fund TOKEN PAYER 100, .issue chA, .signTx tx1, .tick 98, + .submit { echo := chA, payload := .transaction tx1 }]).isSome = true := by decide + +/-- An echoed challenge with a lower amount than the one issued is rejected (binding). -/ +theorem W_tampered_rejected : + rejectedAt guarded [.fund TOKEN PAYER 100, .issue chA, .signTx tx1, + .submit { echo := { chA with request := { req with amount := 1 } }, payload := .transaction tx1 }] 3 = true := by + decide + +/-- A transaction past its validBefore never lands (§Transaction Replay). -/ +theorem W_validBefore_rejected : + rejectedAt guarded [.fund TOKEN PAYER 100, .signTx { tx1 with validBefore := some 50 }, .tick 49, + .broadcast { tx1 with validBefore := some 50 }] 3 = true := by decide + +end TempoCharge.Witnesses diff --git a/formal/tempo-charge/check.sh b/formal/tempo-charge/check.sh new file mode 100644 index 00000000..9557ba2d --- /dev/null +++ b/formal/tempo-charge/check.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +# Build the model from clean and fail unless every proof checks and only Lean's standard axioms +# are used. CI runs this; so can you (needs elan, see README.md). The gates live in +# ../core/check-lib.sh, shared by every model. +set -euo pipefail +cd "$(dirname "$0")" +exec bash ../core/check-lib.sh TempoCharge diff --git a/formal/tempo-charge/lake-manifest.json b/formal/tempo-charge/lake-manifest.json new file mode 100644 index 00000000..89eacb43 --- /dev/null +++ b/formal/tempo-charge/lake-manifest.json @@ -0,0 +1,14 @@ +{"version": "1.3.0", + "packagesDir": ".lake/packages", + "packages": + [{"type": "path", + "scope": "", + "name": "MppCore", + "manifestFile": "lake-manifest.json", + "inherited": false, + "dir": "../core", + "copy": false, + "configFile": "lakefile.toml"}], + "name": "TempoCharge", + "lakeDir": ".lake", + "fixedToolchain": false} diff --git a/formal/tempo-charge/lakefile.toml b/formal/tempo-charge/lakefile.toml new file mode 100644 index 00000000..96cb1ffb --- /dev/null +++ b/formal/tempo-charge/lakefile.toml @@ -0,0 +1,18 @@ +name = "TempoCharge" +version = "0.1.0" +defaultTargets = ["TempoCharge"] + +# Every warning is a build error: a sorry, a deprecated name, an unused variable or simp +# argument fails 'lake build' itself, not only the axiom audit. +# The shared definitions in ../core (run, Reachable, upd), audited with this model. +[[require]] +name = "MppCore" +path = "../core" + +[leanOptions] +warningAsError = true + +[[lean_lib]] +name = "TempoCharge" +# Build every module under TempoCharge/, even one nothing imports, so no proof goes unchecked. +globs = ["TempoCharge", "TempoCharge.+"] diff --git a/formal/tempo-charge/lean-toolchain b/formal/tempo-charge/lean-toolchain new file mode 100644 index 00000000..a6aff065 --- /dev/null +++ b/formal/tempo-charge/lean-toolchain @@ -0,0 +1 @@ +leanprover/lean4:v4.35.0