Debian Codegraph @

src/Bedrock/End2End/X25519/GarageDoorTop.v

raw
1 From Coq Require Import String.
2 From Coq Require Import List.
3 From Coq Require Import ZArith.
4 Require Import Crypto.Spec.Curve25519.
5 Require Import bedrock2.Map.Separation.
6 Require Import bedrock2.Syntax.
7 Require Import compiler.Pipeline.
8 Require Import compiler.Symbols.
9 Require Import compiler.MMIO.
10 Require Import coqutil.Word.Bitwidth32.
11 Require Import Crypto.Arithmetic.PrimeFieldTheorems.
12 Require Import Crypto.Bedrock.Field.Synthesis.New.UnsaturatedSolinas.
13 Require Import Crypto.Bedrock.Group.AdditionChains.
14 Require Import Crypto.Bedrock.Group.ScalarMult.LadderStep.
15 Require Import Crypto.Bedrock.Group.ScalarMult.CSwap.
16 Require Import Crypto.Bedrock.Group.ScalarMult.MontgomeryLadder.
17 Require Import Crypto.Bedrock.End2End.X25519.Field25519.
18 Require Import Crypto.Bedrock.End2End.X25519.MontgomeryLadder.
19 Require Import bedrock2Examples.LAN9250.
20 Require Import bedrock2Examples.lightbulb.
21 Require Import bedrock2Examples.memequal.
22 Require Import bedrock2Examples.memswap.
23 Require Import bedrock2Examples.memconst.
24 Require Import Rupicola.Examples.Net.IPChecksum.IPChecksum.
25 Require Import Crypto.Bedrock.End2End.X25519.GarageDoor.
26 Require Import bedrock2.SemanticsRelations.
27 Import Crypto.Bedrock.End2End.RupicolaCrypto.ChaCha20.
28 Local Open Scope string_scope.
29 Import Syntax Syntax.Coercions NotationsCustomEntry.
30 Import ListNotations.
31 Import Coq.Init.Byte.
32 Import coqutil.Macros.WithBaseName.
33 Import LeakageSemantics LeakageWeakestPrecondition LeakageProgramLogic SeparationLogic.
34
35 (* these wrappers exist because CompilerInvariant requires execution proofs with arbitrary locals in the starting state, which ProgramLogic does not support *)
36 Definition init := func! { initfn() } .
37 Definition loop := func! { loopfn() } .
38 Definition memconst_pk := memconst garageowner.
39 Definition ip_checksum := ip_checksum_br2fn.
40
41 Definition funcs :=
42 &[, (* Main loop *) init; loop; initfn; loopfn;
43
44 (* Ethernet & SPI drivers *)
45 lan9250_tx; recvEthernet; lan9250_init;
46 lan9250_wait_for_boot; lan9250_mac_write;
47 lan9250_writeword; lan9250_readword;
48 SPI.spi_xchg; SPI.spi_write; SPI.spi_read;
49
50 (* "Standard library" of bedrock2 *)
51 memswap; memequal; memconst_pk;
52
53 (* Generated using Rupicola *)
54 ip_checksum; chacha20_block; quarter]
55
56 (* X25519, generated code and handwritten wrappers *)
57 ++MontgomeryLadder.funcs.
58
59 (*
60 Compute (length funcs-3)%nat. (* functions excluding main-loop boilerplate *)
61 Compute ((length MontgomeryLadder.funcs - 2 + 3))%nat. (* generated functions *)
62 Compute (length funcs-3 - (length MontgomeryLadder.funcs - 2 + 3))%nat. (* handwritten functions *)
63 Compute bedrock2.ToCString.c_module funcs.
64 *)
65
66 Lemma chacha20_ok: forall functions,
67 map.get functions "chacha20_block" = Some ChaCha20.chacha20_block ->
68 map.get functions "quarter" = Some ChaCha20.quarter ->
69 ChaCha20.spec_of_chacha20 functions.
70 Proof.
71 intros.
72 simple eapply ChaCha20.chacha20_block_body_correct; [constructor | eassumption | ].
73 eapply ChaCha20.quarter_body_correct; [constructor | eassumption ].
74 Qed.
75
76 Ltac pose_correctness lem :=
77 let H := fresh in
78 pose proof (lem (map.of_list funcs)) as H;
79 unfold LeakageProgramLogic.program_logic_goal_for, ProgramLogic.program_logic_goal_for in H;
80 repeat lazymatch type of H with
81 | map.get (map.of_list _) _ = Some _ -> _ => specialize (H eq_refl)
82 end.
83
84 Import SPI.
85
86 Lemma link_loopfn {pick_sp: PickSp} : spec_of_loopfn (map.of_list funcs).
87 Proof.
88 pose_correctness loopfn_ok.
89 pose_correctness memswap.memswap_ok.
90 pose_correctness memequal_ok.
91 pose_correctness recvEthernet_ok.
92 pose_correctness lan9250_readword_ok.
93 pose_correctness spi_xchg_ok.
94 pose_correctness spi_write_ok.
95 pose_correctness spi_read_ok.
96 pose_correctness (ip_checksum_br2fn_ok I).
97 pose_correctness memmove.memmove_ok_array.
98 pose_correctness clamp.clamp_correct.
99 pose_correctness x25519_base_ok.
100 pose_correctness fe25519_from_word_correct.
101 pose_correctness fe25519_to_bytes_correct.
102 pose_correctness lan9250_tx_ok.
103 pose_correctness lan9250_writeword_ok.
104 pose_correctness x25519_ok.
105 pose_correctness fe25519_from_bytes_correct.
106 pose_correctness chacha20_ok.
107 assert (spec_of_montladder (map.of_list funcs)). {
108 unfold spec_of_montladder, ScalarMult.MontgomeryLadder.spec_of_montladder.
109 intros.
110 eapply Semantics.extend_env_call.
111 2: { eapply link_montladder. eassumption. }
112 clear. unfold funcs.
113 (* TODO this could be more computational *)
114 intros k v G.
115 unfold MontgomeryLadder.funcs, map.of_list in G.
116 rewrite ?map.get_put_dec in G.
117 repeat (destruct_one_match_hyp; [inversion G; subst; reflexivity | ]).
118 rewrite map.get_empty in G. discriminate G.
119 }
120 repeat match goal with
121 | HI: ?A -> _, HA: ?A |- _ => specialize (HI HA)
122 end.
123 assumption.
124 Qed.
125
126 Require compiler.ToplevelLoop.
127 Definition ml: MemoryLayout.MemoryLayout(word:=Naive.word32) := {|
128 MemoryLayout.code_start := word.of_Z 0x20400000;
129 MemoryLayout.code_pastend := word.of_Z 0x21400000;
130 MemoryLayout.heap_start := word.of_Z 0x80000000;
131 MemoryLayout.heap_pastend := word.of_Z 0x80002000;
132 MemoryLayout.stack_start := word.of_Z 0x80002000;
133 MemoryLayout.stack_pastend := word.of_Z 0x80004000;
134 |}.
135
136 Lemma ml_ok : MemoryLayout.MemoryLayoutOk ml. Proof. split; cbv; trivial; inversion 1. Qed.
137
138 Local Instance : FlatToRiscvCommon.bitwidth_iset 32 Decode.RV32IM := eq_refl.
139 Derive garagedoor_compiler_result SuchThat
140 (ToplevelLoop.compile_prog (string_keyed_map:[email protected]) MMIO.compile_ext_call ml funcs
141 = Success garagedoor_compiler_result)
142 As garagedoor_compiler_result_ok.
143 Proof.
144 match goal with x := _ |- _ => cbv delta [x]; clear x end.
145 vm_compute.
146 match goal with |- @Success ?A ?x = Success ?e => is_evar e;
147 exact (@eq_refl (result A) (@Success A x)) end.
148 Qed. Optimize Heap.
149
150 Definition garagedoor_stack_size := snd garagedoor_compiler_result.
151 Definition garagedoor_finfo := snd (fst garagedoor_compiler_result).
152 Definition garagedoor_insns := fst (fst garagedoor_compiler_result).
153 Definition garagedoor_bytes := Pipeline.instrencode garagedoor_insns.
154 (*
155 Compute length garagedoor_bytes.
156 *)
157 Definition garagedoor_symbols : list byte := Symbols.symbols garagedoor_finfo.
158
159 Require Import compiler.CompilerInvariant.
160 Require Import compiler.NaiveRiscvWordProperties.
161 Local Existing Instance SortedListString.map.
162 Import TracePredicate TracePredicateNotations SPI lightbulb_spec.
163 Import GarageDoor.
164
165 Lemma compiler_emitted_valid_instructions :
166 bverify.bvalidInstructions Decode.RV32IM garagedoor_insns = true.
167 Proof. vm_cast_no_check (eq_refl true). Qed.
168
169 Import SPI riscv.Platform.RiscvMachine.
170 Definition only_mmio_satisfying P t :=
171 exists mmios, mmio_trace_abstraction_relation mmios t /\ P mmios.
172
173 Local Notation labeled_transitions := stateful.
174 Local Notation boot_seq := BootSeq.
175
176 Definition protocol_spec l := exists s s', labeled_transitions protocol_step s s' l.
177 Definition io_spec : list _ -> Prop := only_mmio_satisfying (boot_seq +++ protocol_spec).
178
179 Import ExprImpEventLoopSpec.
180 Definition garagedoor_spec : ProgramSpec := {|
181 datamem_start := MemoryLayout.heap_start ml;
182 datamem_pastend := MemoryLayout.heap_pastend ml;
183 goodTrace := io_spec;
184 isReady t m := exists s s', only_mmio_satisfying (boot_seq +++ labeled_transitions protocol_step s' s) t /\ exists bs R, memrep bs R s m |}.
185
186 Import DestructHead.
187 Lemma only_mmio_satisfying_app P Q t :
188 only_mmio_satisfying (P +++ Q) t <->
189 (only_mmio_satisfying P +++ only_mmio_satisfying Q) t.
190 Proof.
191 cbv [only_mmio_satisfying mmio_trace_abstraction_relation]; split; intros;
192 repeat (destruct_head' @ex; destruct_head' @Logic.and; destruct_head' @concat);
193 subst; eauto using Forall2_app, concat_app.
194 eapply Forall2_app_inv_l in H; case H as (?&?&?&?&?); subst.
195 eapply concat_app; eauto.
196 Qed.
197 Lemma only_mmio_satisfying_ex [A] P t :
198 only_mmio_satisfying (fun t => exists x : A, P x t) t <->
199 exists x : A, only_mmio_satisfying (P x) t.
200 Proof.
201 cbv [only_mmio_satisfying mmio_trace_abstraction_relation]; split; intros;
202 repeat (destruct_head' @ex; destruct_head' @Logic.and);
203 eauto using Forall2_app.
204 Qed.
205 Import Coq.Classes.Morphisms.
206 Global Instance Proper_only_mmio_satisfying :
207 Proper (Morphisms.pointwise_relation _ iff ==> Morphisms.pointwise_relation _ iff) only_mmio_satisfying.
208 Proof.
209 cbv [only_mmio_satisfying mmio_trace_abstraction_relation].
210 split; intros (?&?&?); eexists; split; eauto; eapply H; eauto.
211 Qed.
212 Lemma concat_ex_r A B P Q (t : list A) :
213 Morphisms.pointwise_relation (list A) iff
214 (P +++ (fun t => exists x : B, Q x t)) (fun t => exists x : B, (P +++ Q x) t).
215 Proof.
216 repeat intro;
217 unfold "+++"; split; intros;
218 repeat (destruct_head' @ex; destruct_head' @Logic.and; destruct_head' @concat);
219 subst; eauto 6.
220 Qed.
221
222 Lemma good_trace_from_isReady a a0 : isReady garagedoor_spec a a0 ->
223 isReady garagedoor_spec a a0 /\
224 ExprImpEventLoopSpec.goodTrace garagedoor_spec a.
225 Proof.
226 cbv [isReady goodTrace garagedoor_spec io_spec protocol_spec]; intuition eauto;
227 repeat (destruct_head' @ex; destruct_head' @Logic.and).
228 eapply Proper_only_mmio_satisfying.
229 { intros ?. eapply concat_ex_r; eauto. }
230 eapply only_mmio_satisfying_ex; eexists.
231 eapply Proper_only_mmio_satisfying.
232 { intros ?. eapply concat_ex_r; eauto. }
233 eapply only_mmio_satisfying_ex; eexists.
234 eauto.
235 Qed.
236
237 Lemma link_initfn {pick_sp: PickSp} : spec_of_initfn (map.of_list funcs).
238 Proof.
239 pose_correctness initfn_ok.
240 pose_correctness lan9250_init_ok.
241 pose_correctness lan9250_wait_for_boot_ok.
242 pose_correctness lan9250_mac_write_ok.
243 pose_correctness lan9250_readword_ok.
244 pose_correctness lan9250_writeword_ok.
245 pose_correctness spi_xchg_ok.
246 pose_correctness spi_write_ok.
247 pose_correctness spi_read_ok.
248 unfold spec_of_memconst_pk in *.
249 pose_correctness (memconst_ok "memconst_pk" garageowner).
250 repeat match goal with
251 | HI: ?A -> _, HA: ?A |- _ => specialize (HI HA)
252 end.
253 assumption.
254 Qed. Optimize Heap.
255
256 Import Word.Naive.
257 Import ToplevelLoop GoFlatToRiscv regs_initialized LowerPipeline.
258 Import bedrock2.Map.Separation. Local Open Scope sep_scope.
259 Require Import bedrock2.ReversedListNotations.
260 Local Notation run1 := (mcomp_sat (run1 Decode.RV32IM)).
261 Local Notation RiscvMachine := MetricRiscvMachine.
262 Local Notation MMIO := (string * word.rep * word.rep)%type.
263 Goal True.
264 pose (fun bs => lan9250_writepacket _ (bs : list byte) : list MMIO -> Prop).
265 pose (run1 : RiscvMachine -> (RiscvMachine -> Prop) -> Prop).
266 pose (always(iset:=Decode.RV32IM) : (RiscvMachine -> Prop) -> RiscvMachine -> Prop).
267 Abort.
268
269 Implicit Types mach : RiscvMachine.
270 Local Coercion word.unsigned : word.rep >-> Z.
271
272 Definition initial_conditions mach :=
273 0x20400000 = mach.(getPc) /\
274 [] = mach.(getLog) /\
275 Some [] = mach.(getTrace) /\
276 mach.(getNextPc) = word.add mach.(getPc) (word.of_Z 4) /\
277 regs_initialized (getRegs mach) /\
278 (forall a : word32, code_start ml <= a < code_pastend ml -> In a (getXAddrs mach)) /\
279 valid_machine mach /\
280 (imem (code_start ml) (code_pastend ml) garagedoor_insns ⋆
281 mem_available (heap_start ml) (heap_pastend ml) ⋆
282 mem_available (stack_start ml) (stack_pastend ml)) (getMem mach).
283
284 Lemma initial_conditions_sufficient mach :
285 initial_conditions mach ->
286 CompilerInvariant.initial_conditions compile_ext_call ml garagedoor_spec mach.
287 Proof.
288 intros (? & ? & ? & ? & ? & ? & ? & ?).
289 econstructor.
290 eexists garagedoor_insns.
291 eexists garagedoor_finfo.
292 eexists garagedoor_stack_size.
293 rewrite garagedoor_compiler_result_ok; ssplit; trivial using compiler_emitted_valid_instructions; try congruence.
294 2,3:vm_compute; inversion 1.
295 econstructor (* ProgramSatisfiesSpec *).
296 1: vm_compute; reflexivity.
297 1: instantiate (1:=snd init).
298 3: instantiate (1:=snd loop).
299 1,3: exact eq_refl.
300 1,2: cbv [hl_inv]; intros; eapply metricleakage_to_leakage_exec; eapply LeakageWeakestPreconditionProperties.sound_cmd.
301 3: { eapply word.unsigned_inj. rewrite <-H. trivial. }
302
303 all : repeat straightline; subst args.
304 { cbv [LowerPipeline.mem_available LowerPipeline.ptsto_bytes] in *.
305 cbv [datamem_pastend datamem_start garagedoor_spec heap_start heap_pastend ml] in H7.
306 SeparationLogic.extract_ex1_and_emp_in H7.
307 change (BinIntDef.Z.of_nat (Datatypes.length anybytes) = 0x2000) in H7_emp0.
308 Tactics.rapply LeakageWeakestPreconditionProperties.Proper_call;
309 [|eapply link_initfn]; try eassumption.
310 2: {
311 rewrite <-(List.firstn_skipn 0x40 anybytes) in H7.
312 rewrite <-(List.firstn_skipn 0x20 (List.skipn _ anybytes)) in H7.
313 do 2 seprewrite_in @Array.bytearray_append H7.
314 rewrite 2firstn_length, skipn_length, 2Nat2Z.inj_min, Nat2Z.inj_sub, H7_emp0 in H7.
315 split.
316 { use_sep_assumption. cancel. cancel_seps_at_indices 0%nat 0%nat; [|ecancel_done].
317 Morphisms.f_equiv. }
318 { rewrite firstn_length, skipn_length. Lia.lia. }
319 { Lia.lia. } }
320 intros ? ? m ? ?; repeat straightline; eapply good_trace_from_isReady.
321 subst a0; rewrite app_nil_r.
322 lazymatch goal with H: sep _ _ m |- _ => rename H into M end.
323 rewrite <-(List.firstn_skipn 0x20 (List.firstn _ anybytes)) in M.
324 rewrite <-(List.firstn_skipn 1520 (skipn 32 (skipn 64 anybytes))) in M.
325 do 2 seprewrite_in @Array.bytearray_append M.
326 rewrite ?firstn_length, ?skipn_length, ?Nat2Z.inj_min, ?Nat2Z.inj_sub, H7_emp0 in M.
327 cbv [isReady garagedoor_spec protocol_spec io_spec only_mmio_satisfying].
328 eexists (Build_state _ _), (Build_state _ _); fwd. eauto.
329 { rewrite <-app_nil_l. eapply TracePredicate.concat_app; eauto. econstructor. }
330 cbv [memrep]. ssplit.
331 { use_sep_assumption. cancel.
332 cancel_seps_at_indices 0%nat 0%nat; [reflexivity|].
333 cancel_seps_at_indices 0%nat 0%nat; [reflexivity|].
334 cancel_seps_at_indices 0%nat 0%nat; [reflexivity|].
335 ecancel_done. }
336 all : repeat rewrite ?firstn_length, ?skipn_length; try Lia.lia. }
337
338 { match goal with H : goodTrace _ _ |- _ => clear H end.
339 cbv [isReady goodTrace protocol_spec io_spec garagedoor_spec] in *; repeat straightline.
340 DestructHead.destruct_head' state.
341 Tactics.rapply LeakageWeakestPreconditionProperties.Proper_call;
342 [|eapply link_loopfn]; try eassumption.
343 intros ? ? ? ?; repeat straightline; eapply good_trace_from_isReady.
344 eexists; fwd; try eassumption.
345 cbv [only_mmio_satisfying protocol_spec io_spec] in *; repeat straightline.
346 try move H6 at bottom.
347 { subst a0. eexists; split; [eapply Forall2_app; eauto|].
348 eapply stateful_app_r, stateful_singleton; eauto. } }
349 Qed.
350
351 Theorem garagedoor_invariant_proof: exists invariant: RiscvMachine -> Prop,
352 (forall mach, initial_conditions mach -> invariant mach) /\
353 (forall mach, invariant mach -> run1 mach invariant) /\
354 (forall mach, invariant mach -> exists extend, io_spec (getLog mach ;++ extend)).
355 Proof.
356 exists (ll_inv compile_ext_call ml garagedoor_spec).
357 unshelve epose proof compiler_invariant_proofs _ _ _ _ _ _ garagedoor_spec as HCI; shelve_unifiable; try exact _.
358 { exact (naive_word_riscv_ok 5%nat). }
359 { eapply SortedListString.ok. }
360 { eapply @compile_ext_call_correct; try exact _; eapply @SortedListString.ok. }
361 { intros. cbv [compile_ext_call compile_interact]; BreakMatch.break_match; trivial. }
362 { exact ml_ok. }
363 ssplit; intros; ssplit; eapply HCI; eauto using initial_conditions_sufficient.
364 Qed.
365
366 Import OmniSmallstepCombinators.
367
368 Theorem garagedoor_correct : forall mach : RiscvMachine, initial_conditions mach ->
369 always run1 (eventually run1 (fun mach' => io_spec mach'.(getLog))) mach.
370 Proof.
371 intros ? H%initial_conditions_sufficient; revert H.
372 unshelve Tactics.rapply @always_eventually_good_trace; trivial using ml_ok, @Naive.word32_ok; cycle 1.
373 { eapply (naive_word_riscv_ok 5%nat). }
374 { eapply @SortedListString.ok. }
375 { eapply @compile_ext_call_correct; try exact _. eapply @SortedListString.ok. }
376 Qed.
377
378 (*
379 Print Assumptions link_loopfn. (* Closed under the global context *)
380 Print Assumptions garagedoor_invariant_proof. (* propositional_extensionality, functional_extensionality_dep *)
381 Print Assumptions garagedoor_correct. (* propositional_extensionality, functional_extensionality_dep *)
382 *)