Post Fiat

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

Lean Verification on Post Fiat

A practitioner's guide to Post Fiat's zero-dependency Lean 4 verification methodology—adapted from Anatoly Yakovenko and the Solana Lean ecosystem—covering protocol formalization, Rust and Solidity differential oracles, and AI-agent proof workflows.

Markdown

Unit tests check the inputs an engineer thought to write. Code review checks what a human can hold in working memory. Neither exhaustively verifies multi-step interactions across BFT quorums, recovery fences, integer rounding, and cross-chain finality—where individual functions look clean in isolation, yet protocol security depends on invariants holding across every reachable state transition.

To make formal verification a practical part of everyday protocol engineering—usable by both human engineers and autonomous coding agents—we adopted a zero-dependency Lean 4 methodology inspired by recent Solana verification efforts, and ported it across four standalone packages in postfiatorg/postfiatl1v2: NAVCoin vault arithmetic, Consensus v2, FastPay v3 recovery, and Bridge Finality.

This guide documents that methodology end to end:

  1. The Solana Lean blueprint we built on, from Anatoly Yakovenko’s pure-Lean specifications to Solana’s differential oracle clients and Asymmetric Research’s verification hygiene.
  2. How Post Fiat ported it across four core protocol subsystems, with verbatim Lean 4 definitions, theorems, and a worked example of proof-driven arithmetic design.
  3. How differential oracle verification works—including the --oracle wire format—to cross-check compiled Lean specifications against Rust and Foundry EVM.
  4. A practitioner’s and AI-agent workflow guide detailing CI guardrails, anti-reward-hacking controls, and human review checks.

1. The Lean 4 Methodology From Anatoly Yakovenko & the Solana Ecosystem

Three recent Lean 4 projects in the Solana ecosystem showed how to keep formal verification fast, auditable, and coupled to production code:

  • Zero-dependency specifications & explicit proof boundaries (Anatoly Yakovenko): percolator-lean, lean-svm, and lean-svm-jit demonstrated that proving conservation laws and vault-favorable integer rounding in pure Lean 4 (no Mathlib, no external package dependencies) compiles in seconds and directly tests arithmetic and state-machine assumptions. lean-svm-jit also modeled the proof-boundary discipline required whenever a high-throughput Rust engine sits beside a formal specification: state what is kernel-proved versus assumed, and link the two through differential testing.
  • Differential oracle verification against a reference client (MidTermDev/lean-Solana-client): Implemented an executable Solana follower and replay client in Lean 4—including Merkle shred verification, epoch stake schedules, and Alpenglow BLS12-381 finality certificates (lib/Solana/Alpenglow.lean)—and mechanically cross-checked Lean outputs against Agave via make oracle. Compiling the specification into an executable oracle turns a static model into a live parity test against production code.
  • Production verification hygiene (asymmetric-research/lean-svm): Codified the CI guardrails that make Lean 4 packages safe for large teams and automated contributors: separating pure Spec modules from @[csimp]-proved Exec fast paths, strict warning and axiom audits, checker mutation tests, and cache-refinement proofs (executeBlock_eq).

Post Fiat implements the first two patterns today—zero-dependency Lean 4.20.0 specifications, executable --oracle differential harnesses against Rust and Foundry EVM, and .olean kernel replay with CI mutation self-tests—while adopting Asymmetric Research’s @[csimp] Spec/Exec layering as the target standard for future hot-path optimizations.


2. Porting the Methodology to Post Fiat

All four verification packages live under formal/lean/ in postfiatorg/postfiatl1v2. Each compiles standalone on Lean 4.20.0 with zero external dependencies, zero sorry, and zero custom axioms.

