Skip to content

Use stdlib bits as the word type everywhere (word interface removal, PR 3) - #565

Merged
andres-erbsen merged 7 commits into
mit-plv:masterfrom
JasonGross:fable/bits
Sep 17, 2026
Merged

andres-erbsen merged 7 commits into
mit-plv:masterfrom
JasonGross:fable/bits

Conversation

@JasonGross

@JasonGross JasonGross commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

PR 3 of the word-interface removal (after mit-plv/coqutil#187 and mit-plv/riscv-coq#54): the word type is stdlib bits width everywhere in bedrock2, with Bitwidth width the only assumption about the width. One commit per subproject: pins, bedrock2/, compiler/, LiveVerif/, processor/, end2end/, ending in a merge commit so that fast-forwarding leaves the usual history. Absorbs #562 and supersedes #563; the Kami side is mit-plv/kami#51 (pinned at its merge commit, like coqutil and riscv-coq).

What changed in substance: Semantics defines slu, sru, srs (shift amount masked to the bitwidth), ltu, lts and mulhuu, with the shift-amount lemmas next to them (rupicola's copies go away in mit-plv/rupicola#226); divu/modu are the stdlib operations (their by-zero results are the RISC-V ones, so riscv_ok is gone); ZnWords restates its table on the stdlib lemmas; the conversion notations /[x] and \[x] take their width from a WordWidth class hole resolved through the Bitwidth instance in scope, so statements need no : word casts while the elaborated terms stay literally bits.of_Z width x / Zmod.unsigned x; a fold_pow2_moduli step at the entry of ZnWords, the zify tactics, bottom_up_simpl and the LiveVerif steps turns an evaluated power-of-two modulus back into 2 ^ k, replacing the per-file guards against evaluating 2 ^ width. processor/KamiWord.v is deleted (its Kami-side lemmas moved to Kami's Word.v), the Bitwidth instance there is file-local, and the two End2EndPipeline arithmetic goals clear the Kami hypotheses before lia instead of going through helper lemmas. Print Assumptions end2end_lightbulb lists the same 8 axioms as master; admits unchanged; no file slower than 1.3x.

Two judgment calls for review:

  • Word constants in specifications are bits.of_Z _ k (or /[k]), not the numeral notation from coqutil#187, because expr.literal k evaluates to bits.of_Z width k and spelling spec constants as Zmod.one broke seven example proofs on syntactic matching. Zmod.zero/Zmod.one appear only as comparison results.
  • processor/ keeps the width as a named constant, Definition width : Z := 32, and derives nwidth := Z.to_nat width per file, so that riscv-coq's generic code (which takes the width from the section variables' types) and typeclass resolution produce the same bits (Z.of_nat nwidth) syntactically; KamiRiscvStep.v adds a file-local Arguments Z.to_nat : simpl never next to its existing Z.pow/Z.of_nat lines, because one cbn computing Z.to_nat width while another does not made the eval_decodeI proof loop. Details in the processor commit message.

Written by Claude Fable 5.1.

🤖 Generated with Claude Code

https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm

@andres-erbsen

Copy link
Copy Markdown
Contributor

What is holding up porting the rest of the repository?

@JasonGross

Copy link
Copy Markdown
Contributor Author

Nothing structural; it is the long tail. LiveVerif is at 55 of 57 files: what remains is critbit.v (its bit_at lemmas are being restated on the masked shift amount that interp_binop now spells out, \[- i + 31] mod 2 ^ 5, and it is the slowest file to iterate on) and the umbrella LiveVerif.v behind it. processor/ and end2end/ have not started; they take the Kami side from #562 and should be mechanical. The core commit will also be rewritten once more with two ZnWords fixes found by the fiat-crypto port (the disequality case in word_eqs_to_Z_eqs never fired, and the mod-free bitwise lemmas lost the range facts lia needs) and the ArrayCasts lemmas that leaked a width implicit. rupicola#226 and fiat-crypto#2445 are already green against the current tip, so once these land the whole chain gets re-pinned. I expect to push LiveVerif and the core rewrite today and processor/end2end after.


Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm).

@andres-erbsen

Copy link
Copy Markdown
Contributor

prioritize end2end, treat LiveVerif as a background task

@JasonGross

Copy link
Copy Markdown
Contributor Author

Done: processor/end2end are now being ported on their own lane against the current tip, and critbit continues in the background.


Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm).

Comment thread bedrock2/src/bedrock2/bottom_up_simpl.v Outdated
(found = /[1] -> P) ->
found = /[0] ->
/[0] = /[1] -> P.
(/[0] : word) = /[1] -> P.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please find a fix that does not need to add the : word casts at conversion notations. One idea: maybe the notations should be resolved by looking up the BitWidth typeclass?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Working on it. The port added 116 : word casts (50 at /[..]/\[..] sites) because the notations elaborate to bits.of_Z _ x and nothing fixes the modulus when there is no expected type. Probing your idea now: a notation whose width is found by resolving Bitwidth ?w, so that the elaborated term is still literally bits.of_Z width x (syntactic matching against expr.literal's value is what the rest of the port relies on) and the casts can all go.


Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 8a50706: the conversion notations now take their width from a hole of a class type WordWidth (a name for Z) that a Hint Extern resolves through the Bitwidth instance in scope when elaboration leaves it open; unification with the surrounding types still fills it first. The hole is the width rather than the modulus so that a plain modulus evar (an implicit of a Zmod operation) cannot absorb it, and _ :> WordWidth leaves no cast node, so the elaborated terms are exactly bits.of_Z width x and Zmod.unsigned x, the same as the semantics produce. All 50 casts at conversion notations are gone, and 31 binder types that only existed to give \[x] its modulus are back to their pre-port untyped form; two compiler binders keep a type because the statement needs it before any notation could fix it. Wrapper definitions and tactic-driven holes were tried first and rejected (a wrapper breaks syntactic matching against expr.literal's value; a tactic hole runs before the expected type is known and lets the instance beat it).


Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm).

eexists; split; cbv [expr expr_body localsmap get].
{ rewrite ?Properties.map.get_put_dec. eexists; cbn; split; reflexivity. }
rewrite !word.unsigned_ltu.
idtac.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why is this idtac here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A leftover placeholder from removing rewrite !word.unsigned_ltu. there. Removing it, and sweeping the whole diff for other no-op leftovers of the same kind.


Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed, together with the five other placeholders of the same kind the port had left (LiveRules.v twice, LAN9250.v twice, FlatToRiscvCommon.v once); the remaining idtac lines in the diff are pre-existing or meaningful (intuition idtac, a default match arm, progress (idtac; ...)). No other leftover no-ops found.


Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm).

@JasonGross
JasonGross force-pushed the fable/bits branch 3 times, most recently from a6393bd to c07250b Compare September 16, 2026 08:16
@JasonGross
JasonGross marked this pull request as ready for review September 16, 2026 08:16
Comment on lines +19 to +20
(* A power that is the modulus of a word type is left alone: the word tactics
match it syntactically. *)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this really necessary? could the tactics be appropriately generalized instead, either to support non-power-of-two modulus or to recognize an evaluated power of two, whichever is easier?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not necessary in principle: it exists only because the word tactics match the modulus syntactically as 2 ^ w, so anything that evaluates it to a literal (here the constant folding in this test file, elsewhere simpl/cbn) takes the goal out of their reach. Generalizing the recognizer to accept an evaluated power of two (a closed literal m with 2 ^ Z.log2 m = m) in ZnWords, unzify, bottom_up_simpl and the LiveVerif side-condition tactics is the easier direction; doing that now, and then removing this guard and the other workarounds of the same origin across the PR (the file-local Arguments Z.pow : simpl never lines, the change 4294967296 with (2 ^ 32) steps and similar).


Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done (landing with the next push): one recognizer, fold_pow2_moduli, runs at the entry of ZnWords, the zify tactics, bottom_up_simpl and the LiveVerif steps; it turns any word modulus that has been evaluated to Z.pow_pos 2 p or to a literal m with 2 ^ Z.log2 m = m back into 2 ^ k in that hypothesis or goal (about 6 ms on a 200-hypothesis context). With it, this guard, its twin in PrintSmt.v, 26 of critbit's 36 cbn -[Z.pow] and two other workarounds are removed. What stays, with reasons in the commit message: groundcbv's power-of-two case (folding back after it costs 3.4 s per call in FlatConstMem), one file-local Arguments Z.pow : simpl never in insertionsort.v (a list-arithmetic shape, not a modulus issue), and ten cbn -[Z.pow] in critbit where the next step is a hand-written \[k] or a syntactic destruct/subst on a term that must still occur verbatim before any word tactic runs. Arbitrary moduli would have meant restating every lemma table at Zmod m and giving lia the width separately, so recognizing evaluated powers of two was the easier direction.


Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm).

