Debian Codegraph @

src/PushButtonSynthesis/WordByWordMontgomery.v

raw
1 (** * Push-Button Synthesis of Word-By-Word Montgomery *)
2 From Coq Require Import String.
3 From Coq Require Import Lia.
4 From Coq Require Import ZArith.
5 From Coq Require Import MSetPositive.
6 From Coq Require Import List.
7 From Coq Require Import QArith_base Qround.
8 From Coq.Program Require Import Tactics. (* For WBW Montgomery proofs *)
9 From Coq Require Import Derive.
10 Require Import Crypto.Util.ErrorT.
11 Require Import Crypto.Util.ListUtil.
12 Require Import Crypto.Util.ListUtil.FoldBool.
13 Require Import Crypto.Util.Strings.Decimal.
14 Require Import Crypto.Util.ZRange.
15 Require Import Crypto.Util.ZUtil.Definitions.
16 Require Import Crypto.Util.ZUtil.Zselect.
17 Require Import Crypto.Util.ZUtil.Tactics.LtbToLt.
18 Require Import Crypto.Util.ZUtil.ModInv. (* Only needed for WBW Montgomery *)
19 Require Import Crypto.Util.ZUtil.Modulo. (* Only needed for WBW Montgomery proofs *)
20 Require Import Crypto.Util.ZUtil.Le. (* Only needed for WBW Montgomery proofs *)
21 Require Import Crypto.Util.Prod. (* For WBW Montgomery proofs *)
22 Require Import Crypto.Util.ZUtil.Tactics.PullPush.Modulo. (* For WBW montgomery proofs *)
23 Require Import Crypto.Util.ZUtil.Tactics.RewriteModSmall. (* For WBW montgomery proofs *)
24 Require Import Crypto.Util.ZUtil.Div. (* For WBW Montgomery proofs *)
25 Require Import Crypto.Util.ZUtil.Tactics.DivModToQuotRem. (* For WBW Montgomery proofs *)
26 Require Import Crypto.Util.ZUtil.Ones. (* For WBW montgomery proofs *)
27 Require Import Crypto.Util.ZUtil.Shift. (* For WBW montgomery proofs *)
28 Require Import Crypto.Util.ZUtil.ModExp.
29 Require Import Crypto.Util.Tactics.HasBody.
30 Require Import Crypto.Util.Tactics.Head.
31 Require Import Crypto.Util.Tactics.SpecializeBy.
32 Require Import Rewriter.Language.Wf.
33 Require Import Crypto.Language.WfExtra.
34 Require Import Rewriter.Language.Language.
35 Require Import Crypto.Language.API.
36 Require Import Crypto.AbstractInterpretation.AbstractInterpretation.
37 Require Import Crypto.Stringification.Language.
38 Require Import Crypto.Arithmetic.Core.
39 Require Import Crypto.Arithmetic.ModOps.
40 Require Import Crypto.Arithmetic.Freeze.
41 Require Import Crypto.Arithmetic.Partition.
42 Require Import Crypto.Arithmetic.WordByWordMontgomery.
43 Require Import Crypto.Arithmetic.UniformWeight.
44 Require Import Crypto.Arithmetic.BYInv.
45 Require Import Crypto.BoundsPipeline.
46 Require Import Crypto.COperationSpecifications.
47 Require Import Crypto.PushButtonSynthesis.ReificationCache.
48 Require Import Crypto.PushButtonSynthesis.Primitives.
49 Require Import Crypto.PushButtonSynthesis.WordByWordMontgomeryReificationCache.
50 Require Import Crypto.PushButtonSynthesis.BYInversionReificationCache.
51 Require Import Crypto.Assembly.Equivalence.
52 Import ListNotations.
53 Local Open Scope string_scope. Local Open Scope Z_scope. Local Open Scope list_scope. Local Open Scope bool_scope.
54
55 Import
56 Language.Wf.Compilers
57 Language.WfExtra.Compilers
58 Language.Compilers
59 AbstractInterpretation.Compilers
60 Stringification.Language.Compilers.
61 Import Compilers.API.
62
63 Import COperationSpecifications.Primitives.
64 Import COperationSpecifications.Solinas.
65 Import COperationSpecifications.WordByWordMontgomery.
66
67 Import Associational Positional.
68 Import Arithmetic.WordByWordMontgomery.WordByWordMontgomery.
69
70 Import WordByWordMontgomeryReificationCache.WordByWordMontgomery.
71 Import BYInversionReificationCache.WordByWordMontgomeryInversion.
72
73 Local Coercion Z.of_nat : nat >-> Z.
74 Local Coercion QArith_base.inject_Z : Z >-> Q.
75 Local Coercion Z.pos : positive >-> Z.
76
77 Local Set Keyed Unification. (* needed for making [autorewrite] fast, c.f. COQBUG(https://github.com/coq/coq/issues/9283) *)
78
79 (* needed for making [autorewrite] not take a very long time *)
80 Local Opaque
81 reified_mul_gen
82 reified_square_gen
83 reified_add_gen
84 reified_sub_gen
85 reified_opp_gen
86 reified_from_montgomery_gen
87 reified_to_montgomery_gen
88 reified_to_bytes_gen
89 reified_from_bytes_gen
90 reified_encode_gen
91 reified_zero_gen
92 reified_one_gen
93 reified_eval_gen
94 reified_bytes_eval_gen
95 reified_eval_twos_complement_gen
96 reified_msat_gen
97 reified_encode_gen
98 reified_divstep_gen
99 reified_nonzero_gen
100 expr.Interp.
101
102 Section __.
103 Context {output_language_api : ToString.OutputLanguageAPI}
104 {pipeline_opts : PipelineOptions}
105 {pipeline_to_string_opts : PipelineToStringOptions}
106 {synthesis_opts : SynthesisOptions}
107 (m : Z)
108 (machine_wordsize : machine_wordsize_opt).
109
110 Definition s := 2^Z.log2_up m.
111 Definition c := s - m.
112 Definition n : nat := Z.to_nat (Qceiling (Z.log2_up s / machine_wordsize)).
113 Definition sat_limbs := (n + 1)%nat. (* to represent m in twos complement we might need another bit *)
114 Definition r := 2^machine_wordsize.
115 Definition r' := Z.modinv r m.
116 Definition m' := Z.modinv (-m) r.
117 Definition n_bytes := bytes_n s.
118
119 Definition divstep_precompmod :=
120 let bits := (Z.log2 m) + 1 in
121 let i := if bits <? 46 then (49 * bits + 80) / 17 else (49 * bits + 57) / 17 in
122 let k := (m + 1) / 2 in
123 (Z.modexp k i m).
124
125 Definition prime_upperbound_list : list Z
126 := Partition.partition (uweight machine_wordsize) n (s-1).
127 Definition prime_bytes_upperbound_list : list Z
128 := Partition.partition (weight 8 1) n_bytes (s-1).
129 Definition upperbounds : list Z := prime_upperbound_list.
130 Definition prime_bound : ZRange.type.interp (base.type.Z)
131 := r[0~>m-1]%zrange.
132 Definition prime_word_bound : ZRange.type.interp (base.type.Z) (* a word that's guaranteed to be smaller than the prime *)
133 := r[0 ~> Z.min m (2^machine_wordsize) - 1]%zrange.
134 Definition prime_bounds : list (ZRange.type.option.interp base.type.Z)
135 := List.map (fun v => Some r[0 ~> v]%zrange) prime_upperbound_list.
136 Definition prime_bytes_bounds : list (ZRange.type.option.interp (base.type.Z))
137 := List.map (fun v => Some r[0 ~> v]%zrange) prime_bytes_upperbound_list.
138 Local Notation word_bound := (word_bound machine_wordsize).
139 Local Notation saturated_bounds := (saturated_bounds n machine_wordsize).
140 Local Notation larger_saturated_bounds := (Primitives.saturated_bounds sat_limbs machine_wordsize).
141
142
143 Definition divstep_input :=
144 (Some r[0~>2^machine_wordsize-1],
145 (Some (repeat (Some r[0 ~> 2^machine_wordsize-1]) sat_limbs),
146 (Some (repeat (Some r[0 ~> 2^machine_wordsize-1]) sat_limbs),
147 (Some (repeat (Some r[0 ~> 2^machine_wordsize-1]) n),
148 (Some (repeat (Some r[0 ~> 2^machine_wordsize-1]) n),tt)))))%zrange.
149
150 Definition divstep_output :=
151 (Some r[0~>2^machine_wordsize-1],
152 Some (repeat (Some r[0 ~> 2^machine_wordsize-1]) sat_limbs),
153 Some (repeat (Some r[0 ~> 2^machine_wordsize-1]) sat_limbs),
154 Some (repeat (Some r[0 ~> 2^machine_wordsize-1]) n),
155 Some (repeat (Some r[0 ~> 2^machine_wordsize-1]) n))%zrange.
156
157 Local Notation possible_values := (possible_values_of_machine_wordsize machine_wordsize).
158 Local Notation possible_values_with_bytes := (possible_values_of_machine_wordsize_with_bytes machine_wordsize).
159
160 Definition bounds : list (ZRange.type.option.interp base.type.Z)
161 := saturated_bounds (*List.map (fun u => Some r[0~>u]%zrange) upperbounds*).
162 Definition larger_bounds : list (ZRange.type.option.interp base.type.Z)
163 := larger_saturated_bounds (*List.map (fun u => Some r[0~>u]%zrange) upperbounds*).
164 Definition montgomery_domain_bounds := saturated_bounds.
165 Definition non_montgomery_domain_bounds := saturated_bounds.
166 Typeclasses Opaque montgomery_domain_bounds.
167 Typeclasses Opaque non_montgomery_domain_bounds.
168 Global Instance montgomery_domain_bounds_typedef : typedef (t:=base.type.list base.type.Z) (Some montgomery_domain_bounds)
169 := { name := "montgomery_domain_field_element"
170 ; description name := (text_before_type_name ++ name ++ " is a field element in the Montgomery domain.")%string }.
171 Global Instance non_montgomery_domain_bounds_typedef : typedef (t:=base.type.list base.type.Z) (Some non_montgomery_domain_bounds)
172 := { name := "non_montgomery_domain_field_element"
173 ; description name := (text_before_type_name ++ name ++ " is a field element NOT in the Montgomery domain.")%string }.
174
175
176 Local Existing Instance default_translate_to_fancy.
177 Local Instance no_select_size : no_select_size_opt := no_select_size_of_no_select machine_wordsize.
178 Local Instance split_mul_to : split_mul_to_opt := split_mul_to_of_should_split_mul machine_wordsize possible_values.
179 Local Instance split_multiret_to : split_multiret_to_opt := split_multiret_to_of_should_split_multiret machine_wordsize possible_values.
180
181 (** Note: If you change the name or type signature of this
182 function, you will need to update the code in CLI.v *)
183 Definition check_args {T} (requests : list string) (res : Pipeline.ErrorT T)
184 : Pipeline.ErrorT T
185 := check_args_of_list
186 (List.map
187 (fun v => (true, v))
188 [((1 <? machine_wordsize)%Z, Pipeline.Value_not_ltZ "machine_wordsize <= 1" 1 machine_wordsize)
189 ; ((0 <? c)%Z, Pipeline.Value_not_ltZ "c ≤ 0" 0 c)
190 ; ((1 <? m)%Z, Pipeline.Value_not_ltZ "m ≤ 1" 1 m)
191 ; (negb (n =? 0)%nat, Pipeline.Values_not_provably_distinctZ "n = 0" n 0%nat)
192 ; (negb (r' =? 0)%Z, Pipeline.No_modular_inverse "r⁻¹ mod m" r m)
193 ; (((r * r') mod m =? 1)%Z, Pipeline.Values_not_provably_equalZ "(r * r') mod m ≠ 1" ((r * r') mod m) 1)
194 ; (((m * m') mod r =? (-1) mod r)%Z, Pipeline.Values_not_provably_equalZ "(m * m') mod r ≠ (-1) mod r" ((m * m') mod r) ((-1) mod r))
195 ; (s <=? r^n, Pipeline.Value_not_leZ "r^n ≤ s" s (r^n))
196 ; (s <=? uweight machine_wordsize n, Pipeline.Value_not_leZ "weight n < s (needed for from_bytes)" s (uweight machine_wordsize n))
197 ; (s <=? uweight 8 n_bytes, Pipeline.Value_not_leZ "bytes_weight n_bytes < s (needed for from_bytes)" s (uweight 8 n_bytes))
198 ])
199 res.
200
201 Local Arguments Z.mul !_ !_.
202
203 Local Ltac use_curve_good_t :=
204 repeat first [ use_requests_to_prove_curve_good_t_step
205 | assumption
206 | lia
207 | progress autorewrite with distr_length
208 | progress distr_length
209 | solve [ auto with zarith ]
210 | rewrite Z.log2_pow2 by use_curve_good_t ].
211
212 Context (requests : list string)
213 (curve_good : check_args requests (Success tt) = Success tt).
214
215 Lemma use_curve_good
216 : Z.pos (Z.to_pos m) = m
217 /\ m = s - c
218 /\ Z.pos (Z.to_pos m) <> 0
219 /\ s - c <> 0
220 /\ 0 < s
221 /\ s <> 0
222 /\ 0 < machine_wordsize
223 /\ n <> 0%nat
224 /\ List.length bounds = n
225 /\ 0 < 1 <= machine_wordsize
226 /\ 0 < c < s
227 /\ (r * r') mod m = 1
228 /\ (m * m') mod r = (-1) mod r
229 /\ 0 < machine_wordsize
230 /\ 1 < m
231 /\ m < r^n
232 /\ s = 2^Z.log2 s
233 /\ s <= uweight machine_wordsize n
234 /\ s <= uweight 8 n_bytes.
235 Proof using curve_good.
236 prepare_use_curve_good (); cbv [s c] in *.
237 { destruct m eqn:?; cbn; lia. }
238 { use_curve_good_t. }
239 { use_curve_good_t. }
240 { use_curve_good_t. }
241 { use_curve_good_t. }
242 { use_curve_good_t. }
243 { use_curve_good_t. }
244 { use_curve_good_t. }
245 { use_curve_good_t. }
246 { use_curve_good_t. }
247 { use_curve_good_t. }
248 { use_curve_good_t. }
249 { use_curve_good_t. }
250 Qed.
251
252 Local Notation valid := (valid machine_wordsize n m).
253 Local Notation bytes_valid := (WordByWordMontgomery.valid 8 n_bytes m).
254
255 Local Notation from_montgomery_res := (from_montgomerymod machine_wordsize n m m').
256
257 Local Notation notations_for_docstring prefix
258 := ((CorrectnessStringification.dyn_context.cons
259 m "m"
260 (CorrectnessStringification.dyn_context.cons
261 r' ("((2^" ++ Decimal.Z.to_string machine_wordsize ++ ")⁻¹ mod m)")
262 (CorrectnessStringification.dyn_context.cons
263 from_montgomery_res "from_montgomery"
264 (CorrectnessStringification.dyn_context.cons
265 (@eval machine_wordsize n) "eval"
266 (CorrectnessStringification.dyn_context.cons
267 (@eval 8 n_bytes) "bytes_eval"
268 (CorrectnessStringification.dyn_context.cons
269 (Z.log2 m) "⌊log2 m⌋"
270 (CorrectnessStringification.dyn_context.cons
271 (@eval_twos_complement machine_wordsize n) "twos_complement_eval"
272 CorrectnessStringification.dyn_context.nil)))))))%string)
273 (only parsing).
274 Local Notation "'docstring_with_summary_from_lemma!' prefix summary correctness"
275 := (docstring_with_summary_from_lemma_with_ctx!
276 (notations_for_docstring prefix)
277 summary
278 correctness)
279 (only parsing, at level 10, prefix at next level, summary at next level, correctness at next level).
280
281 Definition mul
282 := Pipeline.BoundsPipeline
283 false (* subst01 *)
284 possible_values
285 (reified_mul_gen
286 @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify n @ GallinaReify.Reify m @ GallinaReify.Reify m')
287 (Some montgomery_domain_bounds, (Some montgomery_domain_bounds, tt))
288 (Some montgomery_domain_bounds).
289
290 Definition smul (prefix : string)
291 : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))
292 := Eval cbv beta in
293 FromPipelineToString!
294 machine_wordsize prefix "mul" mul
295 (docstring_with_summary_from_lemma!
296 prefix
297 (fun fname : string => [text_before_function_name ++ fname ++ " multiplies two field elements in the Montgomery domain."]%string)
298 (mul_correct machine_wordsize n m valid from_montgomery_res)).
299
300 Definition square
301 := Pipeline.BoundsPipeline
302 false (* subst01 *)
303 possible_values
304 (reified_square_gen
305 @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify n @ GallinaReify.Reify m @ GallinaReify.Reify m')
306 (Some montgomery_domain_bounds, tt)
307 (Some montgomery_domain_bounds).
308
309 Definition ssquare (prefix : string)
310 : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))
311 := Eval cbv beta in
312 FromPipelineToString!
313 machine_wordsize prefix "square" square
314 (docstring_with_summary_from_lemma!
315 prefix
316 (fun fname : string => [text_before_function_name ++ fname ++ " squares a field element in the Montgomery domain."]%string)
317 (square_correct machine_wordsize n m valid from_montgomery_res)).
318
319 Definition add
320 := Pipeline.BoundsPipeline
321 true (* subst01 *)
322 possible_values
323 (reified_add_gen
324 @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify n @ GallinaReify.Reify m)
325 (Some montgomery_domain_bounds, (Some montgomery_domain_bounds, tt))
326 (Some montgomery_domain_bounds).
327
328 Definition sadd (prefix : string)
329 : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))
330 := Eval cbv beta in
331 FromPipelineToString!
332 machine_wordsize prefix "add" add
333 (docstring_with_summary_from_lemma!
334 prefix
335 (fun fname : string => [text_before_function_name ++ fname ++ " adds two field elements in the Montgomery domain."]%string)
336 (add_correct machine_wordsize n m valid from_montgomery_res)).
337
338 Definition sub
339 := Pipeline.BoundsPipeline
340 true (* subst01 *)
341 possible_values
342 (reified_sub_gen
343 @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify n @ GallinaReify.Reify m)
344 (Some montgomery_domain_bounds, (Some montgomery_domain_bounds, tt))
345 (Some montgomery_domain_bounds).
346
347 Definition ssub (prefix : string)
348 : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))
349 := Eval cbv beta in
350 FromPipelineToString!
351 machine_wordsize prefix "sub" sub
352 (docstring_with_summary_from_lemma!
353 prefix
354 (fun fname : string => [text_before_function_name ++ fname ++ " subtracts two field elements in the Montgomery domain."]%string)
355 (sub_correct machine_wordsize n m valid from_montgomery_res)).
356
357 Definition opp
358 := Pipeline.BoundsPipeline
359 true (* subst01 *)
360 possible_values
361 (reified_opp_gen
362 @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify n @ GallinaReify.Reify m)
363 (Some montgomery_domain_bounds, tt)
364 (Some montgomery_domain_bounds).
365
366 Definition sopp (prefix : string)
367 : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))
368 := Eval cbv beta in
369 FromPipelineToString!
370 machine_wordsize prefix "opp" opp
371 (docstring_with_summary_from_lemma!
372 prefix
373 (fun fname : string => [text_before_function_name ++ fname ++ " negates a field element in the Montgomery domain."]%string)
374 (opp_correct machine_wordsize n m valid from_montgomery_res)).
375
376 Definition from_montgomery
377 := Pipeline.BoundsPipeline
378 true (* subst01 *)
379 possible_values
380 (reified_from_montgomery_gen
381 @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify n @ GallinaReify.Reify m @ GallinaReify.Reify m')
382 (Some montgomery_domain_bounds, tt)
383 (Some non_montgomery_domain_bounds).
384
385 Definition sfrom_montgomery (prefix : string)
386 : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))
387 := Eval cbv beta in
388 FromPipelineToString!
389 machine_wordsize prefix "from_montgomery" from_montgomery
390 (docstring_with_summary_from_lemma!
391 prefix
392 (fun fname : string => [text_before_function_name ++ fname ++ " translates a field element out of the Montgomery domain."]%string)
393 (from_montgomery_correct machine_wordsize n m r' valid)).
394
395 Definition to_montgomery
396 := Pipeline.BoundsPipeline
397 true (* subst01 *)
398 possible_values
399 (reified_to_montgomery_gen
400 @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify n @ GallinaReify.Reify m @ GallinaReify.Reify m')
401 (Some non_montgomery_domain_bounds, tt)
402 (Some montgomery_domain_bounds).
403
404 Definition sto_montgomery (prefix : string)
405 : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))
406 := Eval cbv beta in
407 FromPipelineToString!
408 machine_wordsize prefix "to_montgomery" to_montgomery
409 (docstring_with_summary_from_lemma!
410 prefix
411 (fun fname : string => [text_before_function_name ++ fname ++ " translates a field element into the Montgomery domain."]%string)
412 (to_montgomery_correct machine_wordsize n m valid from_montgomery_res)).
413
414 Definition nonzero
415 := Pipeline.BoundsPipeline
416 true (* subst01 *)
417 possible_values
418 reified_nonzero_gen
419 (Some bounds, tt)
420 (Some r[0~>r-1]%zrange).
421
422 Definition snonzero (prefix : string)
423 : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))
424 := Eval cbv beta in
425 FromPipelineToString!
426 machine_wordsize prefix "nonzero" nonzero
427 (docstring_with_summary_from_lemma!
428 prefix
429 (fun fname : string => [text_before_function_name ++ fname ++ " outputs a single non-zero word if the input is non-zero and zero otherwise."]%string)
430 (nonzero_correct machine_wordsize n m valid from_montgomery_res)).
431
432 Definition to_bytes
433 := Pipeline.BoundsPipeline
434 false (* subst01 *)
435 possible_values_with_bytes
436 (reified_to_bytes_gen
437 @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify n @ GallinaReify.Reify m)
438 (Some prime_bounds, tt)
439 (Some prime_bytes_bounds).
440
441 Definition sto_bytes (prefix : string)
442 : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))
443 := Eval cbv beta in
444 FromPipelineToString!
445 machine_wordsize prefix "to_bytes" to_bytes
446 (docstring_with_summary_from_lemma!
447 prefix
448 (fun fname : string => [text_before_function_name ++ fname ++ " serializes a field element NOT in the Montgomery domain to bytes in little-endian order."]%string)
449 (to_bytes_correct machine_wordsize n n_bytes m valid)).
450
451 Definition from_bytes
452 := Pipeline.BoundsPipeline
453 false (* subst01 *)
454 possible_values_with_bytes
455 (reified_from_bytes_gen
456 @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify 1 @ GallinaReify.Reify s @ GallinaReify.Reify n)
457 (Some prime_bytes_bounds, tt)
458 (Some prime_bounds).
459
460 Definition sfrom_bytes (prefix : string)
461 : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))
462 := Eval cbv beta in
463 FromPipelineToString!
464 machine_wordsize prefix "from_bytes" from_bytes
465 (docstring_with_summary_from_lemma!
466 prefix
467 (fun fname : string => [text_before_function_name ++ fname ++ " deserializes a field element NOT in the Montgomery domain from bytes in little-endian order."]%string)
468 (from_bytes_correct machine_wordsize n n_bytes m valid bytes_valid)).
469
470 Definition encode
471 := Pipeline.BoundsPipeline
472 true (* subst01 *)
473 possible_values
474 (reified_encode_gen
475 @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify n @ GallinaReify.Reify m @ GallinaReify.Reify m')
476 (Some prime_bound, tt)
477 (Some montgomery_domain_bounds).
478
479 Definition sencode (prefix : string)
480 : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))
481 := Eval cbv beta in
482 FromPipelineToString!
483 machine_wordsize prefix "encode" encode
484 (docstring_with_summary_from_lemma!
485 prefix
486 (fun fname : string => [text_before_function_name ++ fname ++ " encodes an integer as a field element in the Montgomery domain."]%string)
487 (encode_correct machine_wordsize n m valid from_montgomery_res)).
488
489
490 Definition encode_word
491 := Pipeline.BoundsPipeline
492 true (* subst01 *)
493 possible_values
494 (reified_encode_gen
495 @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify n @ GallinaReify.Reify m @ GallinaReify.Reify m')
496 (Some prime_word_bound, tt)
497 (Some saturated_bounds).
498
499 Definition sencode_word (prefix : string)
500 : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))
501 := Eval cbv beta in
502 FromPipelineToString!
503 machine_wordsize prefix "encode_word" encode_word
504 (docstring_with_summary_from_lemma!
505 prefix
506 (fun fname : string => [text_before_function_name ++ fname ++ " encodes an integer as a field element in the Montgomery domain."]%string)
507 (encode_word_correct machine_wordsize n m valid from_montgomery_res)).
508
509 Definition zero
510 := Pipeline.BoundsPipeline
511 true (* subst01 *)
512 possible_values
513 (reified_zero_gen
514 @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify n @ GallinaReify.Reify m @ GallinaReify.Reify m')
515 tt
516 (Some montgomery_domain_bounds).
517
518 Definition szero (prefix : string)
519 : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))
520 := Eval cbv beta in
521 FromPipelineToString!
522 machine_wordsize prefix "zero" zero
523 (docstring_with_summary_from_lemma!
524 prefix
525 (fun fname => [text_before_function_name ++ fname ++ " returns the field element zero in the Montgomery domain."]%string)
526 (zero_correct machine_wordsize n m valid from_montgomery_res)).
527
528 Definition one
529 := Pipeline.BoundsPipeline
530 true (* subst01 *)
531 possible_values
532 (reified_one_gen
533 @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify n @ GallinaReify.Reify m @ GallinaReify.Reify m')
534 tt
535 (Some montgomery_domain_bounds).
536
537 Definition sone (prefix : string)
538 : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))
539 := Eval cbv beta in
540 FromPipelineToString!
541 machine_wordsize prefix "set_one" one (* to avoid conflict with boringSSL *)
542 (docstring_with_summary_from_lemma!
543 prefix
544 (fun fname => [text_before_function_name ++ fname ++ " returns the field element one in the Montgomery domain."]%string)
545 (one_correct machine_wordsize n m valid from_montgomery_res)).
546
547 Definition reval (* r for reified *)
548 := Pipeline.RepeatRewriteAddAssocLeftAndFlattenThunkedRects
549 n
550 (Pipeline.PreBoundsPipeline
551 true (* subst01 *)
552 false (* let_bind_return *)
553 (reified_eval_gen
554 @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify n)
555 (Some montgomery_domain_bounds, tt)).
556
557 Definition seval (arg_name : string) (* s for string *)
558 := Show.show (invert_expr.smart_App_curried (reval _) (arg_name, tt)).
559
560 Definition rbytes_eval (* r for reified *)
561 := Pipeline.RepeatRewriteAddAssocLeftAndFlattenThunkedRects
562 n_bytes
563 (Pipeline.PreBoundsPipeline
564 true (* subst01 *)
565 false (* let_bind_return *)
566 (reified_bytes_eval_gen
567 @ GallinaReify.Reify s)
568 (Some prime_bytes_bounds, tt)).
569
570 Definition sbytes_eval (arg_name : string) (* s for string *)
571 := Show.show (invert_expr.smart_App_curried (rbytes_eval _) (arg_name, tt)).
572
573 Definition reval_twos_complement (* r for reified *)
574 := Pipeline.RepeatRewriteAddAssocLeftAndFlattenThunkedRects
575 n
576 (Pipeline.PreBoundsPipeline
577 true (* subst01 *)
578 false (* let_bind_return *)
579 (reified_eval_twos_complement_gen
580 @ GallinaReify.Reify (machine_wordsize:Z)
581 @ GallinaReify.Reify n)
582 (Some bounds, tt)).
583
584 Definition seval_twos_complement (arg_name : string) (* s for string *)
585 := Show.show (invert_expr.smart_App_curried (reval_twos_complement _) (arg_name, tt)).
586
587 Definition selectznz : Pipeline.ErrorT _ := Primitives.selectznz n machine_wordsize.
588 Definition sselectznz (prefix : string)
589 : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))
590 := Primitives.sselectznz n machine_wordsize prefix.
591
592 Definition copy : Pipeline.ErrorT _ := Primitives.copy n machine_wordsize.
593 Definition scopy (prefix : string)
594 : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))
595 := Primitives.scopy n machine_wordsize prefix.
596
597 Definition msat
598 := Pipeline.BoundsPipeline
599 true (* subst01 *)
600 possible_values
601 (reified_msat_gen
602 @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify sat_limbs @ GallinaReify.Reify m)
603 tt
604 (Some larger_bounds).
605
606 Definition smsat (prefix : string)
607 : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))
608 := Eval cbv beta in
609 FromPipelineToString!
610 machine_wordsize prefix "msat" msat
611 (docstring_with_summary_from_lemma!
612 prefix
613 (fun fname => [text_before_function_name ++ fname ++ " returns the saturated representation of the prime modulus."]%string)
614 (msat_correct machine_wordsize n m valid)).
615
616 Definition divstep_precomp
617 := Pipeline.BoundsPipeline
618 true (* subst01 *)
619 possible_values
620 (reified_encode_gen
621 @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify n @ GallinaReify.Reify m @ GallinaReify.Reify m' @ GallinaReify.Reify divstep_precompmod)
622 tt
623 (Some bounds).
624
625 Definition sdivstep_precomp (prefix : string)
626 : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))
627 := Eval cbv beta in
628 FromPipelineToString!
629 machine_wordsize prefix "divstep_precomp" divstep_precomp
630 (docstring_with_summary_from_lemma!
631 prefix
632 (fun fname => [text_before_function_name ++ fname ++ " returns the precomputed value for Bernstein-Yang-inversion (in montgomery form)."]%string)
633 (divstep_precomp_correct machine_wordsize n m valid from_montgomery_res)).
634
635 Definition divstep
636 := Pipeline.BoundsPipeline
637 false (* subst01 *)
638 possible_values
639 (reified_divstep_gen
640 @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify sat_limbs @ GallinaReify.Reify n @ GallinaReify.Reify m)
641 (divstep_input)
642 (divstep_output).
643
644 Definition sdivstep (prefix : string)
645 : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))
646 := Eval cbv beta in
647 FromPipelineToString!
648 machine_wordsize prefix "divstep" divstep
649 (docstring_with_summary_from_lemma!
650 prefix
651 (fun fname : string => [text_before_function_name ++ fname ++ " computes a divstep."]%string)
652 (divstep_correct machine_wordsize n m valid from_montgomery_res)).
653
654 Lemma bounded_by_of_valid x
655 (H : valid x)
656 : ZRange.type.base.option.is_bounded_by (t:=base.type.list base.type.Z) (Some bounds) x = true.
657 Proof using curve_good.
658 pose proof use_curve_good as use_curve_good.
659 clear -H use_curve_good curve_good.
660 destruct H as [H _]; destruct_head'_and.
661 cbv [small] in H.
662 cbv [ZRange.type.base.option.is_bounded_by bounds saturated_bounds word_bound].
663 replace n with (List.length x) by now rewrite H, Partition.length_partition.
664 rewrite <- map_const, fold_andb_map_map1, fold_andb_map_iff.
665 cbv [ZRange.type.base.is_bounded_by is_bounded_by_bool lower upper type_base].
666 split; [ reflexivity | ].
667 intros *; rewrite combine_same, in_map_iff, Bool.andb_true_iff, !Z.leb_le.
668 intros; destruct_head'_ex; destruct_head'_and; subst *; cbn [fst snd].
669 match goal with
670 | [ H : In ?v x |- _ ] => revert v H
671 end.
672 rewrite H.
673 generalize (eval (n:=n) machine_wordsize x).
674 cbn [base.interp base.base_interp].
675 generalize n.
676 intro n'.
677 induction n' as [|n' IHn'].
678 { cbv [Partition.partition seq List.map In]; tauto. }
679 { intros *; rewrite Partition.partition_step, in_app_iff; cbn [List.In].
680 intros; destruct_head'_or; subst *; eauto; try tauto; [].
681 rewrite uweight_S by lia.
682 assert (0 < uweight machine_wordsize n') by now apply uwprops.
683 assert (0 < 2 ^ machine_wordsize) by auto with zarith.
684 assert (0 < 2 ^ machine_wordsize * uweight machine_wordsize n') by nia.
685 rewrite <- Z.mod_pull_div by lia.
686 rewrite Z.le_sub_1_iff.
687 auto with zarith. }
688 Qed.
689
690 (* XXX FIXME *)
691 Lemma bounded_by_prime_bounds_of_valid_gen lgr n' x
692 (Hlgr : 0 < lgr)
693 (Hs : s = 2^Z.log2 s)
694 (Hs' : s <= uweight lgr n')
695 (H : WordByWordMontgomery.valid lgr n' m x)
696 : ZRange.type.base.option.is_bounded_by (t:=base.type.list base.type.Z) (Some (List.map (fun v => Some r[0~>v]%zrange) (Partition.partition (uweight lgr) n' (s-1)))) x = true.
697 Proof using curve_good.
698 pose proof use_curve_good as use_curve_good.
699 clear -H use_curve_good curve_good Hlgr Hs Hs'.
700 destruct H as [H ?]; destruct_head'_and.
701 cbv [small] in H.
702 cbv [ZRange.type.base.option.is_bounded_by].
703 replace n' with (List.length x) by now rewrite H, Partition.length_partition.
704 rewrite fold_andb_map_map1, fold_andb_map_iff.
705 split; [ now autorewrite with distr_length | ].
706 cbv [ZRange.type.base.is_bounded_by is_bounded_by_bool lower upper].
707 rewrite H; autorewrite with distr_length.
708 intros [v1 v0]; cbn [fst snd].
709 rename x into x'.
710 generalize dependent (eval (n:=n') lgr x').
711 replace m with (s - c) in * by easy.
712 intro x; intros ??? H; subst x'.
713 eapply In_nth_error in H; destruct H as [i H].
714 rewrite nth_error_combine in H.
715 break_match_hyps; try discriminate; []; Option.inversion_option; Prod.inversion_prod; subst.
716 cbv [Partition.partition] in *.
717 apply nth_error_map_ex in Heqo; apply nth_error_map_ex in Heqo0; destruct Heqo as (?&?&?), Heqo0 as (?&?&?).
718 rewrite nth_error_seq in *.
719 break_match_hyps; try discriminate; Option.inversion_option; Prod.inversion_prod; subst.
720 rewrite ?Nat.add_0_l.
721 assert (0 <= x < s) by lia.
722 replace s with (2^Z.log2 s) by easy.
723 assert (1 < s) by lia.
724 assert (0 < Z.log2 s) by now apply Z.log2_pos.
725 assert (1 < 2^Z.log2 s) by auto with zarith.
726 generalize dependent (Z.log2 s); intro lgs; intros.
727
728 edestruct (uwprops lgr); try lia.
729 assert (forall i : nat, 0 <= uweight lgr i) by (intro z; specialize (weight_positive z); lia).
730 apply Bool.andb_true_intro; split; apply OrdersEx.Z_as_OT.leb_le;
731 [apply Z.div_nonneg | apply Z.div_le_mono_nonneg]; trivial.
732 apply Z.mod_pos_bound; trivial.
733
734 cbv [uweight].
735 cbv [weight].
736 rewrite Z.div_1_r.
737 rewrite Z.opp_involutive.
738 rewrite <-2Z.land_ones by nia.
739 rewrite Z.sub_1_r, <-Z.ones_equiv.
740 rewrite Z.land_ones_ones.
741 destruct ((lgs <? 0) || (lgr * Z.of_nat (S i) <? 0)) eqn:?.
742 { rewrite Z.land_ones, Z.ones_equiv, <-Z.sub_1_r by nia.
743 pose proof Z.le_max_r lgs (lgr*Z.of_nat (S i)).
744 etransitivity.
745 2:rewrite <- Z.sub_le_mono_r.
746 2:eapply Z.pow_le_mono_r; try lia; eassumption.
747 eapply Z.le_sub_1_iff, Z.mod_pos_bound, Z.pow_pos_nonneg; nia. }
748 rewrite (Z.ones_equiv (Z.min _ _)), <-Z.sub_1_r.
749 enough (Z.land x (Z.ones (lgr * Z.of_nat (S i))) < 2 ^ Z.min lgs (lgr * Z.of_nat (S i))) by lia.
750 eapply Testbit.Z.testbit_false_bound. nia.
751 intros j ?; assert (Z.min lgs (lgr * Z.of_nat (S i)) <= j) by lia.
752 rewrite Hs in *. revert H; intros.
753 rewrite <-(Z.mod_small x (2^lgs)) by lia.
754 rewrite OrdersEx.Z_as_OT.land_spec.
755 destruct (Zmin_irreducible lgs (lgr * Z.of_nat (S i))) as [HH|HH]; rewrite HH in *; clear HH.
756 { rewrite Z.mod_pow2_bits_high; trivial; lia. }
757 { rewrite OrdersEx.Z_as_DT.ones_spec_high, Bool.andb_false_r; trivial; nia. }
758 Qed.
759
760 Lemma length_of_valid lgr n' x
761 (H : WordByWordMontgomery.valid lgr n' m x)
762 : List.length x = n'.
763 Proof using Type.
764 destruct H as [H _]; rewrite H.
765 now autorewrite with distr_length.
766 Qed.
767
768 Lemma bounded_by_prime_bounds_of_valid x
769 (H : valid x)
770 : ZRange.type.base.option.is_bounded_by (t:=base.type.list base.type.Z) (Some prime_bounds) x = true.
771 Proof using curve_good.
772 pose proof use_curve_good as use_curve_good.
773 destruct_head'_and.
774 now apply bounded_by_prime_bounds_of_valid_gen.
775 Qed.
776
777 Lemma bounded_by_prime_bytes_bounds_of_bytes_valid x
778 (H : bytes_valid x)
779 : ZRange.type.base.option.is_bounded_by (t:=base.type.list base.type.Z) (Some prime_bytes_bounds) x = true.
780 Proof using curve_good.
781 pose proof use_curve_good as use_curve_good.
782 destruct_head'_and.
783 now apply bounded_by_prime_bounds_of_valid_gen.
784 Qed.
785
786 Lemma weight_bounded_of_bytes_valid x
787 (H : bytes_valid x)
788 : 0 <= eval 8 (n:=n_bytes) x < weight machine_wordsize 1 n.
789 Proof using curve_good.
790 cbv [bytes_valid] in H.
791 destruct H as [_ H].
792 pose proof use_curve_good.
793 cbv [uweight] in *; destruct_head'_and; lia.
794 Qed.
795
796 Local Ltac solve_extra_bounds_side_conditions :=
797 solve [ cbn [lower upper fst snd] in *; Bool.split_andb; Z.ltb_to_lt; lia
798 | cbv [valid small eval uweight n_bytes] in *; destruct_head'_and; auto
799 | now apply weight_bounded_of_bytes_valid
800 | eapply length_of_valid; eassumption ].
801
802 Hint Rewrite
803 (@eval_mulmod machine_wordsize n m r' m')
804 (@eval_squaremod machine_wordsize n m r' m')
805 (@eval_addmod machine_wordsize n m r' m')
806 (@eval_submod machine_wordsize n m r' m')
807 (@eval_oppmod machine_wordsize n m r' m')
808 (@eval_from_montgomerymod machine_wordsize n m r' m')
809 (@eval_to_montgomerymod machine_wordsize n m r' m')
810 (@eval_encodemod machine_wordsize n m r' m')
811 eval_to_bytesmod
812 eval_from_bytesmod
813 using solve [ eauto using length_of_valid | congruence | solve_extra_bounds_side_conditions ] : push_eval.
814 (* needed for making [autorewrite] fast enough *)
815 Local Opaque
816 WordByWordMontgomery.WordByWordMontgomery.onemod
817 WordByWordMontgomery.WordByWordMontgomery.from_montgomerymod
818 WordByWordMontgomery.WordByWordMontgomery.to_montgomerymod
819 WordByWordMontgomery.WordByWordMontgomery.mulmod
820 WordByWordMontgomery.WordByWordMontgomery.squaremod
821 WordByWordMontgomery.WordByWordMontgomery.encodemod
822 WordByWordMontgomery.WordByWordMontgomery.addmod
823 WordByWordMontgomery.WordByWordMontgomery.submod
824 WordByWordMontgomery.WordByWordMontgomery.oppmod
825 WordByWordMontgomery.WordByWordMontgomery.to_bytesmod.
826 Hint Unfold eval zeromod onemod : push_eval.
827
828 Local Ltac prove_correctness op_correct :=
829 let dont_clear H := first [ constr_eq H curve_good ] in
830 let Hres := match goal with H : _ = Success _ |- _ => H end in
831 let H := fresh in
832 pose proof use_curve_good as H;
833 (* I want to just use [clear -H Hres], but then I can't use any lemmas in the section because of COQBUG(https://github.com/coq/coq/issues/8153) *)
834 repeat match goal with
835 | [ H' : _ |- _ ]
836 => tryif first [ has_body H' | constr_eq H' H | constr_eq H' Hres | dont_clear H' ]
837 then fail
838 else clear H'
839 end;
840 cbv zeta in *;
841 destruct_head'_and;
842 let f := match type of Hres with ?f = _ => head f end in
843 try cbv [f] in *;
844 hnf;
845 PipelineTactics.do_unfolding;
846 try (let m := match goal with m := _ - Associational.eval _ |- _ => m end in
847 cbv [m] in * );
848 intros;
849 lazymatch goal with
850 | [ |- _ <-> _ ] => idtac
851 | [ |- _ = _ ] => idtac
852 | _ => split; [ | try split ];
853 cbv [small]
854 end;
855 PipelineTactics.use_compilers_correctness Hres;
856 repeat first [ reflexivity
857 | now apply bounded_by_of_valid
858 | now apply bounded_by_prime_bounds_of_valid
859 | now apply bounded_by_prime_bytes_bounds_of_bytes_valid
860 | now apply weight_bounded_of_bytes_valid
861 | solve [ eapply op_correct; try eassumption; solve_extra_bounds_side_conditions ]
862 | progress autorewrite with interp_gen_cache interp_extra
863 | progress autorewrite with push_eval
864 | progress autounfold with push_eval
865 | progress autorewrite with distr_length in *
866 | solve [ cbv [valid small eval uweight n_bytes] in *; destruct_head'_and; auto ] ].
867
868 (** TODO: DESIGN DECISION:
869
870 The correctness lemmas for most of the montgomery things are
871 parameterized over a `from_montgomery`. When filling this in
872 for, e.g., mul-correctness, should I use `from_montgomery`
873 from arithmetic, or should I use `Interp
874 reified_from_montgomery` (the post-pipeline version), and take
875 in success of the pipeline on `from_montgomery` as well? *)
876
877 Lemma mul_correct res
878 (Hres : mul = Success res)
879 : mul_correct machine_wordsize n m valid from_montgomery_res (Interp res).
880 Proof using curve_good. prove_correctness mulmod_correct. Qed.
881
882 Lemma Wf_mul res (Hres : mul = Success res) : Wf res.
883 Proof using Type. prove_pipeline_wf (). Qed.
884
885 Lemma square_correct res
886 (Hres : square = Success res)
887 : square_correct machine_wordsize n m valid from_montgomery_res (Interp res).
888 Proof using curve_good. prove_correctness squaremod_correct. Qed.
889
890 Lemma Wf_square res (Hres : square = Success res) : Wf res.
891 Proof using Type. prove_pipeline_wf (). Qed.
892
893 Lemma add_correct res
894 (Hres : add = Success res)
895 : add_correct machine_wordsize n m valid from_montgomery_res (Interp res).
896 Proof using curve_good. prove_correctness addmod_correct. Qed.
897
898 Lemma Wf_add res (Hres : add = Success res) : Wf res.
899 Proof using Type. prove_pipeline_wf (). Qed.
900
901 Lemma sub_correct res
902 (Hres : sub = Success res)
903 : sub_correct machine_wordsize n m valid from_montgomery_res (Interp res).
904 Proof using curve_good. prove_correctness submod_correct. Qed.
905
906 Lemma Wf_sub res (Hres : sub = Success res) : Wf res.
907 Proof using Type. prove_pipeline_wf (). Qed.
908
909 Lemma opp_correct res
910 (Hres : opp = Success res)
911 : opp_correct machine_wordsize n m valid from_montgomery_res (Interp res).
912 Proof using curve_good. prove_correctness oppmod_correct. Qed.
913
914 Lemma Wf_opp res (Hres : opp = Success res) : Wf res.
915 Proof using Type. prove_pipeline_wf (). Qed.
916
917 Lemma from_montgomery_correct res
918 (Hres : from_montgomery = Success res)
919 : from_montgomery_correct machine_wordsize n m r' valid (Interp res).
920 Proof using curve_good. prove_correctness from_montgomerymod_correct. Qed.
921
922 Lemma Wf_from_montgomery res (Hres : from_montgomery = Success res) : Wf res.
923 Proof using Type. prove_pipeline_wf (). Qed.
924
925 Lemma to_montgomery_correct res
926 (Hres : to_montgomery = Success res)
927 : to_montgomery_correct machine_wordsize n m valid from_montgomery_res (Interp res).
928 Proof using curve_good. prove_correctness to_montgomerymod_correct. Qed.
929
930 Lemma Wf_to_montgomery res (Hres : to_montgomery = Success res) : Wf res.
931 Proof using Type. prove_pipeline_wf (). Qed.
932
933 Lemma nonzero_correct res
934 (Hres : nonzero = Success res)
935 : nonzero_correct machine_wordsize n m valid from_montgomery_res (Interp res).
936 Proof using curve_good. prove_correctness nonzeromod_correct. Qed.
937
938 Lemma Wf_nonzero res (Hres : nonzero = Success res) : Wf res.
939 Proof using Type. prove_pipeline_wf (). Qed.
940
941 Lemma to_bytes_correct res
942 (Hres : to_bytes = Success res)
943 : to_bytes_correct machine_wordsize n n_bytes m valid (Interp res).
944 Proof using curve_good. prove_correctness to_bytesmod_correct. Qed.
945
946 Lemma Wf_to_bytes res (Hres : to_bytes = Success res) : Wf res.
947 Proof using Type. prove_pipeline_wf (). Qed.
948
949 Lemma from_bytes_correct res
950 (Hres : from_bytes = Success res)
951 : from_bytes_correct machine_wordsize n n_bytes m valid bytes_valid (Interp res).
952 Proof using curve_good. prove_correctness eval_from_bytesmod_and_partitions. Qed.
953
954 Lemma Wf_from_bytes res (Hres : from_bytes = Success res) : Wf res.
955 Proof using Type. prove_pipeline_wf (). Qed.
956
957 Strategy -1000 [encode]. (* if we don't tell the kernel to unfold this early, then [Qed] seems to run off into the weeds *)
958 Lemma encode_correct res
959 (Hres : encode = Success res)
960 : encode_correct machine_wordsize n m valid from_montgomery_res (Interp res).
961 Proof using curve_good. prove_correctness encodemod_correct. Qed.
962
963 Lemma Wf_encode res (Hres : encode = Success res) : Wf res.
964 Proof using Type. prove_pipeline_wf (). Qed.
965
966 Strategy -1000 [encode_word]. (* if we don't tell the kernel to unfold this early, then [Qed] seems to run off into the weeds *)
967 Lemma encode_word_correct res
968 (Hres : encode_word = Success res)
969 : encode_word_correct machine_wordsize n m valid from_montgomery_res (Interp res).
970 Proof using curve_good. prove_correctness encodemod_correct. Qed.
971
972 Lemma Wf_encode_word res (Hres : encode_word = Success res) : Wf res.
973 Proof using Type. prove_pipeline_wf (). Qed.
974
975 Strategy -1000 [zero]. (* if we don't tell the kernel to unfold this early, then [Qed] seems to run off into the weeds *)
976 Lemma zero_correct res
977 (Hres : zero = Success res)
978 : zero_correct machine_wordsize n m valid from_montgomery_res (Interp res).
979 Proof using curve_good. prove_correctness encodemod_correct. Qed.
980
981 Lemma Wf_zero res (Hres : zero = Success res) : Wf res.
982 Proof using Type. prove_pipeline_wf (). Qed.
983
984 Strategy -1000 [one]. (* if we don't tell the kernel to unfold this early, then [Qed] seems to run off into the weeds *)
985 Lemma one_correct res
986 (Hres : one = Success res)
987 : one_correct machine_wordsize n m valid from_montgomery_res (Interp res).
988 Proof using curve_good. prove_correctness encodemod_correct. Qed.
989
990 Lemma Wf_one res (Hres : one = Success res) : Wf res.
991 Proof using Type. prove_pipeline_wf (). Qed.
992
993 Local Opaque Pipeline.BoundsPipeline. (* need this or else [eapply Pipeline.BoundsPipeline_correct in Hres] takes forever *)
994
995 Lemma selectznz_correct res
996 (Hres : selectznz = Success res)
997 : selectznz_correct saturated_bounds (Interp res).
998 Proof using curve_good. apply Primitives.selectznz_correct, Hres. Qed.
999
1000 Lemma Wf_selectznz res (Hres : selectznz = Success res) : Wf res.
1001 Proof using Type. revert Hres; cbv [selectznz]; apply Wf_selectznz. Qed.
1002
1003 Lemma copy_correct res
1004 (Hres : copy = Success res)
1005 : copy_correct saturated_bounds (Interp res).
1006 Proof using curve_good. Primitives.prove_correctness use_curve_good. Qed.
1007
1008 Lemma Wf_copy res (Hres : copy = Success res) : Wf res.
1009 Proof using Type. revert Hres; cbv [copy]; apply Wf_copy. Qed.
1010
1011 Section ring.
1012 Context from_montgomery_res (Hfrom_montgomery : from_montgomery = Success from_montgomery_res)
1013 mul_res (Hmul : mul = Success mul_res)
1014 add_res (Hadd : add = Success add_res)
1015 sub_res (Hsub : sub = Success sub_res)
1016 opp_res (Hopp : opp = Success opp_res)
1017 encode_res (Hencode : encode = Success encode_res)
1018 zero_res (Hzero : zero = Success zero_res)
1019 one_res (Hone : one = Success one_res).
1020
1021 Definition GoodT : Prop
1022 := GoodT
1023 machine_wordsize n m valid
1024 (Interp from_montgomery_res)
1025 (Interp mul_res)
1026 (Interp add_res)
1027 (Interp sub_res)
1028 (Interp opp_res)
1029 (Interp encode_res)
1030 (Interp zero_res)
1031 (Interp one_res).
1032
1033 Theorem Good : GoodT.
1034 Proof using curve_good Hfrom_montgomery Hmul Hadd Hsub Hopp Hencode Hzero Hone.
1035 pose proof use_curve_good; cbv zeta in *; destruct_head'_and.
1036 eapply Good.
1037 all: repeat first [ assumption
1038 | apply from_montgomery_correct
1039 | lia ].
1040 all: hnf; intros.
1041 all: push_Zmod; erewrite !(fun v Hv => proj1 (from_montgomery_correct _ Hfrom_montgomery v Hv)), <- !eval_from_montgomerymod; try eassumption; pull_Zmod.
1042 all: repeat first [ assumption
1043 | lazymatch goal with
1044 | [ |- context[mul_res] ] => apply mul_correct
1045 | [ |- context[add_res] ] => apply add_correct
1046 | [ |- context[sub_res] ] => apply sub_correct
1047 | [ |- context[opp_res] ] => apply opp_correct
1048 | [ |- context[encode_res] ] => apply encode_correct
1049 | [ |- context[zero_res] ] => apply zero_correct
1050 | [ |- context[one_res] ] => apply one_correct
1051 end ].
1052 Qed.
1053 End ring.
1054
1055 Section for_stringification.
1056 Local Open Scope string_scope.
1057 Local Open Scope list_scope.
1058
1059 Definition known_functions
1060 := [("mul", wrap_s smul);
1061 ("square", wrap_s ssquare);
1062 ("add", wrap_s sadd);
1063 ("sub", wrap_s ssub);
1064 ("opp", wrap_s sopp);
1065 ("from_montgomery", wrap_s sfrom_montgomery);
1066 ("to_montgomery", wrap_s sto_montgomery);
1067 ("nonzero", wrap_s snonzero);
1068 ("selectznz", wrap_s sselectznz);
1069 ("to_bytes", wrap_s sto_bytes);
1070 ("from_bytes", wrap_s sfrom_bytes);
1071 ("one", wrap_s sone);
1072 ("msat", wrap_s smsat);
1073 ("divstep_precomp", wrap_s sdivstep_precomp);
1074 ("divstep", wrap_s sdivstep)].
1075
1076 Definition valid_names : string := Eval compute in String.concat ", " (List.map (@fst _ _) known_functions).
1077
1078 (** Note: If you change the name or type signature of this
1079 function, you will need to update the code in CLI.v *)
1080 Definition Synthesize (comment_header : list string) (function_name_prefix : string) (requests : list string)
1081 : list (synthesis_output_kind * string * Pipeline.M (list string))
1082 := Primitives.Synthesize
1083 machine_wordsize valid_names known_functions (fun _ => nil) all_typedefs!
1084 check_args
1085 (ToString.comment_file_header_block
1086 (comment_header
1087 ++ [""
1088 ; "Computed values:"]
1089 ++ (List.map
1090 (fun s => " " ++ s)%string
1091 ((ToString.prefix_and_indent "eval z = " [seval "z"])
1092 ++ (ToString.prefix_and_indent "bytes_eval z = " [sbytes_eval "z"])
1093 ++ (ToString.prefix_and_indent "twos_complement_eval z = " [seval_twos_complement "z"])))))
1094 function_name_prefix requests.
1095 End for_stringification.
1096 End __.
1097
1098 Module Export Hints.
1099 #[global]
1100 Hint Opaque
1101 mul
1102 square
1103 add
1104 sub
1105 opp
1106 from_montgomery
1107 to_montgomery
1108 nonzero
1109 to_bytes
1110 from_bytes
1111 encode
1112 encode_word
1113 zero
1114 one
1115 selectznz
1116 copy
1117 : wf_op_cache.
1118 #[global]
1119 Hint Immediate
1120 Wf_mul
1121 Wf_square
1122 Wf_add
1123 Wf_sub
1124 Wf_opp
1125 Wf_from_montgomery
1126 Wf_to_montgomery
1127 Wf_nonzero
1128 Wf_to_bytes
1129 Wf_from_bytes
1130 Wf_encode
1131 Wf_encode_word
1132 Wf_zero
1133 Wf_one
1134 Wf_selectznz
1135 Wf_copy
1136 : wf_op_cache.
1137 End Hints.