Debian Codegraph @

src/Bedrock/Group/ScalarMult/MontgomeryLadder.v

raw
1 Require Crypto.Bedrock.Group.Loops.
2 Require Import Crypto.Curves.Montgomery.XZ.
3 Require Import Crypto.Curves.Montgomery.XZProofs.
4 Require Import Rupicola.Lib.Api.
5 Require Import Rupicola.Lib.Alloc.
6 Require Import Rupicola.Lib.SepLocals.
7 Require Import Rupicola.Lib.ControlFlow.DownTo.
8 Require Import Crypto.Arithmetic.PrimeFieldTheorems.
9 Require Import Crypto.Bedrock.Group.ScalarMult.LadderStep.
10 Require Import Crypto.Bedrock.Group.ScalarMult.CSwap.
11 Require Import Crypto.Bedrock.Specs.Field.
12 Require Import Crypto.Util.NumTheoryUtil.
13 Require Import Crypto.Bedrock.Field.Interface.Compilation2.
14 Require Import Crypto.Bedrock.Group.AdditionChains.
15
16 Require bedrock2.NotationsCustomEntry. Import bedrock2.Syntax.Coercions.
17
18 Require Import bedrock2.ZnWords.
19
20 Local Open Scope Z_scope.
21
22 Import NoExprReflectionCompiler.
23 Import DownToCompiler.
24 (* TODO: migrate these to rupicola.
25 Currently break when put in Notations.v
26 *)
27 Notation "'let/n' ( w , x , y , z ) := val 'in' body" :=
28 (nlet [IdentParsing.TC.ident_to_string w;
29 IdentParsing.TC.ident_to_string x;
30 IdentParsing.TC.ident_to_string y;
31 IdentParsing.TC.ident_to_string z]
32 val (fun '\<w, x, y, z\> => body))
33 (at level 200, w name, x name, y name, z name, body at level 200,
34 only parsing).
35
36
37 Notation "'let/n' ( v , w , x , y , z ) := val 'in' body" :=
38 (nlet [IdentParsing.TC.ident_to_string v;
39 IdentParsing.TC.ident_to_string w;
40 IdentParsing.TC.ident_to_string x;
41 IdentParsing.TC.ident_to_string y;
42 IdentParsing.TC.ident_to_string z]
43 val (fun vwxyz => let '\< v, w, x, y, z \> := vwxyz in body))
44 (at level 200, v name, w name, x name, y name, z name, body at level 200,
45 only parsing).
46
47 Section Gallina.
48 Local Open Scope F_scope.
49 Context {m : positive} (a24 : F m) (count : nat).
50 Definition montladder_gallina (k : Z) (u : F m)
51 : F m :=
52 let/n X1 := stack 1 in
53 let/n Z1 := stack 0 in
54 let/n X2 := stack u in
55 let/n Z2 := stack 1 in
56 let/n swap := false in
57 let/n (X1, Z1, X2, Z2, swap) :=
58 downto
59 \<X1, Z1, X2, Z2, swap\> (* initial state *)
60 count
61 (fun state i =>
62 let '\<X1, Z1, X2, Z2, swap\> := state in
63 let/n s_i := Z.testbit k (Z.of_nat i) in
64 let/n swap := xorb swap s_i in
65 let/n (X1, X2) := cswap swap X1 X2 in
66 let/n (Z1, Z2) := cswap swap Z1 Z2 in
67 let/n (X1, Z1, X2, Z2) := ladderstep_gallina m a24 u X1 Z1 X2 Z2 in
68 let/n swap := s_i in
69 \<X1, Z1, X2, Z2, swap\>
70 ) in
71 let/n (X1, X2) := cswap swap X1 X2 in
72 let/n (Z1, Z2) := cswap swap Z1 Z2 in
73 let/n OUT := (F.inv Z1) in
74 let/n OUT := (X1 * OUT) in
75 OUT.
76
77 (*TODO: which of ladderstep_gallina and M.xzladderstep should we change? either?*)
78 Definition reorder_pairs {A B C D} (p : \<<A , B , C , D\>>) : (A*B)*(C*D) :=
79 (P2.car p, P2.car (P2.cdr p),((P2.car (P2.cdr (P2.cdr p))),(P2.cdr (P2.cdr (P2.cdr p))))).
80
81 (* TODO: should M.montladder change to accomodate this? *)
82 Definition to_pair {A B} p : A*B := (P2.car p, P2.cdr p).
83
84 Lemma invert_reorder_pairs {A B C D} (p : \<<A , B , C , D\>>) w x y z
85 : reorder_pairs p = (w,x, (y,z)) <-> p = \<w,x,y,z\>.
86 Proof.
87 destruct p as [? [? [? ?]]].
88 cbv.
89 intuition congruence.
90 Qed.
91
92 Lemma ladderstep_gallina_equiv X1 P1 P2 :
93 reorder_pairs (ladderstep_gallina _ a24 X1 (fst P1) (snd P1) (fst P2) (snd P2)) =
94 @M.xzladderstep _ F.add F.sub F.mul a24 X1 P1 P2.
95 Proof.
96 intros. cbv [ladderstep_gallina M.xzladderstep].
97 destruct P1 as [x1 z1]. destruct P2 as [x2 z2].
98 cbv [Rewriter.Util.LetIn.Let_In nlet]. cbn [fst snd].
99 rewrite !F.pow_2_r; trivial.
100 Qed.
101
102 Lemma montladder_gallina_equiv n point :
103 montladder_gallina n point =
104 @M.montladder _ F.zero F.one F.add F.sub F.mul F.inv a24 (Z.of_nat count) (Z.testbit n) point.
105 Proof.
106 cbv [montladder_gallina M.montladder Rewriter.Util.LetIn.Let_In stack].
107 do 5 (unfold nlet at 1); cbn [fst snd P2.car P2.cdr].
108 rewrite Loops.downto_while.
109 match goal with
110 | |- ?lhs = ?rhs =>
111 match lhs with context [Loops.while ?ltest ?lbody ?fuel ?linit] =>
112 match rhs with context [Loops.while ?rtest ?rbody ?fuel ?rinit] =>
113 rewrite (Loops.while.preservation ltest lbody rtest rbody
114 (fun s1 s2 => s1 = let '(x2, z2, x3, z3, swap, i) := s2 in
115 (\<x2, z2, x3, z3, swap\>, i))) with (init2:=rinit)
116 end end end.
117 { rewrite !Nat2Z.id. destruct (Loops.while _ _ _ _) eqn:? at 1 2.
118 destruct_products. case b; reflexivity. }
119 { intros. destruct_products. congruence. }
120 { intros. destruct_products. Prod.inversion_prod. LtbToLt.Z.ltb_to_lt. subst.
121 rewrite !Z2Nat.id by lia.
122 cbv [nlet M.cswap].
123 repeat match goal with
124 | H : (_,_) = (_,_) |- _ => inversion H; subst; clear H
125 | _ => progress BreakMatch.break_match
126 | _ => progress BreakMatch.break_match_hyps
127 end;
128 rewrite <- ladderstep_gallina_equiv, invert_reorder_pairs in Heqp0;
129 cbn [fst snd to_pair] in Heqp0; inversion_clear Heqp0; trivial. }
130 { reflexivity. }
131 Qed.
132
133 Context
134 (field : @Hierarchy.field (F m) eq F.zero F.one F.opp F.add F.sub F.mul F.inv F.div)
135 (Hm' : (28 <= m)%positive)
136 a (a24_correct : (1 + 1 + 1 + 1) * a24 = a - (1 + 1))
137 (a2m4_nonsq : ~(exists r, F.mul r r = F.sub (F.mul a a) (F.of_Z _ 4)))
138 (b : F m) (b_nonzero : b <> 0).
139
140 Local Instance char_ge_28 : @Ring.char_ge (F m) eq 0 1 F.opp F.add F.sub F.mul 28.
141 Proof. eapply Algebra.Hierarchy.char_ge_weaken; try eapply F.char_gt; trivial. Qed.
142
143 Context {char_ge_3 : @Ring.char_ge (F m) eq 0 1 F.opp F.add F.sub F.mul 3}. (* appears in statement *)
144 Import MontgomeryCurve Montgomery.Affine.
145 Local Notation X0 := (@M.X0 _ eq F.zero F.add F.mul a b).
146 Local Notation add := (M.add(field:=field)(char_ge_3:=char_ge_3)(a:=a)(b_nonzero:=b_nonzero)).
147 Local Notation opp := (M.opp(field:=field)(a:=a)(b_nonzero:=b_nonzero)).
148 Local Notation scalarmult := (@ScalarMult.scalarmult_ref _ add M.zero opp).
149 Add Ring Private_ring : (F.ring_theory m) (morphism (F.ring_morph m), constants [F.is_constant]).
150
151 Lemma montladder_gallina_equiv_affine n P :
152 montladder_gallina n (X0 P) = X0 (scalarmult (n mod 2^Z.of_nat count) P).
153 Proof.
154 unshelve erewrite montladder_gallina_equiv, M.montladder_correct;
155 try lia; try exact _; trivial using F.inv_0.
156 { intros r Hr. apply a2m4_nonsq; exists r. rewrite Hr. f_equal. ring. }
157 Qed.
158 End Gallina.
159
160 Section __.
161
162 Context {width: Z} {BW: Bitwidth width} {word: word.word width} {mem: map.map word Byte.byte}.
163 Context {locals: map.map String.string word}.
164 Context {ext_spec: bedrock2.Semantics.ExtSpec}.
165 Context {word_ok : word.ok word} {mem_ok : map.ok mem}.
166 Context {locals_ok : map.ok locals}.
167 Context {ext_spec_ok : Semantics.ext_spec.ok ext_spec}.
168 Context {field_parameters : FieldParameters}.
169 Context {field_representaton : FieldRepresentation}.
170 Context {field_representation_ok : FieldRepresentation_ok}.
171 Hint Resolve relax_bounds : compiler.
172
173 Section MontLadder.
174 Context scalarbits (scalarbits_small : word.wrap (Z.of_nat scalarbits) = Z.of_nat scalarbits).
175 Local Notation "bs $@ a" := (array ptsto (word.of_Z 1) a bs) (at level 20).
176 Let m : positive := M_pos.
177 Context
178 (field : @Hierarchy.field (F m) eq F.zero F.one F.opp F.add F.sub F.mul F.inv F.div) (Hm' : (28 <= m)%positive)
179 (a : F m) (b : F m) (b_nonzero : b <> F.zero).
180
181 Context {char_ge_3 : @Ring.char_ge (F m) eq F.zero F.one F.opp F.add F.sub F.mul 3}. (* appears in statement *)
182 Import MontgomeryCurve Montgomery.Affine.
183 Local Notation X0 := (@M.X0 _ eq F.zero F.add F.mul a b).
184 Local Notation add := (M.add(field:=field)(char_ge_3:=char_ge_3)(a:=a)(b_nonzero:=b_nonzero)).
185 Local Notation opp := (M.opp(field:=field)(a:=a)(b_nonzero:=b_nonzero)).
186 Local Notation scalarmult := (@ScalarMult.scalarmult_ref _ add M.zero opp).
187
188 Import MontgomeryCurve.
189 Instance spec_of_montladder : spec_of "montladder" :=
190 fnspec! "montladder"
191 (pOUT pK pU : word)
192 / Kbytes (K : Z) (U : F M_pos) (* inputs *)
193 out_bound OUT
194 R,
195 { requires tr mem :=
196 mem =* FElem out_bound pOUT OUT * Kbytes$@pK * FElem (Some tight_bounds) pU U * R /\
197 LittleEndianList.le_combine Kbytes = K /\
198 Z.of_nat scalarbits <= 8*Z.of_nat (length Kbytes);
199 ensures tr' mem' :=
200 tr' = tr /\ (
201 let OUT := montladder_gallina a24 scalarbits K U in
202 (FElem (Some tight_bounds) pOUT OUT * Kbytes$@pK
203 * FElem (Some tight_bounds) pU U
204 * R)%sep mem') }.
205
206 (* Adding word.unsigned_of_Z_1 and word.unsigned_of_Z_0 as hints to
207 compiler doesn't work, presumably because of the typeclass
208 preconditions. This is a hacky workaround. *)
209 (* TODO: figure out a cleaner way to do this *)
210 Lemma unsigned_of_Z_1 : word.unsigned (@word.of_Z _ word 1) = 1.
211 Proof using word_ok. exact word.unsigned_of_Z_1. Qed.
212 Lemma unsigned_of_Z_0 : word.unsigned (@word.of_Z _ word 0) = 0.
213 Proof using word_ok. exact word.unsigned_of_Z_0. Qed.
214 Hint Resolve unsigned_of_Z_0 unsigned_of_Z_1 : compiler.
215 Import bedrock2.NotationsCustomEntry.
216 Lemma compile_sctestbit : forall {tr mem locals functions} bs x i,
217 let v := Z.testbit x (Z.of_nat i) in
218 forall P (pred: P v -> predicate) (k: nlet_eq_k P v) k_impl
219 R x_ptr x_var wi i_var out_var,
220
221 (bs$@x_ptr * R)%sep mem ->
222 map.get locals x_var = Some x_ptr ->
223
224 LittleEndianList.le_combine bs = x ->
225
226 wi = word.of_Z (Z.of_nat i) ->
227 0 <= Z.of_nat i < 2 ^ width ->
228 Z.of_nat i < 8 * Z.of_nat (length bs) ->
229 map.get locals i_var = Some wi ->
230
231 (let v := v in
232 (<{ Trace := tr;
233 Memory := mem;
234 Locals := map.put locals out_var (word.b2w v);
235 Functions := functions }>
236 k_impl
237 <{ pred (k v eq_refl) }>)) ->
238 <{ Trace := tr;
239 Memory := mem;
240 Locals := locals;
241 Functions := functions }>
242 bedrock_cmd:($out_var = (load1($x_var+$i_var>>coq:(3))>>($i_var&coq:(7)))&coq:(1); coq:(k_impl))
243 <{ pred (nlet_eq [out_var] v k) }>.
244 Proof using mem_ok scalarbits word_ok.
245 clear dependent m.
246 repeat straightline.
247 repeat (eexists; split; repeat straightline'; eauto); cbn [Semantics.interp_binop].
248
249 eapply load_one_of_sep.
250 (*
251 (* Note: could instead add the following two lines to seprewrite0_in but kinda wanna avoid reduction/conversion there... *)
252 let t := type of Hrw in
253 let t := eval cbv zeta in t in
254 *)
255 unshelve (
256 let Hrw := open_constr:(@bytearray_index_inbounds _ _ _ _ _ _ _ _ _ : Lift1Prop.iff1 _ _) in
257 seprewrite0_in Hrw H; ecancel_assumption).
258 all : cycle 1.
259
260 all: try eapply word.unsigned_inj.
261 all: unfold word.b2w.
262 all: subst_lets_in_goal; subst.
263 all : repeat rewrite
264 ?word.unsigned_of_Z_b2z, ?word.unsigned_of_Z, ?word.unsigned_and_nowrap, ?word.unsigned_sru_nowrap.
265 all : cbv [word.wrap]; rewrite ?Z.mod_small.
266 all : change 7 with (Z.ones 3); change 1 with (Z.ones 1); rewrite ?Z.land_ones.
267 all : rewrite ?Z.shiftr_div_pow2; change (2^3) with 8; change (2^1) with 2.
268 all : rewrite <-?hd_skipn_nth_default.
269 1: rewrite <-Z.testbit_spec'; f_equal.
270 1: setoid_rewrite Z2Nat.inj_div.
271 all : try match goal with |- 0 <= byte.unsigned ?x < _ => epose proof byte.unsigned_range x end.
272 all : try (destruct Bitwidth.width_cases as [E|E]; rewrite ?E in *; Lia.lia).
273 all : try (destruct Bitwidth.width_cases as [E|E]; rewrite ?E in *; cbn in *; Lia.lia).
274
275 (*
276 Z.testbit (LittleEndianList.le_combine bs) (Z.of_nat i) =
277 Z.testbit (byte.unsigned
278 (nth_default (byte.of_Z 0) bs (Z.to_nat (Z.of_nat i) / Z.to_nat 8)))
279 (Z.of_nat i mod 8)
280 *)
281 rewrite <-(LittleEndianList.split_le_combine bs) at 2.
282 rewrite LittleEndianList.nth_default_le_split, byte.unsigned_of_Z, Nat2Z.id
283 by (eapply Nat.div_lt_upper_bound; Lia.nia).
284 cbv [byte.wrap]; rewrite <-Z.land_ones, Z.land_spec, Z.ones_spec_low by Lia.lia.
285 rewrite Z.shiftr_spec, Bool.andb_true_r by Lia.lia; f_equal.
286 rewrite Nat2Z.inj_div. Lia.lia.
287 Qed.
288
289 Hint Extern 8
290 (WeakestPrecondition.cmd _ _ _ _ _ (_ (nlet_eq _ (Z.testbit _ _) _))) =>
291 simple eapply compile_sctestbit; shelve : compiler.
292
293
294 Existing Instance felem_alloc.
295
296
297 Lemma cswap_same {A} : forall b (a : A), cswap b a a = \<a,a\>.
298 Proof using Type.
299 intros b0; destruct b0; reflexivity.
300 Qed.
301
302 Local Ltac ecancel_assumption ::= ecancel_assumption_impl.
303
304 Lemma scalarbits_bound : Z.of_nat scalarbits < 2 ^ width.
305 Proof using scalarbits_small.
306 clear dependent m.
307 rewrite <- scalarbits_small.
308 unfold word.wrap.
309 apply Z_mod_lt.
310 pose proof word.width_pos.
311 pose proof (Z.pow_pos_nonneg 2 width ltac:(lia)).
312 lia.
313 Qed.
314
315 (* TODO: why doesn't `Existing Instance` work?
316 Existing Instance spec_of_sctestbit.*)
317 Hint Extern 1 (spec_of "ladderstep") =>
318 (simple refine (@spec_of_ladderstep _ _ _ _ _ _ _ _)) : typeclass_instances.
319
320
321 Hint Extern 1 (spec_of "cswap") =>
322 (simple refine (spec_of_cswap)) : typeclass_instances.
323
324 (* TODO: this seems a bit delicate*)
325 Ltac compile_cswap :=
326 eapply compile_felem_cswap;
327 [solve[repeat compile_step] ..
328 | repeat compile_step;
329 rewrite cswap_same;
330 compile_step;
331 match goal with
332 | [|- (WeakestPrecondition.cmd _ _ _ _ _ (_ (let (_,_) := ?v in _)))] =>
333 destruct v
334 end].
335
336 Hint Extern 8 (WeakestPrecondition.cmd _ _ _ _ _ (_ (nlet_eq _ (cswap _ _ _) _))) =>
337 compile_cswap; shelve : compiler.
338
339
340 Lemma word_unsigned_of_Z_eq z
341 : 0 <= z < 2 ^ width -> word.unsigned (word.of_Z z : word) = z.
342 Proof using word_ok.
343 intros.
344 rewrite word.unsigned_of_Z.
345 rewrite word.wrap_small; auto.
346 Qed.
347
348 Hint Extern 8 (word.unsigned (word.of_Z _) = _) =>
349 simple eapply word_unsigned_of_Z_eq; [ ZnWords |] : compiler.
350
351 (*TODO: should this go in core rupicola?*)
352 Lemma compile_copy_bool {tr _m l functions} (x: bool) :
353 let v := x in
354 forall P (pred: P v -> predicate)
355 (k: nlet_eq_k P v) k_impl
356 x_expr var,
357
358 WeakestPrecondition.dexpr _m l x_expr (word.of_Z (Z.b2z v)) ->
359
360 (let v := v in
361 <{ Trace := tr;
362 Memory := _m;
363 Locals := map.put l var (word.of_Z (Z.b2z v));
364 Functions := functions }>
365 k_impl
366 <{ pred (k v eq_refl) }>) ->
367 <{ Trace := tr;
368 Memory := _m;
369 Locals := l;
370 Functions := functions }>
371 cmd.seq (cmd.set var x_expr) k_impl
372 <{ pred (nlet_eq [var] v k) }>.
373 Proof using Type.
374 intros.
375 repeat straightline.
376 eauto.
377 Qed.
378 Hint Extern 10 (WeakestPrecondition.cmd _ _ _ _ _ (_ (nlet_eq _ ?v _))) =>
379 is_var v; simple eapply compile_copy_bool; shelve : compiler.
380
381
382 Hint Resolve unsigned_of_Z_0 : compiler_side_conditions.
383 Hint Resolve unsigned_of_Z_1 : compiler_side_conditions.
384 Hint Unfold F.one F.zero : compiler_cleanup.
385
386 Hint Extern 10 (_ < _) => lia : compiler_side_conditions.
387
388 (* TODO: update the original definition in bedrock2 *)
389 Ltac find_implication xs y ::=
390 multimatch xs with
391 | cons ?x _ =>
392 (* Only proceed if we can find an implication between x and y *)
393 let _ := constr:(ltac:(solve [auto 1 with nocore ecancel_impl])
394 : Lift1Prop.impl1 x y) in
395 constr:(O)
396 | cons _ ?xs => let i := find_implication xs y in constr:(S i)
397 end.
398
399 Context { F_M_pos : M_pos = (2^255-19)%positive }.
400 Context (a24_correct : F.mul (1 + 1 + 1 + 1) Field.a24 = F.sub a (1 + 1))
401 (Ha : ~(exists r, F.mul r r = F.sub (F.mul a a) (F.of_Z _ 4))).
402
403 Hint Extern 1 (spec_of "fe25519_inv") => (simple refine (spec_of_exp_large)) : typeclass_instances.
404 Hint Extern 1 (spec_of "felem_cswap") => (simple refine (spec_of_cswap)) : typeclass_instances.
405
406 Hint Extern 1 => simple eapply compile_felem_cswap; shelve : compiler.
407 Local Hint Extern 10 => lia : compiler_side_conditions.
408 Derive montladder_body SuchThat
409 (defn! "montladder" ("OUT", "K", "U")
410 { montladder_body },
411 implements (montladder_gallina(m:=M_pos))
412 using ["felem_cswap"; felem_copy; from_word;
413 "ladderstep"; "fe25519_inv"; mul])
414 As montladder_correct.
415 Proof.
416 pose proof scalarbits_bound.
417 compile.
418 Qed.
419
420 End MontLadder.
421 End __.
422
423 Global Hint Extern 1 (spec_of "montladder") => (simple refine (@spec_of_montladder _ _ _ _ _ _ _ _ _ _)) : typeclass_instances.
424
425 Import bedrock2.Syntax.Coercions.
426 Local Unset Printing Coercions.
427 (* Set the printing width so that arguments are printed on 1 line.
428 Otherwise the build breaks.
429 *)
430 Local Set Printing Width 160.
431 (*
432 Import NotationsCustomEntry.
433 *)
434 Redirect "Crypto.Bedrock.Group.ScalarMult.MontgomeryLadder.montladder_body" Eval cbv [montladder_body cmd_downto_fresh cmd_downto gs fold_right] in ("montladder", montladder_body 253).