Comment thread processor/src/processor/KamiProc.v Outdated
Comment on lines +222 to +224
(* Kami's word type is indexed by [nwidth], so [Z.of_nat nwidth] is the width
every word-typed term elaborates to; the instance is stated at that spelling. *)
#[global] Instance BW: Bitwidth (Z.of_nat nwidth) := {| width_cases := or_introl eq_refl |}.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you sure we need this instance? And does it really need to be global?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Measured: needed, but not globally. riscv-coq's MachineWidth (bits ?w) instance is resolved before ?w is unified with the processor's word, so with only coqutil's Bitwidth 32 in scope run1's arithmetic elaborates at 2 ^ 32 while every Kami-side term is at 2 ^ Z.of_nat (Z.to_nat width), and the first MMIO-contradiction lia in KamiRiscvStep.v (and everything after it) fails with the instance deleted. #[export] is also wrong: once activated by Import it wins for Context (spec: ProgramSpec) in End2EndPipeline.v, which then disagrees with the compiler's initial_conditions at Bitwidth 32. So it becomes a plain Definition in KamiProc.v with #[local] Existing Instance in exactly the two files whose statements do that resolution (KamiRiscvStep.v, KamiRiscv.v); Consistency.v and end2end see no instance. Spelling the processor's word as bits 32 instead was tried and is worse: every Kami lemma is keyed on 2 ^ Z.of_nat ?sz, which never unifies with the literal, so each of the ~40 Kami rewrites would need (sz := 32%nat) plus a change at every riscv-side boundary. Landing with the current round.


Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm).

Comment thread processor/src/processor/KamiWord.v Outdated
@@ -1,598 +1,116 @@
Require Import Coq.ZArith.ZArith Coq.ZArith.BinIntDef Coq.ZArith.BinInt coqutil.Z.Lia.
Require Import coqutil.sanity coqutil.Tactics.forward coqutil.Word.Interface. Import word.
Require Import Coq.ZArith.ZArith.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be nice if we could get rid of this file entirely now that bedrock2 and kami use the same word type. For each lemma, first investigate its usages and see if the lemma could be disposed of. If the lemma is still needed, consider whether there would be a better place to put it -- either at a standard location, to be reusable, or next to the usages.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Auditing the 13 remaining lemmas by use site now: what is trivial once both sides are bits (Z.of_nat n) gets inlined at the use, what is genuinely about Kami's wordToN/split/combine/weq goes into kami#51's Word.v, and anything used by one file moves next to it, with the goal of deleting the file. The Bitwidth instance question above gets answered by measurement in the same round.


Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done: the file is gone. Of its 13 lemmas, two were disposable (weqb_eqb holds by the definition of Zmod.eqb; unsigned_split1_mod is three stdlib rewrites at its sites), two are local to KamiRiscvStep.v (instances of the others), and the seven genuinely about Kami's own operations (Z_of_N_wordToN, wordToN_split1/2, wordToN_eq_rect, split1_wplus_silent, if_weq_eqb, Z_of_N_wordToN_combine) now live in kami#51's Word.v next to their relatives; the processor pins that. Landing with the current round.


Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm).

Comment thread end2end/src/end2end/End2EndPipeline.v Outdated
(* Stated on its own rather than discharged inline: Kami's Word.v registers
ZifyNat/ZifyN globally, so inside the [end2end] proof below [lia] translates
every [nat] and [N] hypothesis of a very large context, and the certificate
it builds there overflows the kernel stack at [Qed]. *)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

double-check that this is still accurate and consider whether there is a more straightforward workaround

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checking: whether kami#51's Word.v still registers the zify instances globally (if so, making them non-global there is the straightforward fix and this lemma goes back inline), and whether a clear before lia or a Z-only statement is enough otherwise. Will report with the measurement.


Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked. The effect is real but the attribution was off: Kami's Word.v Requires stdlib's ZifyNat/ZifyN, whose registrations are global by design (its own Op_Npow2 is not the cost), so inside end2end lia translates every nat/N hypothesis of the large context; reproduced with the lemmas inlined: both lia calls succeed and Qed then dies with "Stack overflow" after 24 minutes at 6.5 GB. The straightforward fix is clear - the four bounds before lia at the two sites; the standalone lemmas and the comment are gone. No Kami change needed.


Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm).

@andres-erbsen andres-erbsen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Make sure that pull requests to submodules of fiat-crypto (or their submodules) already include include a merge commit, unless the entire PR is just one commit or no adaptations to parent repositories are needed. This is so that fast-forwarding all submodules at once leaves the expected git history.

@JasonGross

Copy link
Copy Markdown
Contributor Author

Understood on the merge commits: every multi-commit submodule PR in this stack now ends in a merge commit (first parent the current master, second the series), and each downstream pin will point at that merge commit, so fast-forwarding all submodules leaves merge history. coqutil#187, riscv-coq#54 and quartz#2 are done; bedrock2#565, rupicola#226, kami#51/#53 and quartz#3 follow when their current review rounds land.


Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm).

JasonGross and others added 7 commits September 16, 2026 20:41
…he word type

