Maintained procedure · manual/workflows/probabilistic-workflows.mdMarkdown source at d23f2aea9f24
On this page

Work with randomized and oracle programs

Randomized algorithms, interactive verifiers and cryptographic reductions separate three layers: program syntax (ProbComp α and ProbOracleComp spec α), probability distributions (PMF α, obtained via ProbComp.eval or stateful oracle execution), and strict polynomial-time machine certificates (IsPPTOn, IsPPT, IsOraclePPTOn, IsOraclePPT). Prove distributional equalities and distance bounds on the semantic side, certify runtime separately on the program syntax, and join them at the final theorem. Each Lean block below is a contextual excerpt from a checked test client, reproduced under the repository's Apache 2.0 license; open the linked file for full imports and surrounding context. cslib-frontier

State a probability and sample uniformly#

Import Notation.lean and open Cslib.Probability so public statements match textbook conventions:

Write uniform sampling with $ᵗ α (let a ← $ᵗ ZMod q, parenthesizing compound types as $ᵗ (ZMod q × Bool)). It is notation for ProbComp.uniform α, so ProbComp.eval_uniform, pmf_norm and all ProbComp.uniform lemmas apply directly; see ProbabilityNotation.lean.

Normalize the law of a program#

To compute with ProbComp.eval of a do block, import Norm.lean in the proof and run simp only [pmf_norm]. It rewrites program evaluation into right-nested PMF.bind chains with returned values substituted and maps pushed into continuations—the exact shape expected by PMF.bind_congr_on_support, PMF.bind_apply and support lemmas, without unfolding support membership or masses (PMFNorm.lean).

To align independent draws across two sampling chains, import PMFSwap.lean (for pmf_swap and pmf_hoist) and GameHop.lean (for peel_binds and game_trans):

See CslibFrontierTests/PMFSwap.lean and GameHopTactic.lean for positive examples and failure boundaries.

Bind a program inside a distribution#

When a security game must be a PMF Bool (for instance because its setup distribution is not assumed efficiently sampleable), import Lift.lean to bind ProbComp steps directly inside a PMF do-block without repeating ProbComp.eval on every line. The lift unfolds definitionally to ProbComp.eval; simp only [pmf_norm] and ProbComp.liftM_eq_eval restore explicit ProbComp.eval for rewriting (ProbabilisticLift.lean).

Keep public theorem statements explicit (ProbComp.eval, Pr[e] or Experiment), and keep any experiment whose steps are all programs as a ProbComp Bool rather than lifting it prematurely to PMF.

Invert a support membership#

To extract the intermediate random choices behind h : x ∈ m.support, import SuppCases.lean and run supp_cases h with ⟨a, ha, b, hb, rfl⟩. It pushes support membership through bind, map, pure, conditionals and uniform draws for PMF, ProbComp.eval, OracleComp.supportWith and OracleComp.support:

See SuppCases.lean for checked patterns and diagnostics.

Sample uniformly, reject within a budget and count coins#

A strict polynomial-time fair-coin machine can sample exact uniform distributions only on dyadic sizes (such as Bool, BitString.sampleList n, or powers of two). ProbComp.uniform (Fin 3) has an exact uniform PMF law, but cannot be realized in strict polynomial time without either truncation error or unbounded coin flips. Choose the matching sampling layer for your claim:

Bound statistical distance, divergences and hybrids#

Keep normalization conventions explicit when converting between distance and divergence measures:

For conditioned finite laws p.filter s h (requiring h : ∃ a ∈ s, a ∈ p.support), import PMF/Filter.lean for toOuterMeasure_filter_mul_eq_inter, filter_filter, filter_map and filter_bind_pair. For independence of observables, use indepFun_iff_map_pair_eq_bind and IndepUniform in PMF/Independence.lean; for splitting product distributions PMF.pi p, import Product/Split.lean; for discrete moment and Markov-chain coupling bounds, use EventCount.lean, PMF/Markov.lean, PMF/Chebyshev.lean and MarkovChain/Coupling.lean.

In multi-hop security proofs, chain Game.advantage_comm, Game.advantage_triangle and Game.advantage_four_hop_le to establish a concrete per-parameter bound Adv(A, n) ≤ Adv(B₁ A, n) + Adv(B₂ A, n) + δ n, then close the asymptotic Negligible goal with negligible (or negligible using hbound after applying each hardness assumption to obtain the negligibility of Adv(Bᵢ A, ·)).

Compare two runs one step at a time#