SubsystemPackageProduction Surface ModeledCore Invariants Formalized
NAVCoin Vault & Policyformal/lean/navcoin-vault/market_policy.rs, nav_vault_asset_execution.rs, b23_facility.rsExact floor/ceil rounding & integer sqrt bounds, backing solvency, round-trip vault-favorability across arbitrary splits, 15-transition supply conservation
Consensus v2formal/lean/consensus-v2/crates/ordering_fast/src/consensus_v2.rsUniversal \(n \ge 1\) BFT quorum intersection, single-height cross-view commit agreement, canonical timeout-QC selection, view-change enabledness
FastPay v3 Recoveryformal/lean/fastpay-v3/crates/execution/src/owned_transfer_recovery.rsValue conservation across wrap/transfer/unwrap/recovery, pairwise fence exclusivity, cross-lane BFT exclusivity, single-step recovery enabledness
Bridge Finality & Solanaformal/lean/bridge-finality/PFTLReceiptFinalityVerifierV2.sol, export/refund lifecycle, solana_bridge.rsInductive committee ancestry, tip monotonicity, single receipt consumption, export/refund mutual exclusion, Solana proof-bounded deposit cap

Below are four concrete examples showing how Post Fiat structures specifications, derives safety from modeled Rust transition functions, and pairs universal theorems with non-vacuity witnesses.


2.1 Proof-Driven Integer Rounding & Solvency Invariants (NAVCoin Vault)

Post Fiat’s NAVCoin primary market and multi-venue route architecture must maintain global supply conservation and exact backing solvency across every mint, redemption, and bridge transition:

$$\text{pftl\_spendable} + \text{outstanding\_bridge\_claims} + \text{pending\_return\_imports} + \text{eth\_spendable} + \text{other\_venues} = \text{authorized\_valid\_supply}$$$$\text{verified\_net\_assets} \times \text{unit\_scale} \ge \text{valid\_global\_supply} \times \text{nav\_floor}$$

Every modeled function is transcribed directly from Rust with explicit source-file and line-number citations. Compare Post Fiat’s Rust backing-capacity calculation against its Lean 4 specification:

// Rust (crates/execution/src/market_policy.rs:461-485)
pub fn compute_backing_capacity_with_unit_scale(
    verified_net_assets_usd_e8: u128,
    valid_global_supply_atoms: u128,
    nav_floor_usd_e8: u128,
    unit_scale: u128,
) -> Result<BackingCapacity, MarketPolicyError> {
    if nav_floor_usd_e8 == 0 || unit_scale == 0 {
        return Err(MarketPolicyError::DivisionByZero);
    }
    let backing_required_usd_e8 =
        mul_div_ceil(valid_global_supply_atoms, nav_floor_usd_e8, unit_scale)?;
    let verified_capacity_remaining_usd_e8 =
        verified_net_assets_usd_e8.saturating_sub(backing_required_usd_e8);
    let verified_capacity_remaining_atoms = mul_div_floor(
        verified_capacity_remaining_usd_e8,
        unit_scale,
        nav_floor_usd_e8,
    )?;
    Ok(BackingCapacity {
        backing_required_usd_e8,
        verified_capacity_remaining_usd_e8,
        verified_capacity_remaining_atoms,
    })
}
-- Lean 4 (NavcoinVault/Arithmetic.lean:33-50 & NavcoinVault/MarketPolicy.lean)
-- Mirrors crates/execution/src/market_policy.rs:393-411 and 461-485
def mulDivFloorNat (x y z : Nat) : Nat := (x * y) / z
def mulDivCeilNat (x y z : Nat) : Nat :=
  let product := x * y
  let q := product / z
  if product % z == 0 then q else q + 1

def mulDivFloor (x y z : Nat) : Option Nat := if z == 0 then none else some (mulDivFloorNat x y z)
def mulDivCeil  (x y z : Nat) : Option Nat := if z == 0 then none else some (mulDivCeilNat x y z)

def computeBackingCapacityCeilWithUnitScale
    (verifiedNetAssetsUsdE8 validGlobalSupplyAtoms navFloorUsdE8 unitScale : Nat) :
    Option BackingCapacity := do
  if navFloorUsdE8 == 0 || unitScale == 0 then
    none
  else
    let backingRequired ← mulDivCeil validGlobalSupplyAtoms navFloorUsdE8 unitScale
    let remUsd := verifiedNetAssetsUsdE8 - backingRequired
    let remAtoms ← mulDivFloor remUsd unitScale navFloorUsdE8
    some {
      backingRequiredUsdE8 := backingRequired
      verifiedCapacityRemainingUsdE8 := remUsd
      verifiedCapacityRemainingAtoms := remAtoms
    }

Worked Example: Catching a Rounding Direction Edge Case in Pre-Mainnet Hardening