coqutil e9309319 (coqutil#187) deletes Word.Interface and Word.Naive,
represents machine words as the stdlib type `bits width` (Zmod (2^width)),
and drops the lemmas and modules that the standard library already provides
(among them coqutil.Z.div_mod_to_equations; the tactic Z.div_mod_to_equations
comes from Lia). riscv-coq 44fc5b8c is the corresponding riscv-coq tip, and
kami 9217329e (kami#51) represents its words as the same stdlib type and
provides the transport lemmas the processor proofs use. bedrock2 follows in
the next commits.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm
coqutil no longer has a word interface: the word type is `bits width` from the
stdlib. Sections keep the name `word` as a local notation for `bits width`, the
`word.ok` hypotheses disappear, and `Bitwidth width` is the only assumption left
about the width. Operations are the stdlib ones (Zmod.add, Zmod.udiv, ...) and
lemmas are the stdlib lemmas or the few that coqutil's Word.Properties keeps.

Semantics: the stdlib shifts take an unmasked Z amount, so the language-level
masking of shift amounts is written out in interp_binop
(`Zmod.slu a (Zmod.unsigned b mod 2 ^ Z.log2 width)`); mulhuu is written out as
`bits.of_Z width (unsigned a * unsigned b / 2 ^ width)`; divu/remu are
Zmod.udiv/umod, whose behaviour on a zero divisor is the RISC-V one; the
comparison operators return Zmod.one/Zmod.zero.

Word constants in specifications and lemmas are spelled `bits.of_Z _ k` (or
`/[k]` with WordNotations), which is the term `expr.literal k` evaluates to, so
that program-derived terms and specification terms agree syntactically.
Zmod.one/Zmod.zero appear only as the boolean results of comparisons.

ZnWords restates its lemma table on the stdlib lemmas, matches
`@Zmod.unsigned (2 ^ ?w) _` to find word-valued subterms, and eliminates
Z.smodulo through coqutil's bridge lemma. bottom_up_simpl, unzify and
WordPushDownLemmas match the stdlib heads; the `unsigned zero`/`unsigned one`
cases are handled by their own rules. WordNotations binds ^+, ^-, ^*, ^<<, ^>>
to the stdlib operations.

groundcbv leaves a bare power of two alone: it is the modulus of the bits
types and the stdlib lemmas are stated with `2 ^ n`, so evaluating it would
only stop them from matching. With the word operations now transparent,
MetricSemantics' `firstorder` unfolded through them (2.4 s); the goal is closed
directly instead.

Zmod.unsigned and Zmod.signed are `simpl never` globally in coqutil's
Bitwidth.v; bedrock2/ needs no further simpl control.

ZnWords keeps word disequalities as disequalities on the unsigned values, and
its bitwise rules use the [mod m] forms (stdlib's Zmod.unsigned_and, and
unsigned_or_modwrap/unsigned_xor_modwrap in WordPushDownLemmas) so that
Z.div_mod_to_equations gives lia the range of the result, as it did for
word.wrap; Zmod.not uses bits.unsigned_not', whose `Z.ones n - x` is linear.
ZnWordsTests covers both points with 64-bit goals.

lia saturates on the `2 ^ width` inside the map.ok section hypothesis, so a
lemma proved with lia in a section with the word parameters acquires an
implicit width its statement does not mention. ArrayCasts keeps its byte and
list material in a section without those parameters, with the simpl settings
as file-level Local Arguments.

LiveVerif's framework support: HeapletwiseAutoSplitMerge's @array patterns
take the current implicit-argument count, tweak_tacs' swap takes open_constr
so that /[0] resolves against the hypothesis, and unzify's get_bitwidth also
finds the width from any Zmod (2 ^ w)-typed hypothesis or goal (LiveVerif's
Bitwidth instance is global, not a hypothesis).

Rocq master ignores non-reference terms in `using` clauses, so FlatConstMem
applies map.adjacent_arrays_disjoint directly instead of passing an applied
term to `auto using`.

Z.div_mod_to_equations, Z.testbit_mod_pow2 and Z.testbit_ones are the
standard library's; coqutil 8b40a6c1 has no copies of them, so nothing
requires coqutil.Z.div_mod_to_equations.

WordNotations resolves the width of /[x] and \[x] through Bitwidth: the
width is a hole of the class type WordWidth (a name for Z), filled by
unification like any hole, and a hole still open at the end of elaboration
is resolved through the Bitwidth instance in scope to the literal width; so
the notations need neither an expected type nor a `: word` ascription. The
hole is the width rather than the modulus so that a plain modulus evar (an
implicit argument of a Zmod operation) unifies with the application 2 ^ ?w
instead of absorbing the hole, and `_ :> WordWidth` ascribes the type
without a cast node, so the elaborated terms are exactly bits.of_Z width x
and Zmod.unsigned x, as the semantics produces them. Printing is unchanged.

The word tactics recognise a modulus by its shape 2 ^ w, and simpl, cbn,
injection and cbv evaluate a closed one to Z.pow_pos 2 p or a literal;
fold_pow2_moduli (FoldPow2Moduli.v) folds such moduli back in the
hypotheses and the goal (by change, so that the dependent types of the
variables follow) and runs at the entry of ZnWords_pre, zify_goal,
zify_hyps and bottom_up_simpl_in_goal/_in_hyp, so that a plain cbn or
simpl before a word tactic is harmless. groundcbv still leaves a bare
power of two alone: FlatConstMem's simpl_lengths matches the modulus
right after it, and folding back there costs seconds per call.

Semantics names the shifts and the comparisons of the language (slu, sru,
srs with the masked amount; ltu, lts as booleans on unsigned and signed)
and interp_binop uses them, so that downstream code can state and reify
against these heads rather than the inline lambdas; the constant-amount
lemmas unsigned_slu_shamtZ, unsigned_sru_shamtZ, signed_srs_shamtZ and
shamt_small live next to them. The five carry the simpl hint (Arguments
... /) so that simpl and cbn expose the masked amount and the Z
comparison as the program logic's automation expects, and the restricted
cbn/cbv lists that unfold interp_binop name them too.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm
The word type is `bits width`; the `word.ok` and `word.riscv_ok` hypotheses
and NaiveRiscvWordProperties.v are gone. RiscvWordProperties.v keeps the three
lemmas that relate riscv-coq's spelling of mulhuu, divu and remu (with their
zero-divisor tests) to bedrock2's semantics; the zero-divisor cases are now
the stdlib's Zmod.udiv_0_r and Zmod.umod_0_r.

Places that depended on the abstract word instance:
- riscv-coq's shift-immediate instructions shift by the raw immediate, while
  the source semantics masks the amount; the two agree because the compiled
  instruction is valid only for amounts below the bitwidth, which
  `shift_imm_range` extracts from the ptsto_instr clause.
- `simpl` on an `execute` term now reduces `Zmod.eqb` to a match on the
  representation, which `simulate'` does not recognise; RunInstruction.v and
  FlatToRiscvFunctions.v make Zmod.eqb `simpl never` locally, the only two
  files whose automation needs it.
- `lia` saturates on the `2 ^ width` that `map.ok mem` now exposes, so width-
  free lemmas inside a section with a `Bitwidth` context acquire a `width`
  parameter nothing can infer at `eapply`; Spilling.v's max_var lemmas move
  above that context, and Pipeline's `exec` applications lose the word
  argument.
- coqutil's solve_word_eq no longer calls simpl, so the few proofs that relied
  on it to unfold framelength, List.app or a Let-bound instruction list do so
  explicitly.
- MMIO's register names come from the reg_class equation rather than from
  automatically generated names.

GoFlatToRiscv and MMIO use the standard library's Z.div_mod_to_equations;
coqutil 8b40a6c1 has no copy of it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm
The word type is now stdlib's bits, so the framework's patterns and the
examples follow the ops and lemma names of coqutil's fable/bits, and the
Bitwidth instance for the examples is a global instance rather than a
section hypothesis (LiveVerifBitwidth.v).

Points that needed more than renaming:

- Standalone word constants in statements need a type ascription
  (`(/[k] : word)`, `\[(/[k] : word)]`): the modulus of `Zmod.of_Z` is
  only inferred from a typed position.
- `simpl`, `cbn` and `injection` reduce the `2 ^ 32` modulus in word
  types to `Z.pow_pos 2 32`, after which the word tactics and even
  `rewrite` no longer recognise the terms; those calls become
  `cbn -[Z.pow]`, `cbn [f]`, or an `assert ... by congruence`.
- critbit's `bit_at` masks its shift amount like the semantics does
  (`(bw-1 - i) mod 2 ^ log2 bw`); the `bit_at_step` rules only match
  the normalised amount shapes, because matching the raw program term
  makes unification reduce closed word arithmetic (an exponential
  blow-up through the stdlib bounds checks).
- Auto-generated hypothesis names changed (the word type is `Zmod`, so
  `r`, `r0` became `z`, `z0`); proofs that relied on them bind the
  variable explicitly.
- PrintSmt/SampleSideconds: the SMT export filters the Bitwidth
  instance, spells unsigned comparison with `Z.ltb`, and leaves the
  moduli of word types alone when evaluating constant powers.
- The bits 32 ring comes from coqutil, so SampleSimpls' own Add Ring
  is gone.

The coqutil pin 8b40a6c1 removed List.compare, List.assoc_app_cons and
bitblast.Z.testbit_ones_nonneg; the examples use the standard library's
ListDef.list_compare, List.app_assoc and Z.testbit_ones_nonneg instead.
In insertion_sort the app_assoc instance is posed with the cons-shaped
type it is convertible to, so that `rewrite in *` still instantiates it
per hypothesis; note that `[x]` is the list-indexing notation in
LiveVerif, not a singleton list.

step and steps fold evaluated word moduli back (fold_pow2_moduli) before
doing anything, so the examples use plain cbn and the SMT tests'
eval_constant_pows no longer spares the moduli. Ten cbn -[Z.pow] stay
in critbit, where a hand-written \[k] or a syntactic step (destruct,
subst, match on a hypothesis, rewrite in) follows the cbn before any
word tactic could fold the moduli back.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm
Kami's word n is the standard library's bits (Z.of_nat n) and the
processor's machine word is bits 32, so nothing here needs a word
instance any more: the KamiWord.word record, its ok proof, the wordW
instance, the Spelling lemmas and the kunsigned/kofZ/ksigned wrappers
are gone, and KamiWord.v keeps only the lemmas that carry Kami's
unsigned_* specification over to the wordToN, split1/split2 and combine
spellings the processor proofs meet.

The machine word is spelled bits (Z.of_nat (Z.to_nat width)), with
width the Z definition 32 that KamiProc always had: this is what
riscv-coq's generic code produces when its bits width is instantiated
from the types of the section variables, and the Bitwidth instance is
stated at the same spelling so that typeclass resolution (which fixes
the width from the instance) and type-driven unification agree. Any
second spelling of the same modulus is fatal in KamiRiscvStep.v, whose
tactics compare terms syntactically: lia, destruct ... in *, and the
folding of Z.of_nat literals in the kitchen-sink tactics. Two
alternatives were tried and rejected. With width := Z.of_nat nwidth
(nwidth := 32), that folding rewrites the modulus of every word,
section variables included, to 2 ^ 32, after which Kami's lemmas keyed
on 2 ^ Z.of_nat ?sz no longer unify and fetch_ok silently fails inside
its try. With Word.word nwidth as the type, riscv-coq's map.get and the
processor's map.get of one register read are two syntactically different
terms and destruct splits them into two variables.

KamiRiscvStep.v additionally declares Z.to_nat simpl never, next to its
existing Z.pow and Z.of_nat lines: cbn in decodeI computed
Z.to_nat width inside the let-bound decoder while the hypotheses derived
from it earlier still read Z.to_nat width, so destruct (Z.eqb_spec ..)
in * no longer reached the body and eval_decodeI's repeat loop ran for
ten minutes without terminating. Kami's own kinds (Bit 32, Bit
BitsPerByte) still cbn to unary literals, so BitsPerByte is excluded
from the literal folding, the folding covers let-bound bodies as well as
hypotheses, and the load-value blocks rewrite unsigned to wordToN by the
word's type rather than by unifying its modulus. The remaining
alignments are at the places the old proof also aligned: Kami-side
terms carry Pos.to_nat 32 after its cbv and are changed to nwidth before
the MMIO contradictions; lui/auipc change Z.of_nat nwidth to 32 before
their lia; unsigned_of_Z is rewritten at syntactic occurrences only
because a bare rewrite sees through Kami's combine (an of_Z after one
unfolding); signExtend and the bitSlice range facts are stated at the
Z.of_nat nwidth spelling. riscvMemInit_get_None takes its pair equality
apart with pair_equal_spec, since inversion and injection simpl the
components and compute the modulus. wordToN_bound at Word.word rv32RfIdx
gives Npow2 rv32RfIdx.