To relate two iterative or stateful computations without inducting on full transcripts by hand:

  1. Rewrite loops as distribution chains with ProbComp.eval_iterate, ProbComp.eval_iterate_congr and OracleComp.run_interpret_iterate_pmf from Iteration/Chain.lean.
  2. Couple loop states with invariants using PMF/Coupling.lean: PMF.RepInv bundles d₁.map rep = d₂ with a support invariant (PMF.RepInv.iterate), while PMF.HiddenCoupling relates a real state a to an ideal run that first draws hidden randomness exp a and applies rep a (PMF.HiddenCoupling.iterate, composing via .pure, .bind, .map and .congr).
  3. Lift step relations across adaptive oracle queries with run_interpret_simulation_of_invariant and run_interpret_map_state_of_invariant in Simulation.lean, or under a decreasing query budget (such as remaining space in a bounded cache) with ProbOracleComp.IsQueryBounded.run_interpret_bind_comm_of_invariant in Oracle/QueryBoundedSimulation.lean.

Certify a closed randomized routine#

State closed runtime claims as IsPPTOn encIn encOut program (or IsPPT encOut program for cryptographic algorithms taking unary security parameter n : ℕ and auxiliary word List Bool). A certificate provides one finite-control fair-coin multi-tape Turing machine and one strict polynomial clock valid on every input and coin path, charging output writing and matching ProbComp.eval (program x) exactly.

When a module certifies many reductions or ppt is slow on an adversary call with preprocessed inputs, compose the combinators explicitly: apply IsPPTOn.isPPT, chain sampled words with (ComputableInPolyTime.sampleList (by fun_prop)).bind_with, invoke the adversary via IsPPT.preprocess (which takes separate certificates for the security parameter and word input, avoiding metavariable ambiguity on pairs), and close deterministic leaves with fun_prop. Open InaccessibleEntropy.lean:

example {A : ℕ → List Bool → ProbComp (List Bool)} (hA : IsPPT encBits A) :
    IsPPT encBits (fun n y => do
      let pad ← Cslib.BitString.sampleList n
      let raw ← A n (y ++ pad)
      return raw.take n) := by
  apply IsPPTOn.isPPT
  refine (ComputableInPolyTime.sampleList (by fun_prop)).bind_with ?_
  exact (hA.preprocess (by fun_prop) (by fun_prop)).bind_with
    (ComputableInPolyTime.isPPTOn (by fun_prop))

For randomized loops, folds and iterated PRG stretch whose state grows across rounds:

Substitute an oracle while preserving private samples#

In an oracle reduction, import Oracle/Substitution.lean and replace external queries with a ProbOracleComp handler via ProbOracleComp.simulate handler adversary. External queries route through handler (which may itself flip coins and issue target queries), while adversary's private coin draws remain untouched without case-splitting on sumHandler. Open ProbOracleSubstitution.lean:

private noncomputable def adversary : ProbOracleComp (fun _ : Bool => ℕ) (Bool × ℕ) := do
  let bit ← ProbOracleComp.sample (ProbComp.uniform Bool)
  let reply ← ProbOracleComp.query bit
  return (bit, reply)

private noncomputable def maskedQuery (bit : Bool) : ProbOracleComp (fun _ : Bool => ℕ) ℕ := do
  let mask ← ProbOracleComp.sample (ProbComp.uniform Bool)
  ProbOracleComp.query (bit ^^ mask)

private noncomputable def reduction : ProbOracleComp (fun _ : Bool => ℕ) (Bool × ℕ) :=
  ProbOracleComp.simulate maskedQuery adversary

Combine ProbOracleComp.simulate with three companion modules:

Pass a query adapter through an eager/lazy game hop#

To switch between an eagerly sampled random function and a lazily memoized cache behind a query adapter, import Oracle/Substitution.lean and RandomOracle/Probabilistic.lean, and apply RandomOracle.interpret_prob_eq_memoize (or interpret_prob_eq_memoize_map when cache keys and values map through a representation) directly to ProbOracleComp.simulate handler program. Open RandomOracleAdapter.lean:

private def oneBitQuery (word : List Bool) : ProbOracleComp (fun _ : Bool => Bool) (List Bool) :=
  match word with
  | [bit] => List.singleton <$> ProbOracleComp.query bit
  | _ => pure []

private noncomputable def repeated : ProbOracleComp (fun _ : List Bool => List Bool) Bool := do
  let first ← ProbOracleComp.query [false]
  let coin ← ProbOracleComp.sample (ProbComp.uniform Bool)
  let rejected ← ProbOracleComp.query []
  let second ← ProbOracleComp.query [false]
  return (first == second) && rejected.isEmpty && coin

private noncomputable def adapted : ProbOracleComp (fun _ : Bool => Bool) Bool :=
  ProbOracleComp.simulate oneBitQuery repeated

Follow with ProbOracleComp.interpret_simulate and normalize closed state-threaded runs using simp only [runWith_norm, pmf_norm] from Oracle/Norm.lean.

When a game stores one or more random-oracle caches inside its own state record (rather than calling memoize directly), import RandomOracle/Represented.lean (and RandomOracle/Sum.lean for ⊕ₒ multi-oracle interfaces): map state to RandomOracle.Cache spec with RandomOracle.ofList and Cache.sum, prove each lazy call matches RandomOracle.answer, and apply RandomOracle.eval_run_interpret_eq_complete_bind followed by RandomOracle.bind_complete_sum. If a handler inspects the cache directly (so the hop is only statistically close), use OracleComp.closeTo_run_interpret_simulation_readOnly in Simulation/CloseTo.lean with RandomOracle.complete, charging only cache-reading calls.

Bound stateful identical-until-bad hops and random-oracle collisions#

When two stateful oracle worlds agree until a collision or guessing event occurs, use the shared bad-flag framework in UntilBad/Flag.lean and Crypto/Game/UntilBad.lean (UntilBadROMFramework.lean):

Certify an adaptive oracle client#

Strict polynomial-time oracle algorithms are written in WordOracleComp Operation α (finite operation tags with List Bool requests and replies) and certified with IsOraclePPTOn encIn encOut prog (or parameterized IsOraclePPT) from Oracle/Composition.lean.

To propagate query budgets and instantiate external handlers:

Connect a randomized RAM loop to its answer law#

When certifying a randomized algorithm on the Word-RAM rather than a Turing machine, import Randomized/LoopSegmentLaw.lean and track LoopSegmentLaw (pairing exact equality of an observed output's PMF with pathwise instruction and random-call upper bounds and a supported-state postcondition): lift a loop body's ExecRandLaw with LoopSegmentLaw.single (charging two guard steps), chain phases across every supported intermediate state with LoopSegmentLaw.trans, and exit on a falsified guard with LoopSegmentLaw.finish (WordRAMLoopSegmentLaw.lean).

Carry the certificate into a security proof#

Follow the contract of AGENTS.md (Security theorems) and policy/statements.md from the start of every cryptographic development:

  1. Check model boundaries before proving security. In Crypto/Computational/Basic.lean, ComputationallyIndistinguishable quantifies over uniform strict-PPT distinguishers (IsPPT encBool) without requiring the compared PMF ensembles themselves to be efficiently sampleable. In CCA and hybrid reductions (Encryption/Hybrid.lean, Hybrid/CompositionCCA.lean, KEMFromPKE/CCA.lean), verify canonical encPair framing and the KEM ciphertext-space predicate ctSpace on decryption, enforce challenge freshness on raw ciphertext words, distinguish failed decapsulation none from an empty key some [], and state public-key CPA assumptions with two-stage cpaAdvantage (PKE/ExplicitCoin.lean) rather than fixed message pairs.
  2. Write every reduction as an explicit program with a strict-PPT witness. Prove isPPT_… or isOraclePPT_… from the adversary's certificate and any component efficiency hypotheses, prove the concrete advantage inequality Adv(A, n) ≤ f(Adv(B A, n)) + δ n as a lemma, and derive the asymptotic security theorem first by applying each hardness assumption directly to B A through its efficiency witness (ElGamal/ProbComp.lean is a canonical template). Never leave a premise about a constructed reduction, simulator, extractor or hybrid on a security theorem; an algebraic helper taking such a premise must be named …_of_reduction_le and open its docstring by calling itself a step or helper, not a headline.
  3. Register and verify every named hardness assumption. Every Prop-valued hardness assumption (including component security notions assumed of caller arguments) must appear in the assumptions inventory as standard (docstring cites the exact source definition with a locator verified at the source, listing every material deviation such as uniform adversaries or arbitrary setup laws), novel (docstring states "novel to this library", relates it to standard assumptions and explains plausibility; theorems resting on it name the assumption and never claim a cited result), or vocabulary (generic relations such as Game.Indistinguishable, whose concrete instance review checks at each call site). Where an insecure instance exists (a constant function, fixed group or zero noise law), include a test proving the assumption fails on it (AssumptionNonvacuity.lean).
  4. Run the cryptographic audits before opening a PR. After building the affected targets and CslibFrontierResults, run python3 scripts/check_hardness_assumptions.py (enforced in CI) and inspect any output from the advisory scans python3 scripts/check_security_premises.py and python3 scripts/check_reduction_witnesses.py on changed modules, alongside python3 -B scripts/check_operator_manual.py.