Formalization pays off immediately when a proof stalls on an edge case unit tests never hit. During pre-mainnet hardening of crates/execution/src/market_policy.rs, compute_backing_capacity_with_unit_scale originally computed backing_required_usd_e8 with mul_div_floor:

- let backing_required_usd_e8 =
-     mul_div_floor(valid_global_supply_atoms, nav_floor_usd_e8, unit_scale)?;
+ let backing_required_usd_e8 =
+     mul_div_ceil(valid_global_supply_atoms, nav_floor_usd_e8, unit_scale)?;
  • Why the proof stalled: Attempting to prove exact post-mint solvency \(A \cdot U \ge (S + \Delta) \cdot F\) over mulDivFloorNat left an unprovable divisibility remainder whenever \(U \nmid S \cdot F\). At \(U = 10^{18}, F = 10^8, A = 10^8, S = 10^{18} - 1\), flooring required backing produces 99_999_999 instead of 100_000_000—a non-compounding < 1 usd_e8 ($0.00000001) shortfall that still breaks the exact cross-product invariant (computeBackingCapacity_floor_violates_invariant_default_scale).
  • How Lean closed the loop: Switching that single line to mul_div_ceil gives \(S \cdot F \le \lceil S \cdot F / U \rceil \cdot U\), so assuming pre-mint solvency (hinit : postMintBackingInvariantHoldsWithUnitScale A S F U = true), minting any \(\Delta\) within the computed headroom preserves solvency for all Nat inputs:
theorem computeBackingCapacityCeil_preserves_invariant
    {A S F U delta : Nat} {cap : BackingCapacity}
    (hcap : computeBackingCapacityCeilWithUnitScale A S F U = some cap)
    (hinit : postMintBackingInvariantHoldsWithUnitScale A S F U = true)
    (hdelta : delta ≤ cap.verifiedCapacityRemainingAtoms) :
    postMintBackingInvariantHoldsWithUnitScale A (S + delta) F U = true

We locked the change into Rust with a deterministic regression test (compute_backing_capacity_never_violates_post_mint_invariant) and our 10,000-vector differential oracle.

The same mathematical discipline governs round-trip subscribe/redeem pricing in NavcoinVault/MarketPolicy.lean. By using ceiling rounding on subscriptions (baseValueCeil) and floor rounding on redemption base values (baseValueFloor), primary_split_redemption_fixed_with_floor_base_value proves a round-trip no-profit inequality across arbitrary finite splits: subscribing parts.sum atoms and redeeming them in any sequence of split orders parts never debits more reserve than was credited and never pays out more than the subscription cost:

theorem primary_split_redemption_fixed_with_floor_base_value
    (parts : List Nat) (navPerUnit denom issueMultiplierBps redeemMultiplierBps : Nat)
    (hdenom : denom > 0)
    (hredeem : redeemMultiplierBps ≤ BPS)
    (hissue : BPS ≤ issueMultiplierBps) :
    let totalReserveDebited := (parts.map (fun a => baseValueFloor a navPerUnit denom)).sum
    let totalPayout := (parts.map (fun a =>
      redeemSettlementOutput (baseValueFloor a navPerUnit denom) redeemMultiplierBps)).sum
    let reserveCredited := baseValueCeil parts.sum navPerUnit denom
    let subscribeCost := subscribeSettlementDue reserveCredited issueMultiplierBps
    totalReserveDebited ≤ reserveCredited ∧ totalPayout ≤ subscribeCost

Explicit u128 vs. Nat type boundary: Lean Nat truncated subtraction (-) matches Rust u128::saturating_sub identically. Rust’s checked u128 multiplication returns Err(MarketPolicyError::Overflow) on intermediate overflow, whereas Lean Nat is unbounded and returns none only on division by zero. Keeping that boundary explicit lets Lean prove universal properties over Nat, the differential oracle check non-overflowing parity and zero-divisor errors, and Rust unit tests (arithmetic_errors_fail_closed) verify overflow fail-closed rejection.


2.2 Quorum Intersection & Single-Height BFT Agreement (Consensus v2)

crates/ordering_fast/src/consensus_v2.rs implements Post Fiat’s two-phase BFT finality rules (Prepare, Precommit, Timeout, durable locked_qc, and TimeoutCertificate view changes). While Rust tests check quorum intersection by bitmask enumeration up to n <= 20, formal/lean/consensus-v2/ConsensusV2/Quorum.lean proves algebraically that \(2q > n + f\) guarantees an honest validator in every pair of quorums for all committee sizes \(n \ge 1\).

Crucially, per-validator safety invariants are proved inductively from the modeled Rust authorization functions, not assumed as axioms. In ConsensusV2/Invariants.lean, HonestStep invokes authorizePrepareVote, authorizePrecommitVote, or authorizeTimeoutVote, and HonestStep.preserves proves that every authorized step preserves SafetyInvariant and StateMonotone starting from initialSafetyState_invariant (so carrying SafetyInvariant tr[i].pre inside ValidValidatorTrace is an inductively proved convenience, not an extra assumption):

-- Mirrors authorize_consensus_v2_{prepare,precommit,timeout}_vote (consensus_v2.rs:802-962)
def HonestStep (c : Committee) (s : SafetyState) (act : HonestAction) (s' : SafetyState) : Prop :=
  match act with
  | .prepare p tc? graph => authorizePrepareVote s c graph p tc? = .ok s'
  | .precommit qc => authorizePrecommitVote s c qc = .ok s'
  | .timeout round hq? graph => authorizeTimeoutVote s graph round hq? = .ok s'

theorem HonestStep.preserves {c : Committee} {s s' : SafetyState} {act : HonestAction}
    (hinv : SafetyInvariant s) (hstep : HonestStep c s act s') :
    SafetyInvariant s' ∧ StateMonotone s s' := by
  cases act with
  | prepare p tc? graph => exact authorizePrepareVote_preserves_invariant hinv hstep
  | precommit qc => exact authorizePrecommitVote_preserves_invariant hinv hstep
  | timeout round hq? graph =>
    have h := authorizeTimeoutVote_spec hinv hstep
    exact ⟨h.1, h.2.1⟩

def ValidValidatorTrace (c : Committee) (H : Height) (tr : List TraceEntry) : Prop :=
  H > 0 ∧
  (∀ e ∈ tr, HonestStep c e.pre e.act e.post) ∧
  (∀ i (hi : i < tr.length),
    SafetyInvariant tr[i].pre ∧
    (i = 0 → initialSafetyState H = .ok tr[i].pre)) ∧
  (∀ i (hi : i + 1 < tr.length), tr[i].post = tr[i + 1].pre)

From ValidValidatorTrace alone, ConsensusV2/Invariants.lean proves honest_prepare_unique, honest_precommit_unique, honest_timeout_unique, honest_precommit_before_later_prepare, and honest_locked_qc_origin. ConsensusV2/Safety.lean then combines those derived trace theorems with explicit cryptographic and causal execution hypotheses (SystemExecution) to prove single-height cross-view commit agreement across any views v1, v2 at height H:

theorem bft_commit_agreement (exec : SystemExecution)
    {c1 c2 : Commit} {v1 v2 : View} {B1 B2 : BlockId}
    (hauth1 : exec.AuthenticQC c1.precommitQc)
    (hauth2 : exec.AuthenticQC c2.precommitQc)
    (hr1 : c1.precommitQc.round = ⟨exec.H, v1⟩)
    (hr2 : c2.precommitQc.round = ⟨exec.H, v2⟩)
    (hcom1 : commitFromPrecommitQC exec.c c1.precommitQc = .ok B1)
    (hcom2 : commitFromPrecommitQC exec.c c2.precommitQc = .ok B2) :
    B1 = B2 := by
  have hs1 := commitFromPrecommitQC_spec hcom1
  have hs2 := commitFromPrecommitQC_spec hcom2
  exact bft_precommit_qc_agreement exec hauth1 hauth2 hr1 hr2 hs1.2.1 hs2.2.1 hs1.2.2 hs2.2.2

Proved vs. assumed inside SystemExecution:

  • Proved from the modeled Rust step functions: round monotonicity, per-view vote uniqueness, durable locked_qc preservation, and the unlock condition (locked.round < validQc.round).
  • Assumed explicitly as fields of SystemExecution (never global axioms): committee fault bound (|Byz| ≤ f, 2q > n + f), ML-DSA-65 unforgeability (every honest vote inside an AuthenticQC was emitted by that validator in traces strictly before qcTime), and Lamport happens-before causality (every QC verified by an honest validator formed strictly before stepTime).
  • Kernel-checked non-vacuity: To prove SystemExecution is inhabited rather than vacuous, systemExecution_4v_commit_witness constructs a concrete 4-validator execution (n = 4, f = 1, q = 3, Byz = [3]) where honest validators execute Prepare → Precommit and satisfy commitFromPrecommitQC exec.c cm.precommitQc = .ok 500.
  • Canonical signer-subset selection: Because a certificate_id hashes the signer subset, two valid Prepare QCs for the same (height, view, block) can carry distinct certificate_ids. Modeling timeout-QC selection (highestTimeoutQcFixed) as a two-pass max-rank fold—rejecting only distinct-block conflicts at maximum rank and tie-breaking same-block QCs by smallest certificate_id—proves order-independent, deterministic view-change selection across every quorum subset.

2.3 Owned-Object Recovery Fences & Value Conservation (FastPay v3)

FastPay v3 settles transfers and unwraps of versioned owned objects (object_id, version) in one round-trip once a validator quorum signs an ML-DSA-65 certificate. If a client stalls mid-lock, ordered consensus recovery (crates/execution/src/owned_transfer_recovery.rs) runs a Reveal → Decision → Version Fence state machine that writes a permanent version fence either confirming a revealed certificate (Confirmed) or advancing the input version (Cancelled).

In formal/lean/fastpay-v3/, we prove total value conservation across all operations (traceFixed_conserves), pairwise fence exclusivity (no_conflicting_fences_for_ref), cross-lane BFT exclusivity (cross_lane_exclusivity_bft), and single-step recovery enabledness (fixed_recovery_confirm_liveness, fixed_blocks_cross_lock_cancellation—note that despite the Liveness.lean module name, these theorems prove single-step transition enabledness under the modeled rules, not asynchronous network liveness).

Two core invariants shape the recovery model:

  1. Order-level reveal deduplication: Keying recovery reveals on (lock_id, order_digest) rather than certificate_digest guarantees that distinct valid validator subsets (e.g., multiple 5-of-6 quorums for the same order) collapse idempotently ahead of table-capacity checks.
  2. Input-overlap cancellation guard: Checking whether any revealed certificate overlaps a candidate cancellation’s input (object_id, version)—regardless of lock_id or nonce—guarantees mutual exclusion between confirmed certificates and cancellations.

To verify non-vacuity directly in the Lean kernel, FastPayV3/Liveness.lean pairs the universal theorem with a concrete 6-validator execution witness discharged by rfl:

theorem fixed_6v_cross_lock_blocked :
    ∃ s1 revA s2 fenceA,
      recordRecoveryRevealFixed fixtureLedger certA_subset1 fixtureCtx6 111 = .ok (s1, revA) ∧
      executeRecoveryDecisionFixed s1
        { submittedAtHeight := 120, signedOrder := signedOrderB }
        fixtureCtx6 120 = .error .invalidRecovery ∧
      executeRecoveryDecisionFixed s1
        { submittedAtHeight := 120, signedOrder := signedOrderA }
        fixtureCtx6 120 = .ok (s2, fenceA) ∧
      fenceA.decision = .confirmed (orderDigest orderA) (certificateDigest certA_subset1) := by
  refine ⟨_, _, _, _, rfl, rfl, rfl, rfl⟩

2.4 Inductive Bridge Ancestry & Explicit ZK Proof Assumptions (Bridge Finality)

In formal/lean/bridge-finality/, we model PFTLReceiptFinalityVerifierV2.sol, the Post Fiat–Ethereum export/refund lifecycle, and solana_bridge.rs. Rather than treating ZK proof verification as an opaque global axiom, VerifierV2.lean passes proof soundness explicitly via ProofSound:

structure ProofSound
    (proofReceiptOk : ReceiptPublicValues → Bool)
    (proofCheckpointOk : CheckpointPublicValues → Bool)
    (ValidAncestrySegment : Bytes32 → Bytes32 → Bytes32 → Prop)
    (ValidCheckpointSucc : Bytes32 → Bytes32 → Nat → Prop) : Prop where
  receipt_sound : ∀ pv, proofReceiptOk pv = true →
    ValidAncestrySegment pv.ancestryRootCommitment pv.ancestrySegmentCommitment
      pv.provenCommitteeRootCommitment ∧
    ValidCheckpointSucc pv.priorCheckpointCommitment pv.resultingCheckpointCommitment
      pv.finalizedHeight
  checkpoint_sound : ∀ pv, proofCheckpointOk pv = true →
    ValidAncestrySegment pv.ancestryRootCommitment pv.ancestrySegmentCommitment
      pv.provenCommitteeRootCommitment ∧
    ValidCheckpointSucc pv.priorCheckpointCommitment pv.resultingCheckpointCommitment
      pv.finalizedHeight

theorem v2_inductive_committee_ancestry_soundness
    {cfg : VerifierV2Config} (hCfg : cfg.valid)
    {proofReceiptOk : ReceiptPublicValues → Bool}
    {proofCheckpointOk : CheckpointPublicValues → Bool}
    {ValidAncestrySegment : Bytes32 → Bytes32 → Bytes32 → Prop}
    {ValidCheckpointSucc : Bytes32 → Bytes32 → Nat → Prop}
    (hSound : ProofSound proofReceiptOk proofCheckpointOk ValidAncestrySegment ValidCheckpointSucc)
    {s : VerifierV2State}
    (hReach : V2Reachable cfg proofReceiptOk proofCheckpointOk s) :
    (∀ c, s.canonicalCheckpointHeight c > 0 →
      AncestryChain cfg.ancestryAnchorCommitment cfg.ancestryAnchorHeight ValidCheckpointSucc
        c (s.canonicalCheckpointHeight c)) ∧
    (∀ pv ∈ s.acceptedReceipts,
      pv.ancestryRootCommitment = cfg.ancestryAnchorCommitment ∧
      pv.committeeRootCommitment = pv.provenCommitteeRootCommitment ∧
      ValidAncestrySegment cfg.ancestryAnchorCommitment pv.ancestrySegmentCommitment
        pv.committeeRootCommitment)

ProofSound constrains a single proof’s inputs and outputs (bundling Groth16 soundness and SP1 guest obligations such as unique checkpoint heights). What the Lean theorem proves on top of ProofSound is that the on-chain verifier’s stateful storage logic (canonicalCheckpointHeight, pinnedTipHeight, consumedReceiptIdentifier, consumedProofNullifier, _requireAncestry, and _advanceTipIfStrictlyGreater) inductively preserves anchored committee ancestry across arbitrary interleaved verifyAndAccept and advanceCheckpoint calls. The same package also formalizes export/refund mutual exclusion on BFT_CHECKPOINT routes and proof-bounded deposit caps on Post Fiat’s Solana ingress bridge.


3. How Differential Oracle Verification Works

A Lean proof establishes mathematical properties of a model, not automatically of the production Rust or Solidity codebase. Borrowing the make oracle architecture from MidTermDev/lean-Solana-client and lean-svm-jit, Post Fiat narrows that gap mechanically using differential oracle testing.

The Three-Step --oracle Pattern

flowchart LR
    G["Deterministic Vector Generator<br/>(Adversarial Boundaries + Seeded PRNG)"]
    R["Production Rust / Foundry EVM<br/>(cargo test & forge test --ffi)"]
    L["Compiled Lean 4 Model<br/>(pkg_check --oracle vectors.txt)"]
    C["Line-by-Line Comparator<br/>(Return Values, Revert Selectors, Post-State)"]

    G --> R
    G --> L
    R --> C
    L --> C
  1. Expose --oracle <path> in each package’s Main.lean: The compiled Lean binary reads one space-delimited query per line, evaluates the exact Lean functions referenced by the theorems, and prints one canonical result line per query:
# Input vectors (vectors.txt -> navcoin_vault_check --oracle vectors.txt)
cap 100000000 999999999999999999 100000000 1000000000000000000
settle 100 1000001 1000000
cap 100000000 1000 0 1000000000000000000

# Canonical Lean oracle output compared line-for-line against Rust
ok 100000000 0 0 true
ok 101 100
err

Wire-format decoding:

  • cap <assets_usd_e8> <supply_atoms> <nav_floor_usd_e8> <unit_scale> → ok <backing_required_usd_e8> <remaining_usd_e8> <remaining_atoms> <post_mint_solvency_holds> (the trailing true confirms that postMintBackingInvariantHoldsWithUnitScale holds after adding remaining_atoms), or err on division by zero.
  • settle <amount_atoms> <nav_per_unit> <denom> → ok <base_value_ceil> <base_value_floor>, or err when denom = 0.
  • For stateful oracles (consensus-v2, fastpay-v3, bridge-finality), each line encodes a multi-step command sequence (<op1> <op2> ...) and outputs <step_outcomes_csv> | <final_state_fields>—including exact Solidity custom revert selectors (such as wrong_ancestry_root or receipt_consumed) in LeanBridgeFinalityOracle.t.sol.
  1. Drive production code from the same deterministic stream: Each Rust integration test (cargo test) or Foundry test (forge test --ffi) feeds identical boundary cases and deterministically seeded randomized sequences through both production code (using real ML-DSA-65 signatures for Consensus v2 and FastPay v3, and EVM execution for PFTLReceiptFinalityVerifierV2.sol) and the compiled Lean binary.
  2. Assert exact output parity: Any disagreement in return values, revert/error classification, or final state fails the test immediately and prints the exact failing vector.

Post Fiat’s Four Differential Oracles & Trust Boundary

All four suites currently pass with zero disagreements within their tested input domains, whose scope and exclusions are summarized below:

PackageOracle HarnessWhat Is Cross-CheckedKnown Scope Boundaries
NAVCoin Vaultcrates/execution/tests/lean_navcoin_oracle.rs10,000 arithmetic vectors (boundary cases, NAV floor, backing capacity, subscribe-ceil / redeem-floor settlement)Non-overflow u64/u128 domain (overflow Err covered by Rust unit tests); outer 15-transition routes covered by unit tests
Consensus v2crates/ordering_fast/tests/lean_consensus_v2_oracle.rsQuorum thresholds (n = 1..20), 250 ML-DSA-65 highest_timeout_qc quorums, 250 6-step Prepare/Precommit/Timeout safety sequencesFixed 4-validator committee (q = 3), single height, views 0..3; networking and WAL persistence abstracted out
FastPay v3crates/execution/tests/lean_fastpay_v3_oracle.rs250 6-step ML-DSA-65 sequences across all 7 valid 5/6-of-6 subsets, reveal deduplication, shadow-order guards, bad signatures, and height windowsFixed 6-validator committee (q = 5), 2 owned objects, transfers (unwraps and cap saturation covered by unit tests)
Bridge Finalitycrates/ethereum-contracts/test/LeanBridgeFinalityOracle.t.sol500 6-step Foundry EVM sequences of verifyAndAccept & advanceCheckpoint matching every custom revert selector and final tip/receipt stateMock SP1 verifier (hex"0102" / hex"dead"); ExportRefund and solana_bridge.rs covered by unit tests

Keeping the Trusted Computing Base (TCB) explicit is the core discipline behind this workflow:

  • Kernel-verified: All audited Lean theorems (lake build --wfail, {propext, Classical.choice, Quot.sound} only, .olean replay via lean4checker).
  • Differentially tested: Model-to-code parity across the four oracle domains above (narrows transcription drift within the tested input distributions; trusts the Lean compiler for executable evaluation).
  • Explicit theorem hypotheses: Cryptographic hardness (ML-DSA-65, SHA3-384, SP1 Groth16) and unverified SP1 guest obligations enter as explicit parameters—never global axioms.
  • Out of scope: Hardware side-channels, disk/WAL persistence, and asynchronous network liveness under partial synchrony.

4. Practitioner’s & AI Agent’s Guide to Lean 4 on Post Fiat

Because the Lean 4 kernel rejects every invalid proof term, both human engineers and autonomous coding agents can develop and iterate on proofs safely—provided the CI harness prevents proof shortcuts and reviewers audit what the kernel cannot judge.

Standard Workflow Loop (Human & AI Contributors)

  1. Transcribe Spec faithfully: Copy the target Rust or Solidity logic into pure Lean 4, citing exact file paths and line numbers above every definition and documenting any intentional type boundary (such as u128 overflow vs. unbounded Nat).
  2. State the target invariant & isolate hypotheses: Pass cryptographic and external-guest assumptions as explicit structure parameters (like SystemExecution or ProofSound), never global axioms.
  3. Treat stuck goals as design diagnostics: When a theorem resists closing, inspect the remaining goal state and construct a minimal concrete counterexample to determine whether the spec needs a sharper precondition, a different rounding direction, or a stronger state-machine guard.
  4. Prove non-vacuity: Pair every flagship universal theorem with a concrete executable inhabitation witness (systemExecution_4v_commit_witness, fixed_6v_cross_lock_blocked) so False → Anything can never pass unnoticed.
  5. Wire --oracle <path> parity tests: Add deterministic boundary and PRNG vectors comparing the compiled Lean binary against Rust (cargo test) or Solidity (forge test --ffi).
  6. Register theorems in lean-check.toml and run the full CI gate.

Anti-Reward-Hacking CI Guardrails (scripts/check-lean-formal-proofs)

When autonomous coding agents write or refactor Lean proofs, naive CI checks can be gamed (for example, by weakening or deleting a hard theorem, using native_decide or sorry, or injecting custom compiler flags). Post Fiat’s CI gate blocks those failure modes mechanically:

  • Zero external dependencies & locked compiler options: Pins leanprover/lean4:v4.20.0, forbids [[require]], and disallows custom leanOptions or moreLeanArgs in package lakefile.toml files.
  • Strict source scan & --wfail: Builds with lake build --wfail and scans all .lean files banning sorry, admit, axiom, native_decide, unsafe, implemented_by, skipKernelTC, debug.*, elab, macro, syntax, run_cmd, #eval, initialize, and addDecl.
  • Full-environment axiom audit & lean4checker replay: Verifies every audited declaration depends only on {propext, Classical.choice, Quot.sound} and replays all .olean artifacts through lean4checker.
  • Theorem-manifest pinning & checker self-tests: Checks exact theorem-list parity against lean-check.toml (preventing silent theorem deletion) and runs scripts/check-lean-formal-proofs --self-test mutation tests proving injected violations fail the gate.
  • Target standard for future fast paths (@[csimp]): Following Asymmetric Research’s Spec/Exec layering, whenever an executable Lean model adds a cached or optimized path, keep Spec pure and attach optimizations strictly via kernel-proved @[csimp] equality lemmas—never @[implemented_by] or unsafe.

What Humans Must Audit (And Agents Cannot Self-Certify)

Name-pinning in lean-check.toml blocks an autonomous agent from deleting a theorem, and the Lean kernel blocks invalid proof steps—but neither prevents an agent from weakening a theorem’s statement or modeling the wrong function. Every human review of an agent-authored proof PR checks four things:

  • Theorem-signature diffs: Inspect diffs to theorem statements (not just proof bodies) to confirm no conclusion was weakened and no extra precondition was quietly added.
  • Hypothesis-bundle audit: Read every assumption field in parameter structures like SystemExecution and ProofSound in plain English to verify cryptographic and external-guest obligations match reality.
  • Non-vacuity witnesses: Confirm every new universal theorem has an executable or rfl-checked inhabitation witness so the hypotheses are jointly satisfiable.
  • Spec-to-code fidelity: Spot-check source-cited Lean definitions against production Rust/Solidity and verify the corresponding --oracle suite exercises the changed paths.

Reproducing Verification Locally

# 1. Lean CI gate: build (--wfail), source-scan, axiom-audit, lean4checker replay, self-test
scripts/check-lean-formal-proofs
scripts/check-lean-formal-proofs --self-test

# 2. All 4 Lean-vs-Rust and Lean-vs-Foundry EVM differential oracles
cargo test --locked --release -p postfiat-execution --test lean_navcoin_oracle -- --nocapture
cargo test --locked --release -p postfiat-ordering-fast --test lean_consensus_v2_oracle -- --nocapture
cargo test --locked --release -p postfiat-execution --test lean_fastpay_v3_oracle -- --nocapture
(cd crates/ethereum-contracts && forge test --ffi --match-contract LeanBridgeFinalityOracleTest -vv)