coqutil 8b40a6c1 states bitSlice_alt in division form, so the
bitSlice' unfoldings after it are gone. Statements are unchanged up to
the rename; admits are unchanged.

KamiProc's Bitwidth (Z.of_nat nwidth) is a plain definition now, made an
instance only in KamiRiscvStep.v and KamiRiscv.v, the two files whose
statements resolve riscv-coq's MachineWidth (bits ?w) for the
processor's word. That resolution happens before ?w is unified with the
word, so it is the instance that decides the spelling of every modulus
in the riscv arithmetic of run1.

Measured on c07250b, processor/ and end2end/ from clean each time. With
no instance, Consistency.v still compiles (its statements get the width
from the word type by unification) but KamiRiscvStep.v fails at the
first MMIO-contradiction lia in execLd (line 1730) and in every later
case: coqutil's Bitwidth 32 is the only candidate, ?w becomes 32, the
riscv side of run1 comes out at 2 ^ 32 (Hlv) while every Kami-side term
is at 2 ^ Z.of_nat (Z.to_nat width) (Heqic), and lia sees two atoms.
With an export-scoped instance, processor/ builds but End2EndPipeline.v
fails at line 371: activated at Import, the instance is tried first for
Context (spec: ProgramSpec), spec is elaborated at
Z.of_nat (Z.to_nat width), the compiler's initial_conditions hypothesis
has datamem_start at 32, and rewrite heap_start_agree in H no longer
applies. The global instance only worked because it was tried after
Bitwidth 32 there. Consistency.v and end2end see no instance now, and
end2end elaborates spec at the compiler's own width as before. Same 8
axioms, admits unchanged, times unchanged (KamiRiscvStep 494 s).

bedrock2 and Kami use the same word type now, so the file had shrunk to a
dozen transport lemmas, and each has a better home. Two are disposable:
Zmod.eqb is Z.eqb on unsigned by definition, so weqb_eqb was reflexivity,
and unsigned_split1_mod's three sites rewrite with wordToN_split1,
N2Z.inj_mod and Z_of_N_Npow2 instead. Seven state facts about Kami's own
wordToN, split1/split2, combine, eq_rect, wplus and weq and are now
provided by Kami's Word.v (Z_of_N_wordToN, wordToN_split1,
wordToN_split2, Z_of_N_wordToN_combine, wordToN_eq_rect,
split1_wplus_silent, if_weq_eqb; kami#51 at 9217329e), so their copies and the
Z_pow_add_lor helper behind the combine lemma go. The two that remain,
sumbool_rect_bool_weq and unsigned_eqb, are about the shapes
KamiRiscvStep.v's own tactics produce and are local to that file.
Admits are unchanged.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm
Bedrock2SemanticsForKami keeps only the memory map instance, since the
word and its ok and riscv_ok instances have no counterpart on bits;
KamiRiscvWordProperties.v goes with them. The compiler-facing side stays
at bits 32 and meets the processor's bits (Z.of_nat (Z.to_nat width)) by
conversion, as the two instances did before.

In end2end's memory-layout cancellation the generic cancel no longer
pre-matches any pair, because the addresses differ in that width
spelling, so each of the four pairs gets its own step: the instruction
pair is convertible, the unused-instruction pair needs only
simpl_word_exprs, and the heap pair needs its length arithmetic, stated
on its own as imem_heap_lengths for the same reason as
imem_heap_stack_lengths (lia over the whole context overflows the
kernel stack at Qed). lightbulb_spec's goodHlTrace and OP take no word
argument any more. RelyNotations writes its demo words as bits 32.
Print Assumptions end2end_lightbulb lists the same 8 axioms as before.

The two length lemmas stated on their own for lia's sake are gone; the
goals are proved in place after clearing everything but the four bounds
they need. Requiring Kami's Word.v loads stdlib's ZifyNat and ZifyN (no
other dependency does), whose registrations are global by design, so lia
inside the end2end proof translates every nat and N hypothesis of the
whole context; with the context cleared the two calls take well under a
second and End2EndPipeline.v compiles in 10 s, whereas with the two calls inlined
over the full context the file ran 24 minutes at 6.5 GB and then Qed of
end2end failed with a stack overflow. Kami's own
Op_Npow2 registration could be made local, but it is not what costs
here.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm
Use stdlib bits as the word type throughout bedrock2 (coqutil#187, riscv-coq#54, kami#51).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm
JasonGross added a commit to JasonGross/bedrock2 that referenced this pull request Sep 16, 2026
Simulate the processor regenerated from Kami's Bluespec output (kami#54), on top of the stdlib bits port (mit-plv#565).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm
Comment on lines +69 to +70
Definition ltu (a b : word) : bool := Z.ltb (Zmod.unsigned a) (Zmod.unsigned b).
Definition lts (a b : word) : bool := Z.ltb (Zmod.signed a) (Zmod.signed b).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In a follow-up PR, inline and remove these definitions (just ltu and lts). Or is that a really bad idea?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tried it in a scratch tree (bedrock2 with ltu/lts inlined, rupicola re-keyed on Z.ltb (Zmod.unsigned _) (Zmod.unsigned _) / Z.ltb (Zmod.signed _) (Zmod.signed _)). Workable, but it has real costs, so I would keep the two definitions:

  • Without a head symbol, a word comparison is distinguished from a Z comparison only by the shape of its operands. \[a] <? \[b] still compiles to expr.op ltu, and a pure-Z z <? 3 still takes the Z lemma, but \[a] <? 5 makes the Z lemma fire and leaves DEXPR ?e (bits.of_Z _ (Zmod.unsigned a)) unsolvable, and \[a] <? \[b] + 1 matches nothing; today ltu a 5 and ltu a (b + 1) compile.
  • A comparison against a numeral loses its modulus: Z.ltb (Zmod.unsigned (bits.of_Z _ 11)) (Zmod.unsigned idx) elaborates with an unresolved 2 ^ ?y, and the Compute in rupicola's Examples/Loops.v then hangs in vm_compute instead of failing; Utf8's 0x10FFFF <w c / c3 >w 1114111 need an explicit width. With the width spelled out at those three sites everything builds and the generated programs are byte-identical.
  • The definitions cost nothing on the bedrock2 side: Arguments ltu / already gives simpl/cbn the inline form, and bedrock2's own references are all in unfold lists. Diff for the inlining would be 10 rupicola files (+28/-28) plus three unfold lists in bedrock2; no lemma is lost.

Inlining only one of the two has the same issues for that operator (ltu: 14 rupicola sites plus the three numeral sites; lts: 12 sites, none against a numeral). Happy to do it as a follow-up anyway if you prefer the smaller Semantics.


Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm).

@andres-erbsen
andres-erbsen merged commit 24b234f into mit-plv:master Sep 17, 2026
5 checks passed
@andres-erbsen

Copy link
Copy Markdown
Contributor

Please investigate usage of Semantics and LeakageSemantics (and other Leakage- files) throughout the repository and present a plan and considerations for using Leakage-aware specificaitons for fiat-crypto GarageDoor.v and all bedrock2 functions transitively called from there.

@JasonGross

Copy link
Copy Markdown
Contributor Author

Leakage-aware specs for GarageDoor: inventory, plan, considerations.

Status

  • bedrock2's leakage stack is complete from semantics to RISC-V: LeakageSemantics,
    LeakageWeakestPrecondition, LeakageProgramLogic, LeakageLoops, and
    Pipeline.compiler_correct(_wp), whose forall kH kL, exists f pick_sp, ... getTrace final = Some (f kH') is the constant-time statement for one call
    (compilerExamples/memequal.v).
  • The event-loop pipeline (ExprImpEventLoopSpec, ToplevelLoop, CompilerInvariant)
    threads leakage but discards it; the Kami refinement drops it. LiveVerif and Rupicola
    have none.
  • GarageDoor.v is already written in the leakage program logic (fiat-crypto #2009) but its
    specs say nothing about k'; of its 37 functions only memequal has a leakage spec.
    The rest are plain: 10 drivers, memswap/memconst/memmove, 7 Rupicola functions, 3
    wrappers, 9 generated fe25519 functions.
  • Audit result: every function is constant-time w.r.t. the secrets (seed, ephemeral key,
    shared secret). Generated field code is straight-line with literal shift amounts and
    pointer+literal addresses; the ladder reads scalar bits by counter-indexed loads and
    shifts; loop counts are constants or public. The only secret-derived branch is
    if (set0|set1) in loopfn, whose value is already on GPIO, so the spec declassifies it
    through the I/O log.

Plan (leaves first)

  1. Fix the spec form: k' = f <public> ++ k with f before the secrets; for loopfn,
    K = f ioh k. T1 (per-iteration theorem) first, T2 (reactive) later.
  2. bedrock2 leaves: memswap/memconst/memmove like memequal; SPI/LAN9250 drivers and
    recvEthernet re-run their existing automation under LeakageProgramLogic with one
    align_trace goal per branch. Add a leakage-to-plain lemma so lightbulb keeps
    building. About 2 weeks.
  3. Generated field functions: one generic "straight-line constant-time" lemma with a
    vm_compute syntactic check, combined with the existing plain proofs via intersect.
    No change to the translation proofs. 1-2 weeks, reusable for all fiat-crypto outputs.
  4. Rupicola functions (montladder, cswap, inv, chacha20, ip_checksum): leakage-only proofs
    on the derived code, reusing the plain proofs. 1-2 weeks.
  5. Wrappers (x25519, x25519_base, clamp): 1-2 days. GarageDoor.v specs and loopfn_ok
    (650 lines, 7 branches): 1 week.
  6. Top level: T1 from compiler_correct_wp in days; T2 (getTrace = Some (LEAK getLog)
    as an event-loop invariant) needs compiler work: leakage in ProgramSpec, ll_good
    pinning the trace, a computable leakage predictor exposed from Pipeline. 3-4 weeks.

Considerations: loop leakage functions are hand-written; no leakage-to-plain lifting
exists yet; the statement stops at riscv-coq's leakage model, not the Kami processor; no
interaction with the stdlib-bits port.

Effort: 6-8 person-weeks to a per-iteration RISC-V constant-time theorem, plus 3-4
weeks for the reactive whole-loop theorem.

Full report

Follow-up F: leakage-aware specifications for GarageDoor

Request: Andres Erbsen, #565, 2026-09-17 06:02Z. "Investigate usage of
Semantics and LeakageSemantics (and other Leakage- files) throughout the repository and
present a plan and considerations for using Leakage-aware specifications for fiat-crypto
GarageDoor.v and all bedrock2 functions transitively called from there."

Sources read (read-only clones, after the stdlib-bits port):

  • bedrock2 447b97d (/data/jason/fiat-crypto-worktrees/wp-j3/bedrock2)
  • fiat-crypto a5ee22098 (/data/jason/fiat-crypto-worktrees/wp-f1/fiat-crypto)
  • rupicola 4764adf (/data/jason/fiat-crypto-worktrees/wp-f1/rupicola)

One measurement was compiled in scratch (/data/jason/fiat-crypto-worktrees/fu-f/sizes.v)
against the built fiat-crypto clone: statement counts and control-flow counts of every
function in GarageDoorTop.funcs. Nothing was edited, pushed, or posted.

1. Inventory of the leakage machinery in bedrock2

Dates from git log: the leakage files were added 2024-08/09 (Owen Conoly's leakage work),
the compiler pipeline became leakage-aware 2024-11, SemanticsRelations.v 2025-01, and all
of them were touched last on 2026-09-16 by the stdlib-bits port (wp-j3). Everything below
builds and is exercised by bedrock2 CI, so the definitions and the compiler theorem are
mature; the proof automation is usable but thinner than the plain program logic (see 4).

Semantics layer

File (LOC) What it provides Maturity
bedrock2/src/bedrock2/LeakageSemantics.v (424) leakage_event = leak_unit/leak_bool/leak_word/leak_list (l.48); ExtSpec whose postcondition also receives the leakage list of the external call (l.58); PickSp := leakage -> word, the stack-pointer oracle for stackalloc (l.101); leak_binop: divu/remu leak both operands, slu/sru/srs leak the shift amount, everything else leaks nothing (l.113); eval_expr leaks every load and inlinetable address and the branch of expr.ite (l.134); exec leaks leak_word a on store, leak_unit on stackalloc and call, leak_bool on cond/while, leak_list klist on interact (l.181); weaken, intersect, extend_env, call (l.274-424). align_trace tactic for trace equations (l.28). solid
MetricLeakageSemantics.v (564) Same with metrics; this is the semantics the compiler theorem is stated in. solid
SemanticsRelations.v (498) Lifts between the four semantics: leakage_to_plain_exec/call (plain proof gives a leakage proof that says nothing about k, l.290/342), metricleakage_to_leakage_* (l.154/182), deleakaged_ext_spec turning a leakage ExtSpec into a plain one (l.111). Gap: there is no leakage-to-plain direction (a LeakageSemantics.exec proof cannot currently be turned into a Semantics.exec proof); see 4. solid
FE310CSemantics.v (78) leakage_ext_spec: MMIOWRITE leaks [addr], MMIOREAD leaks [addr] (l.33); plain ext_spec := deleakaged_ext_spec (l.66). This is the ext_spec GarageDoor uses. solid
memory_mapped_ext_spec.v Same pattern for the newer memory-mapped ext-call model. solid

Program logic layer

File (LOC) What it provides
LeakageWeakestPrecondition.v (491) WP over (k, t, m, l); cmd_body mirrors the plain WP with leakage threaded (l.85); call is a notation for LeakageSemantics.call (l.143); fnspec! notations with requires k tr mem / ensures k' tr' mem', including the fnspec! exists f, ... form where f is quantified before the ghost variables (l.180-330).
LeakageWeakestPreconditionProperties.v (490) Proper_cmd/call/program, sound_cmd (WP to exec, l.286), complete_cmd (l.326), start_func, interact_nomem (l.381), dexpr_expr (l.440), intersect_expr.
LeakageProgramLogic.v (450) program_logic_goal_for_function! (l.69), straightline (l.252; same cases as the plain one plus LeakageLoops.enforce), straightline_call = `straightline_call_noex
LeakageLoops.v (599) Full parity with Loops.v: wp_while, tailrec, tailrec_localsmap, tailrec_localsmap_1ghost(_parameterized_finalpost), atleastonce(_localsmap), tailrec_earlyout(_localsmap), while(_localsmap), while_zero_iterations, tailrec_sep, loop_simpl.

Examples (bedrock2Examples)

File (LOC) Spec style Notes
memequal.v (189) fnspec! exists f, ... ensures k' := f x y n ++ k = k' (l.34) The model constant-time loop proof: hand-written recursive newtrace (l.45), LeakageLoops.tailrec with the leakage equation in the loop invariant (l.70). Already used by GarageDoor.
ct.v (409) k' = f k (div3329), vartime variant with explicit leakage (l.37), getline with a recursive leakage function (l.77), password_checker calling memequal (l.281), semiprime, maskloop Shows the intended forms. Two rough edges: Fail Lemma password_checker_ct ... (*Why*) (l.290, the callee instance must be Global), and "no leakage -- 3 minutes" for a two-line function (l.33: cbn on the leakage goal is slow; align_trace is the right tool).
swap.v (82), stackalloc.v (212) K = f a_addr b_addr ++ k swap_ok is repeat straightline. intuition eauto. align_trace.; stackalloc.v shows pick_sp handling.
kyberslash.v (489) nested loops with get_inner_leakage/get_outer_leakage Comment at l.169: leakage straightline does not unfold dexpr for loop conditions; manual steps needed.

LiveVerif and Rupicola have no leakage support at all (grep -ril leakage LiveVerif/src and
grep -rl LeakageSemantics rupicola/src are both empty).

Compiler

The whole pipeline is leakage-aware and proven:

  • compiler/src/compiler/Pipeline.v: Lang.Call carries pick_sp, k and a leakage
    postcondition (l.69); phase_correct relates source and target leakage through an
    existential k2'' per phase (l.78). compiler_correct (l.681) and compiler_correct_wp
    (l.763) are stated as forall kH kL, exists f pick_sp, forall t mH argvals post, ... runsTo ... final.(getTrace) = Some (f kH'). The quantifier order is the constant-time statement:
    the function f from source leakage to RISC-V leakage is chosen knowing only the public
    leakage history, before memory and arguments.
  • The source proof has to hold for the compiler-chosen pick_sp, so source specs must be
    proven for an arbitrary pick_sp (GarageDoor already does: Context {pick_sp: PickSp}).
  • The FlatToRiscv and Spilling phases have computable leakage predictors
    (FlatToRiscvDef.stmt_leakage l.758 / fun_leakage l.793, Spilling.stmt_leakage l.478 /
    fun_leakage l.559, MMIO.leak_ext_call l.137, riscv-coq Spec/LeakageOfInstr.v).
    Pipeline exposes them only as the existential f.
  • compiler/src/compilerExamples/memequal.v (134) is the model end-to-end statement for one
    call: exists finalTrace, forall Rx Ry xs ys m ... initial, ... runsTo initial (fun final => ... final.(getTrace) = Some finalTrace) (l.69), proven from memequal_ok and
    compiler_correct_wp in 35 lines.

Event loop (what GarageDoor actually uses)

  • compiler/src/compiler/ExprImpEventLoopSpec.v: hl_inv spec k t m l mc := isReady t m /\ goodTrace t (l.29) ignores k; ProgramSatisfiesSpec requires init/loop bodies to run
    under MetricLeakageSemantics.exec for every pick_spH (l.43-50).
  • compiler/src/compiler/ToplevelLoop.v: ll_good keeps only exists kL0, mach.(getTrace) = Some kL0 (l.151); at each iteration the proof calls compiler_correct, destructs f and
    pick_spH, and discards f (l.297-330, l.507-530).
  • compiler/src/compiler/CompilerInvariant.v: initial_conditions requires getTrace = Some nil (l.187); compiler_invariant_proofs / always_eventually_good_trace say nothing
    about leakage.
  • end2end/src/end2end/End2EndPipeline.v and processor/src/processor/KamiRiscv.v: the Kami
    refinement only requires getTrace = Some nil initially (KamiRiscv.v l.534); leakage is not
    related to the hardware. A leakage statement therefore ends at the riscv-coq ISA-level
    leakage model, not at the pipelined processor.

So: leakage is threaded through the event-loop pipeline but never stated. There is no
reactive (whole-loop) leakage theorem anywhere in bedrock2 today.

2. GarageDoor call graph and current spec styles

GarageDoorTop.funcs has 37 functions (4 loop wrappers, 10 driver functions, 3 stdlib,
3 Rupicola, 17 from MontgomeryLadder.funcs). The end-to-end theorem is
garagedoor_correct (GarageDoorTop.v l.365): always run1 (eventually run1 (fun mach' => io_spec mach'.(getLog))), obtained from compiler_invariant_proofs with garagedoor_spec
(l.179, goodTrace := io_spec, isReady = protocol state + memrep).

Important head start: GarageDoor.v is already written in the leakage program logic
(fiat-crypto commit 1c166e0, 2025-02-16, "switch GarageDoor to LeakageSemantics (#2009)").
GarageDoor.v l.123 imports LeakageSemantics LeakageWeakestPrecondition LeakageProgramLogic, l.136 has Context {pick_sp: PickSp}, spec_of_initfn (l.138) and
spec_of_loopfn (l.257) use requires k t m, and GarageDoorTop.v links through
metricleakage_to_leakage_exec + LeakageWeakestPreconditionProperties.sound_cmd (l.298).
But the two ensures clauses say nothing about k', every callee except memequal is
called through straightline_call_from_plain, and the event loop discards k.

Statement counts (measured; "stmts" = leaf commands; w/c/call/io = while / cond / call /
interact nodes):

Function Where defined / proven Spec style today stmts w/c/call/io Leakage character
init, loop GarageDoorTop.v wrappers 1 0/0/1/0 trivial
initfn GarageDoor.v l.56/148 leakage WP, no k' clause 5 0/0/2/3 public (MMIO addresses, constants)
loopfn GarageDoor.v l.64/272 (650-line proof) leakage WP, no k' clause 43 0/7/11/2 branches on pktlen/ethertype/protocol (public, from the packet); stackalloc 32 (address = pick_sp k); if (set0|set1) at l.106 branches on the authentication result, which was already written to GPIO at l.104 (declassified through the I/O log)
memequal bedrock2Examples/memequal.v leakage (f x y n) 7 1/0/0/0 done
memswap memswap.v (164) plain fnspec! 10 1/0/0/0 pointers + n
memconst_pk memconst.v (149) plain 5 1/0/0/0 pointer only
memmove memmove.v (399) plain (spec_of_memmove_array) 16 2/2/0/0 pointers + n (overlap test on pointers)
recvEthernet lightbulb.v (623) l.100/365 plain, hand-written WeakestPrecondition.call 23 1/5/3/0 depends on MMIO read values (in the log) and packet length
lan9250_tx LAN9250.v (901) l.749/771 plain fnspec! 12 1/3/3/0 length + MMIO values
lan9250_init, wait_for_boot, mac_write, writeword, readword LAN9250.v l.140-274 plain, hand-written 15/11/7/33/34 up to 8 conds, 4 interacts MMIO addresses + MMIO read values (error paths)
spi_xchg, spi_write, spi_read SPI.v (440) l.68-376 plain, hand-written 4/12/11 polling loops number of polls = length of the I/O segment (public)
ip_checksum rupicola Examples/Net/IPChecksum plain, Rupicola compile 26 1/1/0/0 pointer + wlen
chacha20_block, quarter RupicolaCrypto/ChaCha20.v (1933) l.438/461 plain, Rupicola 60/12 1/0/8/0, 0/0/0/0 fixed loop, pointers only
x25519, x25519_base End2End/X25519/MontgomeryLadder.v (294) l.81/121 plain fnspec!, hand proof with straightline_call 8/8 0/0/5/0 pointers only
clamp End2End/X25519/clamp.v plain 2 0/0/0/0 pointer only
montladder Group/ScalarMult/MontgomeryLadder.v (447) l.196 plain, Rupicola 23 1/0/11/0 loop of scalarbits iterations; scalar bit read as load1(pK + i>>3) >> (i&7) & 1 (l.250): address and shift amount depend only on the counter
ladderstep LadderStep.v (153) plain, Rupicola 20 0/0/18/0 pointers only
felem_cswap CSwap.v (592) l.473 plain, Rupicola 16 1/0/0/0 mask arithmetic, no branch on the mask
fe25519_inv AdditionChains.v (673) l.618 plain, Rupicola 16 2/0/10/0 fixed exponent chains
fe25519_mul/square/to_bytes/from_bytes/scmula24/add/sub/copy/from_word Field25519.v via derive_bedrock2_func, proofs = Translation/Proofs/* (5.4k LOC) applied through Synthesis/New/Signature.v plain spec_of_BinOp/UnOp/... (Specs/Field.v l.80-200) 684/463/285/134/109/55/55/44/26 0/0/0/0 straight-line; loads/stores at ptr + literal (Translation/LoadStoreList.v l.59/142); shifts only by literals (Translation/Expr.v l.73-90 require a literal shift amount); no divu/remu/inlinetable/ite

Secret data in GarageDoor: the 32-byte seed and 32-byte sk at ST (initially whatever
mem_available contains), the shared secret in the stackalloc buffer, and memory contents
generally. Public data: MMIO addresses, constants, pointers (fixed addresses ST/PK/BUF
plus pick_sp k), the packet bytes (they arrive as MMIO read values and are in the I/O
log), the GPIO read value, and the GPIO write value (which encodes set0/set1).
Conclusion of the audit: every function in the call graph is constant-time with respect
to the secrets, modulo declassifying the authentication bit through the GPIO write
; no
table lookups, no division, no secret-dependent addresses or shift amounts. The work is
purely to state and prove this.

3. Plan

The target statement, at the source level: for every function, k' = f <public data> ++ k
with f chosen before the secrets (the fnspec! exists f form). For loopfn, the public
data of an iteration is its I/O segment ioh (the existing protocol_step already exposes
it) plus k itself (through pick_sp), so the natural clause is K = f ioh k.

Order: leaves first, so that straightline_call picks up leakage specs instead of the
from_plain fallback.

Phase 0: fix the statement (1-2 days, design only)

Decide (a) the per-function spec form above, (b) how driver leakage is expressed (as a
function of the abstract I/O events ioh, which is what the existing driver specs already
quantify), (c) the top-level target: T1 (per-iteration RISC-V theorem, available with
today's compiler) first, T2 (reactive whole-loop theorem, needs compiler work) later.

Phase 1: bedrock2 leaves: stdlib and drivers (about 2 person-weeks, in bedrock2)

  • memswap, memconst, memmove: clone the memequal.v pattern (recursive leakage
    function + LeakageLoops.tailrec); 50-150 LOC each. memmove's two loops and two
    conds are on pointer comparisons.
  • spi_write, spi_read, spi_xchg: the poll loops leak one MMIOREAD address per poll,
    so the leakage function is indexed by the length of ioh (already constrained to
    patience in the error case).
  • lan9250_readword/writeword/mac_write/wait_for_boot/init/tx, recvEthernet: the existing
    proofs are repeat (straightline || straightline_call || split_if || ...) and should
    re-run under LeakageProgramLogic with one extra leakage-equation goal per branch,
    closed by align_trace. The leakage functions are case splits on err / on the ioh
    shape that the specs already enumerate. recvEthernet (1 loop, 5 conds, 3 calls) and
    lan9250_readword/writeword (7-8 conds, 4 interacts each) are the largest.
  • Add the missing helper plain_of_leakage_exec/call to SemanticsRelations.v (about 60
    LOC, same shape as plain_to_metric_exec) and a straightline_call variant that strips
    leakage, so lightbulb.v and other plain users of the drivers keep building when the
    drivers' specs become leakage specs. Otherwise lightbulb.v (623 LOC) has to be ported
    too.

Phase 2: generated field functions (1-2 weeks, fiat-crypto, reusable)

Three options; recommend A.

  • A. Generic straight-line constant-time lemma. Define a boolean check
    straightline_ct (public_vars) (c : cmd): no cond/while/stackalloc/interact; every
    load/store address expression and every shift amount is built only from public_vars
    and literals; no divu/remu/inlinetable/ite; public_vars are never assigned.
    Prove once: straightline_ct pv c = true -> exec c k t m l post -> exec c k t m l (fun k' t' m' l' => post k' t' m' l' /\ k' = leak_of c (restrict l pv) ++ k) with a computable
    leak_of. The check runs by vm_compute on each of the 10 fe25519_* bodies (the
    measured shapes above guarantee it passes). Combine with the existing plain
    fe25519_*_correct via leakage_to_plain_call and LeakageSemantics.exec.intersect
    (l.297) to obtain spec_of_BinOp-style leakage instances. About 300-500 LOC once, plus
    a 10-line lemma per field op; no change to the 5.4k-LOC translation proofs. Extending
    the check with cmd.call to callees whose leakage spec is pointer-only also covers
    ladderstep, quarter, x25519, x25519_base, clamp, and every other fiat-crypto
    bedrock2 output (P-256, P-384, ...).
  • B. Leakage-aware translate_func_correct: generalize Translation/Proofs/{Expr,Cmd,Func, LoadStoreList}.v and Synthesis/New/Signature.v from WeakestPrecondition to the
    leakage WP. 2-4 weeks, touches 5.4k LOC, and the Types.parameters plumbing over
    Semantics.ExtSpec (Field25519.v l.23). Only worth it if leakage is wanted for every
    future generated function without a post-hoc check.
  • C. Brute force repeat straightline on each generated body: fe25519_mul is 684
    statements; the existing pipeline never runs straightline over these bodies and
    ct.v reports minutes for two lines. Not recommended.

Phase 3: Rupicola-generated functions (1-2 weeks, fiat-crypto)

Rupicola has no leakage support (10.3k LOC library, zero hits). Recommend proving
leakage-only specs directly on the derived bedrock2 code with LeakageProgramLogic +
LeakageLoops, reusing functional correctness from the plain spec through
leakage_to_plain_call + intersect: montladder (1 loop, 11 calls), felem_cswap (1
loop), fe25519_inv (2 loops, 10 calls), chacha20_block (1 loop, 8 calls), ip_checksum
(1 loop, 1 cond); ladderstep and quarter are straight-line and fall under Phase 2A. A
leakage-only proof needs the loop counts (constants or public lengths) and the callees'
leakage specs, not the field arithmetic, so 100-300 LOC each. Adding leakage to Rupicola's
compile lemmas is a multi-month project and should only be considered if many more
Rupicola functions need constant-time proofs.

Phase 4: handwritten fiat-crypto wrappers (1-2 days)

x25519, x25519_base, clamp: port End2End/X25519/MontgomeryLadder.v and clamp.v to
LeakageProgramLogic (the proofs are straightline/straightline_call sequences; with
Phases 1-3 in place straightline_call finds leakage specs). Or cover them by Phase 2A.

Phase 5: GarageDoor.v (about 1 week)

Add K = f ioh k (initfn: K = f k) to spec_of_initfn/spec_of_loopfn. loopfn_ok is
650 lines with Optimize Heap checkpoints and 7 branches; each branch gets one
align_trace goal, plus the declassification argument that f reads set0/set1 from
the GPIO store event in ioh. link_loopfn/link_initfn in GarageDoorTop.v are
unchanged in shape. Expect proof-engineering friction from the size of the proof rather
than from leakage itself.

Phase 6: top-level theorem

  • T1 (2-3 days, no compiler change): a memequal_ct-style theorem for the compiled
    loopfn/loop as a single call, from compiler_correct_wp: forall kH kL, exists F, forall seed sk bs ... initial, ... runsTo initial (fun final => final.(getTrace) = Some (F (getLog final))), where F composes the compiler's f with the source f ioh k and
    mmio_trace_abstraction_relation. This says: one loop iteration's RISC-V leakage is a
    function of its I/O events and the leakage history, independent of all memory contents.
  • T2 (3-4 weeks, bedrock2 compiler work): a reactive statement, e.g. exists LEAK, always run1 (eventually run1 (fun mach => getTrace mach = Some (LEAK (getLog mach)))).
    Requires (i) a leakage component in ProgramSpec/hl_inv, (ii) ll_good to pin
    getTrace instead of exists kL0, (iii) either exposing a computable composed leakage
    predictor from Pipeline (the FlatToRiscv/Spilling ones exist; whether every phase's
    k2'' is computable must be checked) so that LEAK is definable, or a relational
    invariant proven functional on reachable states. This is the one genuinely open design
    question; the compiler's per-call exists f cannot be turned into one global function
    without choice.

Total: about 6-8 person-weeks to T1 (Phases 0-6/T1), plus 3-4 weeks for T2. Phases 1, 2,
and 3 are independent of each other and can run in parallel.

4. Considerations and risks

  • Automation gaps. straightline/straightline_call/LeakageLoops exist and mirror
    the plain ones, so straight-line and simple-loop proofs port mechanically. There is no
    automation to synthesize the leakage function of a loop; each loop needs a hand-written
    recursive function (newtrace, getline_leakage, get_inner_leakage). program_logic_ goal_for_function! needs Global spec instances (ct.v l.290). Leakage goals should be
    closed with align_trace, not cbn (ct.v l.33). LiveVerif and Rupicola have nothing.
  • Missing lemma. SemanticsRelations.v lifts plain to leakage but not back; once a
    shared function (drivers, memswap) gets a leakage spec, plain callers need
    plain_of_leakage_call or their own port. Also a call-level intersect (combine a plain
    functional spec with a leakage-only spec) is a 20-line lemma that does not exist yet.
  • ext_spec plumbing. Field25519.v and the Rupicola files are parameterized over
    Semantics.ExtSpec; leakage specs need LeakageSemantics.ExtSpec + PickSp.
    FE310CSemantics provides both and deleakaged_ext_spec connects them, so Option A
    avoids touching the generated proofs. The source-level proofs must hold for every
    pick_sp (they do; pick_sp must stay a section variable, never a concrete oracle).
  • Interaction with the stdlib-bits port. None specific. The leakage files were already
    ported (wp-j3, 2026-09-16); leakage equations are list equations, and leak_binop's
    use of the new Semantics.slu/sru/srs shift amounts is unchanged. No new word lemmas are
    needed.
  • What is and is not proven at the bottom. The RISC-V leakage model is riscv-coq's
    LeakageOfInstr (addresses of loads/stores, branch outcomes, divu/remu operands,
    MMIO addresses via MMIO.leak_ext_call); FE310CSemantics.v l.32 documents the timing
    assumptions (fixed-latency multiply). The Kami/end2end refinement does not carry leakage,
    so no statement about the pipelined processor follows.
  • Declassification. loopfn branches on set0|set1 after emitting them on GPIO; the
    spec must make f depend on ioh. If a reviewer wants "leakage independent of the
    authentication result", the code would have to be restructured (e.g. branch-free rekey),
    which is a code change, not a proof change.
  • Secret-dependent control flow found: none other than the declassified one. Loop
    counts are constants (scalarbits, ChaCha rounds, limb counts) or public lengths
    (pktlen, wlen, n); poll loops depend on MMIO values (public). memequal takes
    n = 16 constants. pick_sp makes the stackalloc address public by construction.
  • Effort drivers. Cost scales with control-flow nodes and calls, not statements
    (except brute force). The single riskiest item is loopfn_ok (Phase 5) because of its
    size, and the single open design item is T2 (Phase 6).

GitHub-ready summary (for bedrock2#565)

Leakage-aware specs for GarageDoor: inventory, plan, considerations.

Status

  • bedrock2's leakage stack is complete from semantics to RISC-V: LeakageSemantics,
    LeakageWeakestPrecondition, LeakageProgramLogic, LeakageLoops, and
    Pipeline.compiler_correct(_wp), whose forall kH kL, exists f pick_sp, ... getTrace final = Some (f kH') is the constant-time statement for one call
    (compilerExamples/memequal.v).
  • The event-loop pipeline (ExprImpEventLoopSpec, ToplevelLoop, CompilerInvariant)
    threads leakage but discards it; the Kami refinement drops it. LiveVerif and Rupicola
    have none.
  • GarageDoor.v is already written in the leakage program logic (fiat-crypto #2009) but its
    specs say nothing about k'; of its 37 functions only memequal has a leakage spec.
    The rest are plain: 10 drivers, memswap/memconst/memmove, 7 Rupicola functions, 3
    wrappers, 9 generated fe25519 functions.
  • Audit result: every function is constant-time w.r.t. the secrets (seed, ephemeral key,
    shared secret). Generated field code is straight-line with literal shift amounts and
    pointer+literal addresses; the ladder reads scalar bits by counter-indexed loads and
    shifts; loop counts are constants or public. The only secret-derived branch is
    if (set0|set1) in loopfn, whose value is already on GPIO, so the spec declassifies it
    through the I/O log.

Plan (leaves first)

  1. Fix the spec form: k' = f <public> ++ k with f before the secrets; for loopfn,
    K = f ioh k. T1 (per-iteration theorem) first, T2 (reactive) later.
  2. bedrock2 leaves: memswap/memconst/memmove like memequal; SPI/LAN9250 drivers and
    recvEthernet re-run their existing automation under LeakageProgramLogic with one
    align_trace goal per branch. Add a leakage-to-plain lemma so lightbulb keeps
    building. About 2 weeks.
  3. Generated field functions: one generic "straight-line constant-time" lemma with a
    vm_compute syntactic check, combined with the existing plain proofs via intersect.
    No change to the translation proofs. 1-2 weeks, reusable for all fiat-crypto outputs.
  4. Rupicola functions (montladder, cswap, inv, chacha20, ip_checksum): leakage-only proofs
    on the derived code, reusing the plain proofs. 1-2 weeks.
  5. Wrappers (x25519, x25519_base, clamp): 1-2 days. GarageDoor.v specs and loopfn_ok
    (650 lines, 7 branches): 1 week.
  6. Top level: T1 from compiler_correct_wp in days; T2 (getTrace = Some (LEAK getLog)
    as an event-loop invariant) needs compiler work: leakage in ProgramSpec, ll_good
    pinning the trace, a computable leakage predictor exposed from Pipeline. 3-4 weeks.

Considerations: loop leakage functions are hand-written; no leakage-to-plain lifting
exists yet; the statement stops at riscv-coq's leakage model, not the Kami processor; no
interaction with the stdlib-bits port.

Effort: 6-8 person-weeks to a per-iteration RISC-V constant-time theorem, plus 3-4
weeks for the reactive whole-loop theorem.


Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm).

@andres-erbsen

andres-erbsen commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

@JasonGross-fiat-crypto-bot implement the first two steps of this plan, one PR per file

@JasonGross-fiat-crypto-bot

Copy link
Copy Markdown

Working on it: one PR each for memswap.v, memconst.v, memmove.v, SPI.v, LAN9250.v and lightbulb.v (recvEthernet), with the SemanticsRelations leakage-to-plain helper as a small first PR so plain callers keep building. Drivers stack on each other (SPI, then LAN9250, then recvEthernet).


Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm).

@JasonGross-fiat-crypto-bot

Copy link
Copy Markdown

Design note for the SPI/LAN9250 leakage PRs: spi_xchg's timeout branch (any +++ spi_timeout) ioh is too weak to compose leakage specs. A caller such as lan9250_readword has to split ioh into per-call segments to apply spi_xchg's leakage function, and with an arbitrary prefix before the timeout that split is ambiguous. Plan: state the timeout branch precisely (spi_write/spi_read already do, with a fixed patience length), do the same for the LAN9250 functions, and add a lemma recovering the old (any +++ spi_timeout) fact for lightbulb.v. Success branches are unchanged. Say so if you would prefer a different shape.


Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm).

@JasonGross-fiat-crypto-bot

Copy link
Copy Markdown

First batch of the plan is open, one PR per file, all against master:

Still coming: SPI, LAN9250 (with the precise timeout specs from the note above), recvEthernet stacked on those; lightbulb's other functions stay plain and take the stackalloc-free hypothesis.


Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm).

@JasonGross-fiat-crypto-bot

Copy link
Copy Markdown

The rest of the first two steps is up, so every PR in the plan is now open and ready:

As described in the design note above, the SPI and LAN9250 timeout branches are now stated precisely. A lemma recovers the old any +++ timeout form for lightbulb.v. The other lightbulb functions keep their plain specs.

Compile times: LAN9250.v goes from 35 s to 59 s. lightbulb.v stays at about 36 s. Unfolding the recvEthernet loop with cbn made the kernel check take hours. #586 unfolds it with small rewrite lemmas instead.


Written by Claude Opus 5.5 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants