Repository navigation
Expand file tree
/
Copy pathSlotCoalescingShim.lean
More file actions
712 lines (625 loc) · 31.9 KB
/
Copy pathSlotCoalescingShim.lean
File metadata and controls
712 lines (625 loc) · 31.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
/-
Copyright (c) 2026 Verity Authors. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Verity Authors
-/
import Compiler.Proofs.PackedBitfieldMetaSpec
import Compiler.Proofs.MetaSpecs
namespace Compiler.Proofs.SlotCoalescingShim
open Compiler
open Compiler.CompilationModel
open Compiler.Proofs.PackedBitfieldMetaSpec
open Compiler.Proofs.MetaSpecs
/-!
# Verified Automatic Packed-Slot Coalescing Shim (`SLOAD`/`SSTORE` Fusion, Phase 4 Track P3)
This module formalizes and verifies the compiler optimization pass that coalesces a
sequence of $N$ sub-word bitfield writes `(lens₁, v₁), …, (lensₙ, vₙ)` targeting the
same 256-bit EVM storage slot `s` (such as Uniswap v3/v4 `Slot0` packing
`sqrtPriceX96` [160b], `tick` [24b], `protocolFee` [24b], and `lpFee` [24b]) from:
- **Uncoalesced Execution (`execUncoalescedPackedWrites`)**:
$N$ sequential `(SLOAD s; setBits; SSTORE s)` pairs, costing $N \times 200$ warm gas, to
- **Coalesced Execution (`execCoalescedPackedWrites`)**:
**1 `SLOAD s`** + in-register composition of all $N$ bitfield mask/shift updates
(`applyPackedWritesInRegister`) + **1 `SSTORE s`**, costing $200$ warm gas.
Using the Three-Layer Specification Architecture:
- **Layer I (Universal Coalescing Meta-Spec & Algebraic Theorems)**:
- `execCoalescedPackedWrites_eq_uncoalesced`: exact state equivalence for every write
list `writes : List PackedFieldWrite` (including overlapping or overwriting writes),
- `coalescedPackedWrites_mem_read_of_pairwiseDisjoint` &
`coalescedSlot0_final_read_each_field`: under `PairwiseDisjointLenses`, reading each
packed field $i$ after the single coalesced `SSTORE` returns `vᵢ % 2 ^ widthᵢ`,
- `slotCoalescingVerifiedShim`: `VerifiedCompilerShim` instance certifying the pass,
- `slotCoalescing_gas_saved`: strict gas savings of $(N - 1) \times 200$ gas for all
$N \ge 2$ (saving $600$ gas per `Slot0` 4-field update).
- **Layer II (1-3 Line Projection Corollaries)**:
Direct observational equivalence, frame preservation (`fmp` and other slots), and
overwrite-fusion corollaries.
- **Layer III (`by decide`, `0 native_decide` Executable Witness Suite)**:
Kernel-checked concrete witness suite for Uniswap v3/v4 `Slot0` coalescing,
same-field overwrite fusion, and gas accounting.
-/
/-! ## Layer I.1: Packed Field Writes, Storage Slot State & Execution Semantics -/
/-- A single sub-word packed bitfield write `(lens, val)` targeting a shared 256-bit slot. -/
structure PackedFieldWrite where
/-- Bitfield lens focusing on `[offset, offset + width)` within the 256-bit slot word. -/
lens : PackedWordLens
/-- Value written into the bitfield slice (automatically masked to `width` bits). -/
val : Nat
deriving DecidableEq, Repr, Inhabited
/-- Abstract EVM state focused on a target packed storage slot `slotWord`,
coupled with the free-memory pointer `fmp` (`0x40`) and the root of all other
storage slots `otherSlotsRoot` (`s' ≠ s`). -/
structure SlotStorageState where
/-- Current 256-bit word stored at the target packed storage slot `s`. -/
slotWord : Nat := 0
/-- Free-memory pointer at `memory[0x40]` (untouched by storage coalescing). -/
fmp : Nat := 128
/-- Commitment root of all storage slots other than `s` (frame-preserved). -/
otherSlotsRoot : Nat := 0
deriving DecidableEq, Repr, Inhabited
/-- Perform a single `SLOAD` on the target storage slot. -/
@[simp]
def sloadSlot (st : SlotStorageState) : Nat :=
st.slotWord
/-- Perform a single `SSTORE` updating the target storage slot to `newWord` while
preserving `fmp` and `otherSlotsRoot`. -/
@[simp]
def sstoreSlot (st : SlotStorageState) (newWord : Nat) : SlotStorageState :=
{ st with slotWord := newWord }
/-- Execute a single uncoalesced packed field write: `SLOAD` + `lens.set` + `SSTORE`. -/
@[simp]
def execSingleUncoalescedWrite (st : SlotStorageState) (wr : PackedFieldWrite) :
SlotStorageState :=
sstoreSlot st (wr.lens.set (sloadSlot st) wr.val)
/-- **Uncoalesced Execution (`execUncoalescedPackedWrites`)**:
Executes $N$ sub-word packed writes as $N$ separate `SLOAD` + `setBits` + `SSTORE`
transactions on the target slot. -/
def execUncoalescedPackedWrites (st : SlotStorageState) :
List PackedFieldWrite → SlotStorageState
| [] => st
| wr :: rest => execUncoalescedPackedWrites (execSingleUncoalescedWrite st wr) rest
/-- Compose a sequence of sub-word bitfield updates purely in a stack/Yul register word
without intermediate `SLOAD` or `SSTORE` operations. -/
def applyPackedWritesInRegister (word : Nat) : List PackedFieldWrite → Nat
| [] => word
| wr :: rest => applyPackedWritesInRegister (wr.lens.set word wr.val) rest
/-- **Coalesced Execution (`execCoalescedPackedWrites`)**:
Performs **1 `SLOAD`**, composes all $N$ bitfield masks in register via
`applyPackedWritesInRegister`, and commits the result with **1 `SSTORE`**. -/
def execCoalescedPackedWrites (st : SlotStorageState)
(writes : List PackedFieldWrite) : SlotStorageState :=
sstoreSlot st (applyPackedWritesInRegister (sloadSlot st) writes)
/-- **Theorem 1 (`execCoalescedPackedWrites_eq_uncoalesced`)**:
Coalescing any sequence of $N$ sub-word packed writes into a single `SLOAD` +
in-register bitwise composition + single `SSTORE` produces the exact same post-state
as $N$ uncoalesced `SLOAD`/`SSTORE` pairs. -/
@[simp]
theorem execCoalescedPackedWrites_eq_uncoalesced
(st : SlotStorageState) (writes : List PackedFieldWrite) :
execCoalescedPackedWrites st writes = execUncoalescedPackedWrites st writes := by
induction writes generalizing st with
| nil => rfl
| cons wr rest ih =>
unfold execUncoalescedPackedWrites execCoalescedPackedWrites applyPackedWritesInRegister
rw [← ih (execSingleUncoalescedWrite st wr)]
rfl
/-! ## Layer I.2: Pairwise Disjoint Lenses & Final Field Read Correctness -/
/-- Every write in `writes` focuses on a slice disjoint from `targetLens`. -/
def AllDisjointFrom (targetLens : PackedWordLens) (writes : List PackedFieldWrite) : Prop :=
∀ w ∈ writes, BitfieldSlice.Disjoint w.lens.slice targetLens.slice
/-- The bitfield lenses in `writes` are pairwise non-overlapping (`List.Pairwise`). -/
def PairwiseDisjointLenses (writes : List PackedFieldWrite) : Prop :=
writes.Pairwise (fun a b => BitfieldSlice.Disjoint a.lens.slice b.lens.slice)
/-- Executable boolean checker for `PairwiseDisjointLenses`. -/
def pairwiseDisjointLensesBool : List PackedFieldWrite → Bool
| [] => true
| w :: rest =>
rest.all (fun u => BitfieldSlice.disjointBool w.lens.slice u.lens.slice) &&
pairwiseDisjointLensesBool rest
/-- Soundness of the executable `pairwiseDisjointLensesBool` checker. -/
theorem pairwiseDisjointLenses_of_bool_eq_true
{writes : List PackedFieldWrite}
(h : pairwiseDisjointLensesBool writes = true) :
PairwiseDisjointLenses writes := by
induction writes with
| nil => exact List.Pairwise.nil
| cons w rest ih =>
simp only [pairwiseDisjointLensesBool, Bool.and_eq_true, List.all_eq_true,
BitfieldSlice.disjointBool_eq_true_iff] at h
exact List.Pairwise.cons h.1 (ih h.2)
/-- Applying in-register writes that are all disjoint from `targetLens` preserves
`targetLens.get word`. -/
theorem get_applyPackedWritesInRegister_of_allDisjoint
(targetLens : PackedWordLens) (word : Nat) (writes : List PackedFieldWrite)
(hdisj : AllDisjointFrom targetLens writes) :
targetLens.get (applyPackedWritesInRegister word writes) = targetLens.get word := by
induction writes generalizing word with
| nil => rfl
| cons wr rest ih =>
unfold applyPackedWritesInRegister
have hhead : BitfieldSlice.Disjoint wr.lens.slice targetLens.slice :=
hdisj wr List.mem_cons_self
have htail : AllDisjointFrom targetLens rest :=
fun u hu => hdisj u (List.mem_cons_of_mem wr hu)
rw [ih (wr.lens.set word wr.val) htail,
PackedWordLens.get_set_disjoint wr.lens targetLens hhead word wr.val]
/-- **Universal Disjoint Read-After-Coalesce Theorem
(`coalescedPackedWrites_mem_read_of_pairwiseDisjoint`)**:
Whenever `writes` has pairwise disjoint lenses (`PairwiseDisjointLenses writes`),
reading any field `wr ∈ writes` after the single coalesced `SSTORE` returns
`wr.val % 2 ^ wr.lens.slice.width`. -/
theorem coalescedPackedWrites_mem_read_of_pairwiseDisjoint
(st : SlotStorageState) (writes : List PackedFieldWrite) (wr : PackedFieldWrite)
(hpair : PairwiseDisjointLenses writes) (hmem : wr ∈ writes) :
wr.lens.get (execCoalescedPackedWrites st writes).slotWord =
wr.val % 2 ^ wr.lens.slice.width := by
induction writes generalizing st with
| nil => cases hmem
| cons hd tl ih =>
rw [PairwiseDisjointLenses, List.pairwise_cons] at hpair
rcases List.mem_cons.mp hmem with rfl | hmem_tl
· have hall : AllDisjointFrom wr.lens tl :=
fun u hu => (hpair.1 u hu).symm
unfold execCoalescedPackedWrites applyPackedWritesInRegister
simp only [sstoreSlot, sloadSlot]
rw [get_applyPackedWritesInRegister_of_allDisjoint wr.lens _ tl hall,
PackedWordLens.get_set_same]
· exact ih (execSingleUncoalescedWrite st hd) hpair.2 hmem_tl
/-! ## Layer I.3: Canonical Uniswap v3/v4 `Slot0` Layout & 4-Field Coalescing -/
/-- Uniswap v3/v4 `Slot0.sqrtPriceX96` lens: bits `[0, 160)` (`uint160`). -/
def slot0SqrtPriceX96Lens : PackedWordLens :=
⟨{ offset := 0, width := 160 }⟩
/-- Uniswap v3/v4 `Slot0.tick` lens: bits `[160, 184)` (`int24` two's-complement word). -/
def slot0TickLens : PackedWordLens :=
⟨{ offset := 160, width := 24 }⟩
/-- Uniswap v3/v4 `Slot0.protocolFee` lens: bits `[184, 208)` (`uint24`). -/
def slot0ProtocolFeeLens : PackedWordLens :=
⟨{ offset := 184, width := 24 }⟩
/-- Uniswap v3/v4 `Slot0.lpFee` lens: bits `[208, 232)` (`uint24`). -/
def slot0LpFeeLens : PackedWordLens :=
⟨{ offset := 208, width := 24 }⟩
/-- Construct the 4-field packed write sequence updating Uniswap v3/v4 `Slot0`
(`sqrtPriceX96`, `tick`, `protocolFee`, `lpFee`) on the shared storage slot `0`. -/
def mkSlot0PackedWrites (sqrtPriceX96 tick protocolFee lpFee : Nat) :
List PackedFieldWrite :=
[ { lens := slot0SqrtPriceX96Lens, val := sqrtPriceX96 }
, { lens := slot0TickLens, val := tick }
, { lens := slot0ProtocolFeeLens, val := protocolFee }
, { lens := slot0LpFeeLens, val := lpFee } ]
/-- All four `Slot0` bitfield lenses are pairwise disjoint for any field values. -/
theorem slot0_pairwiseDisjointLenses (sqrtPriceX96 tick protocolFee lpFee : Nat) :
PairwiseDisjointLenses (mkSlot0PackedWrites sqrtPriceX96 tick protocolFee lpFee) :=
pairwiseDisjointLenses_of_bool_eq_true rfl
/-- **Theorem 2 (`coalescedSlot0_final_read_each_field`)**:
After executing the coalesced single-`SLOAD`/single-`SSTORE` update of `Slot0`
(or any 4 pairwise-disjoint `Slot0` writes), reading each of the four sub-word
fields returns its exact truncated written value `vᵢ % 2 ^ widthᵢ`. -/
theorem coalescedSlot0_final_read_each_field
(st : SlotStorageState) (sqrtPriceX96 tick protocolFee lpFee : Nat) :
let writes := mkSlot0PackedWrites sqrtPriceX96 tick protocolFee lpFee
let finalWord := (execCoalescedPackedWrites st writes).slotWord
PairwiseDisjointLenses writes ∧
slot0SqrtPriceX96Lens.get finalWord = sqrtPriceX96 % 2 ^ 160 ∧
slot0TickLens.get finalWord = tick % 2 ^ 24 ∧
slot0ProtocolFeeLens.get finalWord = protocolFee % 2 ^ 24 ∧
slot0LpFeeLens.get finalWord = lpFee % 2 ^ 24 := by
intro writes finalWord
have hpair := slot0_pairwiseDisjointLenses sqrtPriceX96 tick protocolFee lpFee
refine ⟨hpair, ?_, ?_, ?_, ?_⟩
· exact coalescedPackedWrites_mem_read_of_pairwiseDisjoint st writes
⟨slot0SqrtPriceX96Lens, sqrtPriceX96⟩ hpair (by simp [writes, mkSlot0PackedWrites])
· exact coalescedPackedWrites_mem_read_of_pairwiseDisjoint st writes
⟨slot0TickLens, tick⟩ hpair (by simp [writes, mkSlot0PackedWrites])
· exact coalescedPackedWrites_mem_read_of_pairwiseDisjoint st writes
⟨slot0ProtocolFeeLens, protocolFee⟩ hpair (by simp [writes, mkSlot0PackedWrites])
· exact coalescedPackedWrites_mem_read_of_pairwiseDisjoint st writes
⟨slot0LpFeeLens, lpFee⟩ hpair (by simp [writes, mkSlot0PackedWrites])
/-! ## Layer I.4: `VerifiedCompilerShim` Instance & Warm `SLOAD`/`SSTORE` Gas Savings -/
/-- Frame invariant for packed-slot coalescing: preserves `fmp` (`0x40`) and all
other storage slots `otherSlotsRoot`. -/
def slotCoalescingFrame (st post : SlotStorageState) : Prop :=
post.fmp = st.fmp ∧ post.otherSlotsRoot = st.otherSlotsRoot
/-- Universal frame soundness for `execCoalescedPackedWrites`. -/
theorem execCoalescedPackedWrites_frame_sound
(writes : List PackedFieldWrite) (st : SlotStorageState) :
slotCoalescingFrame st (execCoalescedPackedWrites st writes) :=
⟨rfl, rfl⟩
/-- **Theorem 3 (`slotCoalescingVerifiedShim`)**:
`VerifiedCompilerShim` instance certifying that the single-`SLOAD`/single-`SSTORE`
packed-slot coalescing pass refines uncoalesced sequential `SLOAD`/`SSTORE` writes
and preserves the memory and storage frame. -/
def slotCoalescingVerifiedShim :
VerifiedCompilerShim (List PackedFieldWrite) SlotStorageState SlotStorageState where
name := "slotCoalescing"
denoteSpec := fun writes st => execUncoalescedPackedWrites st writes
shimImpl := fun writes st => execCoalescedPackedWrites st writes
effects := { readsStorage := true, writesStorage := true }
freeMemoryFrame := slotCoalescingFrame
refines_denote := fun writes st => execCoalescedPackedWrites_eq_uncoalesced st writes
frame_sound := execCoalescedPackedWrites_frame_sound
non_vacuous := ⟨mkSlot0PackedWrites 1000 20 3 30, trivial⟩
/-- EIP-2929 warm `SLOAD` gas cost (`100` gas). -/
def warmSloadGas : Nat := 100
/-- EIP-2929 warm dirty `SSTORE` gas cost (`100` gas). -/
def warmSstoreGas : Nat := 100
/-- Combined gas cost of one warm `SLOAD` + `SSTORE` read-modify-write pair (`200` gas). -/
def warmSlotAccessPairGas : Nat := warmSloadGas + warmSstoreGas
/-- Total `SLOAD` + `SSTORE` gas consumed by $N$ uncoalesced packed writes ($N \times 200$). -/
def uncoalescedPackedWritesGas (numWrites : Nat) : Nat :=
numWrites * warmSlotAccessPairGas
/-- Total `SLOAD` + `SSTORE` gas consumed by coalesced packed writes ($0$ when $N = 0$,
$200$ when $N \ge 1$). -/
def coalescedPackedWritesGas (numWrites : Nat) : Nat :=
if numWrites == 0 then 0 else warmSlotAccessPairGas
/-- Gas saved by coalescing $N$ sub-word writes on the same storage slot. -/
def slotCoalescingGasSaved (numWrites : Nat) : Nat :=
uncoalescedPackedWritesGas numWrites - coalescedPackedWritesGas numWrites
/-- **Theorem 4 (`slotCoalescing_gas_saved`)**:
For every sequence of $N \ge 2$ packed writes to the same slot, slot coalescing
strictly saves $(N - 1) \times 200$ gas (eliminating $N - 1$ warm `SLOAD` + `SSTORE`
pairs). -/
theorem slotCoalescing_gas_saved (numWrites : Nat) (hge : 2 ≤ numWrites) :
slotCoalescingGasSaved numWrites = (numWrites - 1) * 200 ∧
0 < slotCoalescingGasSaved numWrites := by
have hne : (numWrites == 0) = false := beq_false_of_ne (by omega)
simp only [slotCoalescingGasSaved, uncoalescedPackedWritesGas,
coalescedPackedWritesGas, warmSlotAccessPairGas, warmSloadGas, warmSstoreGas,
hne, Bool.false_eq_true, ↓reduceIte]
omega
/-! ## Layer II: 1-3 Line Projection & Fusion Corollaries -/
/-- Layer II observational refinement corollary for `slotCoalescingVerifiedShim`. -/
theorem slotCoalescing_obs_eq
(writes : List PackedFieldWrite) (st : SlotStorageState) :
slotCoalescingVerifiedShim.shimImpl writes st =
slotCoalescingVerifiedShim.denoteSpec writes st :=
slotCoalescingVerifiedShim.obs_eq writes st
/-- Layer II frame corollary for `slotCoalescingVerifiedShim`. -/
theorem slotCoalescing_denote_frame_sound
(writes : List PackedFieldWrite) (st : SlotStorageState) :
slotCoalescingFrame st (slotCoalescingVerifiedShim.denoteSpec writes st) :=
slotCoalescingVerifiedShim.denote_frame_sound writes st
/-- Two consecutive writes to the same packed lens `lens` coalesce into the single
final write `(lens, v₂)` (`PackedWordLens.set_set_fuse`). -/
@[simp]
theorem execCoalescedPackedWrites_same_lens_fuse
(st : SlotStorageState) (lens : PackedWordLens) (v₁ v₂ : Nat)
(rest : List PackedFieldWrite) :
execCoalescedPackedWrites st (⟨lens, v₁⟩ :: ⟨lens, v₂⟩ :: rest) =
execCoalescedPackedWrites st (⟨lens, v₂⟩ :: rest) := by
simp [execCoalescedPackedWrites, applyPackedWritesInRegister]
/-- Concrete gas-saving corollary for Uniswap v3/v4 `Slot0` ($N = 4$ fields):
coalescing saves $3 \times 200 = 600$ gas per `Slot0` update. -/
theorem slot0_coalescing_saves_600_gas :
slotCoalescingGasSaved 4 = 600 ∧
uncoalescedPackedWritesGas 4 = 800 ∧
coalescedPackedWritesGas 4 = 200 := by
decide
/-! ## Layer III: Kernel-Checked (`by decide`, `0 native_decide`) Executable Witness Suite -/
/-- Executable witness verifying `Slot0` 4-field coalescing equivalence, pairwise
disjointness, exact field readback, overwrite fusion, frame preservation, and
$600$-gas savings. -/
def checkSlotCoalescingWitnessSuite : Bool :=
let st₀ : SlotStorageState :=
{ slotWord := 0xdeadbeef, fmp := 128, otherSlotsRoot := 777 }
let writes := mkSlot0PackedWrites 0x123456789abcdef 0x000abc 0x000015 0x000bb8
let coalesced := slotCoalescingVerifiedShim.shimImpl writes st₀
let uncoalesced := slotCoalescingVerifiedShim.denoteSpec writes st₀
let overwriteWrites : List PackedFieldWrite :=
[ ⟨slot0TickLens, 111⟩, ⟨slot0TickLens, 222⟩, ⟨slot0LpFeeLens, 500⟩ ]
let fusedWrites : List PackedFieldWrite :=
[ ⟨slot0TickLens, 222⟩, ⟨slot0LpFeeLens, 500⟩ ]
(coalesced == uncoalesced) &&
pairwiseDisjointLensesBool writes &&
(slot0SqrtPriceX96Lens.get coalesced.slotWord == 0x123456789abcdef) &&
(slot0TickLens.get coalesced.slotWord == 0x000abc) &&
(slot0ProtocolFeeLens.get coalesced.slotWord == 0x000015) &&
(slot0LpFeeLens.get coalesced.slotWord == 0x000bb8) &&
(coalesced.fmp == 128) &&
(coalesced.otherSlotsRoot == 777) &&
(execCoalescedPackedWrites st₀ overwriteWrites ==
execCoalescedPackedWrites st₀ fusedWrites) &&
(slotCoalescingGasSaved 4 == 600) &&
(slotCoalescingGasSaved 2 == 200)
/-- Kernel-checked (`by decide`, `0 native_decide`) proof of `checkSlotCoalescingWitnessSuite`. -/
theorem checkSlotCoalescingWitnessSuite_eq_true :
checkSlotCoalescingWitnessSuite = true := by
decide
/-! ## Layer IV: Redundant SLOAD Elimination (Intra-Block SLOAD CSE) -/
/-- Intra-block single-slot operation for redundant `SLOAD` common subexpression
elimination (CSE) across a shared storage slot. -/
inductive SingleSlotOp where
| sload
| sstore (val : Nat)
| pureOp (delta : Nat)
| externalCallBarrier
deriving DecidableEq, Repr, Inhabited
/-- Unoptimized single-step execution on `(slotWord, traceReads)`:
- `.sload` reads `st.1` from storage (`100` warm gas) and appends `st.1` to `st.2`
- `.sstore v` updates `st.1 := v`
- `.pureOp _` leaves storage and read trace unchanged
- `.externalCallBarrier` leaves storage and read trace unchanged. -/
@[simp]
def execUncachedOp (op : SingleSlotOp) (st : Nat × List Nat) : Nat × List Nat :=
match op with
| .sload => (st.1, st.2 ++ [st.1])
| .sstore v => (v, st.2)
| .pureOp _ => st
| .externalCallBarrier => st
/-- Unoptimized multi-step execution over a list of `SingleSlotOp` operations. -/
def execUncachedOps : List SingleSlotOp → (Nat × List Nat) → (Nat × List Nat)
| [], st => st
| op :: rest, st => execUncachedOps rest (execUncachedOp op st)
/-- Cached single-step execution on `(cache : Option Nat)` and `(slotWord, traceReads)`:
- `.sload`: if `cache = some v`, serves `v` from the Yul local variable (`0` `SLOAD` gas)
and keeps `cache = some v`; if `cache = none`, reads `st.1` from storage (`100` gas)
and populates `cache = some st.1`
- `.sstore v`: updates `st.1 := v` and writes through to `cache := some v`
- `.pureOp _`: preserves both `cache` and `st`
- `.externalCallBarrier`: flushes `cache := none` while preserving `st`. -/
@[simp]
def execCachedOp (op : SingleSlotOp) (cache : Option Nat) (st : Nat × List Nat) :
Option Nat × (Nat × List Nat) :=
match op with
| .sload =>
match cache with
| some v => (some v, (st.1, st.2 ++ [v]))
| none => (some st.1, (st.1, st.2 ++ [st.1]))
| .sstore v => (some v, (v, st.2))
| .pureOp _ => (cache, st)
| .externalCallBarrier => (none, st)
/-- Cached multi-step execution threading the local Yul slot cache across `ops`. -/
def execCachedOps :
List SingleSlotOp → Option Nat → (Nat × List Nat) → Option Nat × (Nat × List Nat)
| [], cache, st => (cache, st)
| op :: rest, cache, st =>
let step := execCachedOp op cache st
execCachedOps rest step.1 step.2
/-- Execute intra-block `SLOAD` CSE starting from an initially empty local cache (`none`). -/
@[simp]
def runSloadCSE (ops : List SingleSlotOp) (st : Nat × List Nat) : Nat × List Nat :=
(execCachedOps ops none st).2
/-- Coherence invariant linking the local Yul register cache `cache` to the
current storage word `slotWord`. -/
def CacheCoherent (cache : Option Nat) (slotWord : Nat) : Prop :=
∀ v, cache = some v → v = slotWord
/-- An empty local cache (`none`) is vacuously coherent with any storage word `slotWord`. -/
theorem CacheCoherent_none (slotWord : Nat) :
CacheCoherent none slotWord := by
intro v hv
cases hv
/-- Caching the current storage word `some slotWord` is coherent with `slotWord`. -/
theorem CacheCoherent_some_self (slotWord : Nat) :
CacheCoherent (some slotWord) slotWord := by
intro v hv
injection hv with hv'
exact hv'.symm
/-- Exact characterization of coherence for a populated cache `some v`. -/
theorem CacheCoherent_some_iff (v slotWord : Nat) :
CacheCoherent (some v) slotWord ↔ v = slotWord := by
constructor
· intro h
exact h v rfl
· intro h u hu
injection hu with hu'
omega
/-- Every `SingleSlotOp` preserves `CacheCoherent` across `execCachedOp`. -/
theorem execCachedOp_preserves_coherent
(op : SingleSlotOp) (cache : Option Nat) (st : Nat × List Nat)
(hcoh : CacheCoherent cache st.1) :
CacheCoherent (execCachedOp op cache st).1 (execCachedOp op cache st).2.1 := by
cases op with
| sload =>
cases cache with
| none =>
dsimp only [execCachedOp]
exact CacheCoherent_some_self st.1
| some v =>
dsimp only [execCachedOp]
have hv : v = st.1 := hcoh v rfl
rw [hv]
exact CacheCoherent_some_self st.1
| sstore val =>
dsimp only [execCachedOp]
exact CacheCoherent_some_self val
| pureOp delta =>
dsimp only [execCachedOp]
exact hcoh
| externalCallBarrier =>
dsimp only [execCachedOp]
exact CacheCoherent_none st.1
/-- Whenever `CacheCoherent cache st.1` holds, a single cached operation produces the
exact same `(slotWord, traceReads)` state as `execUncachedOp`. -/
theorem execCachedOp_snd_eq_unoptimized
(op : SingleSlotOp) (cache : Option Nat) (st : Nat × List Nat)
(hcoh : CacheCoherent cache st.1) :
(execCachedOp op cache st).2 = execUncachedOp op st := by
cases op with
| sload =>
cases cache with
| none => rfl
| some v =>
dsimp only [execCachedOp, execUncachedOp]
have hv : v = st.1 := hcoh v rfl
rw [hv]
| sstore val => rfl
| pureOp delta => rfl
| externalCallBarrier => rfl
/-- Multi-step `execCachedOps` preserves `CacheCoherent` across any operation sequence `ops`. -/
theorem execCachedOps_preserves_coherent
(ops : List SingleSlotOp) (cache : Option Nat) (st : Nat × List Nat)
(hcoh : CacheCoherent cache st.1) :
CacheCoherent (execCachedOps ops cache st).1 (execCachedOps ops cache st).2.1 := by
induction ops generalizing cache st with
| nil => exact hcoh
| cons op rest ih =>
dsimp only [execCachedOps]
exact ih (execCachedOp op cache st).1 (execCachedOp op cache st).2
(execCachedOp_preserves_coherent op cache st hcoh)
/-- By induction on `ops`, running `execCachedOps` from any coherent cache produces
the exact same `(slotWord, traceReads)` result as `execUncachedOps`. -/
theorem execCachedOps_snd_eq_unoptimized
(ops : List SingleSlotOp) (cache : Option Nat) (st : Nat × List Nat)
(hcoh : CacheCoherent cache st.1) :
(execCachedOps ops cache st).2 = execUncachedOps ops st := by
induction ops generalizing cache st with
| nil => rfl
| cons op rest ih =>
dsimp only [execCachedOps, execUncachedOps]
have hstep := execCachedOp_snd_eq_unoptimized op cache st hcoh
have hcoh' := execCachedOp_preserves_coherent op cache st hcoh
rw [← hstep]
exact ih (execCachedOp op cache st).1 (execCachedOp op cache st).2 hcoh'
/-- Starting from `cache = none`, intra-block `SLOAD` CSE (`runSloadCSE`) is
observationally identical to unoptimized execution (`execUncachedOps`). -/
@[simp]
theorem runSloadCSE_sound
(ops : List SingleSlotOp) (st : Nat × List Nat) :
runSloadCSE ops st = execUncachedOps ops st :=
execCachedOps_snd_eq_unoptimized ops none st (CacheCoherent_none st.1)
/-- Master soundness theorem for intra-block redundant `SLOAD` elimination (`SLOAD` CSE):
starting from `cache = none`, cached execution matches unoptimized execution on both
final storage word and read trace while maintaining cache coherence. -/
theorem redundant_sload_elimination_sound
(ops : List SingleSlotOp) (st : Nat × List Nat) :
runSloadCSE ops st = execUncachedOps ops st ∧
CacheCoherent (execCachedOps ops none st).1 (execCachedOps ops none st).2.1 :=
⟨runSloadCSE_sound ops st,
execCachedOps_preserves_coherent ops none st (CacheCoherent_none st.1)⟩
/-- Warm gas saved by eliminating `redundantLoads` redundant `SLOAD` instructions
(`100` gas per eliminated warm `SLOAD`). -/
def sloadCSEGasSaved (redundantLoads : Nat) : Nat :=
100 * redundantLoads
/-- Eliminating one or more redundant `SLOAD` instructions strictly saves `100 * redundantLoads`
warm gas (`> 0`). -/
theorem sloadCSEGasSaved_pos (redundantLoads : Nat) (hpos : 0 < redundantLoads) :
sloadCSEGasSaved redundantLoads = 100 * redundantLoads ∧
0 < sloadCSEGasSaved redundantLoads := by
refine ⟨rfl, ?_⟩
dsimp only [sloadCSEGasSaved]
omega
/-- Executable witness suite for Layer IV intra-block `SLOAD` CSE across read hits,
write-through `SSTORE` forwarding, pure ops, and `externalCallBarrier` cache flushes. -/
def checkSloadCSEWitnessSuite : Bool :=
let ops : List SingleSlotOp :=
[ .sload
, .sload
, .pureOp 10
, .sstore 99
, .sload
, .externalCallBarrier
, .sload ]
let st₀ : Nat × List Nat := (42, [])
let cseOut := runSloadCSE ops st₀
let unoptOut := execUncachedOps ops st₀
(cseOut == unoptOut) &&
(cseOut == (99, [42, 42, 99, 99])) &&
(sloadCSEGasSaved 2 == 200) &&
(sloadCSEGasSaved 3 == 300)
/-- Kernel-checked (`by decide`, `0 native_decide`) witness theorem for Layer IV `SLOAD` CSE. -/
theorem checkSloadCSEWitnessSuite_eq_true :
checkSloadCSEWitnessSuite = true := by
decide
/-! ## Layer V: Compositional Packed-Write Algebra & Frame Preservation -/
/-- Alias for `updateBits`: clears `[offset, offset + width)` in `word` and inserts
`val % 2 ^ width` at bit `offset`. -/
@[simp]
abbrev clearInsertBits (word offset width val : Nat) : Nat :=
updateBits word offset width val
/-- Bit offset projection on `PackedWordLens`. -/
@[simp]
abbrev _root_.Compiler.Proofs.PackedBitfieldMetaSpec.PackedWordLens.offset
(lens : PackedWordLens) : Nat :=
lens.slice.offset
/-- Bit width projection on `PackedWordLens`. -/
@[simp]
abbrev _root_.Compiler.Proofs.PackedBitfieldMetaSpec.PackedWordLens.width
(lens : PackedWordLens) : Nat :=
lens.slice.width
/-- Applying an empty sequence of packed field writes in register is the identity on `word`. -/
@[simp]
theorem applyPackedWritesInRegister_nil (word : Nat) :
applyPackedWritesInRegister word [] = word :=
rfl
/-- Applying a cons list `w :: ws` of packed field writes in register updates `word`
via `clearInsertBits word w.lens.offset w.lens.width w.val` and continues with `ws`. -/
@[simp]
theorem applyPackedWritesInRegister_cons
(word : Nat) (w : PackedFieldWrite) (ws : List PackedFieldWrite) :
applyPackedWritesInRegister word (w :: ws) =
applyPackedWritesInRegister (clearInsertBits word w.lens.offset w.lens.width w.val) ws :=
rfl
/-- In-register packed write composition distributes over list append (`w₁ ++ w₂`). -/
@[simp]
theorem applyPackedWritesInRegister_append
(word : Nat) (w₁ w₂ : List PackedFieldWrite) :
applyPackedWritesInRegister word (w₁ ++ w₂) =
applyPackedWritesInRegister (applyPackedWritesInRegister word w₁) w₂ := by
induction w₁ generalizing word with
| nil => rfl
| cons wr rest ih => exact ih (wr.lens.set word wr.val)
/-- Uncoalesced sequential packed writes distribute over list append (`w₁ ++ w₂`). -/
@[simp]
theorem execUncoalescedPackedWrites_append
(st : SlotStorageState) (w₁ w₂ : List PackedFieldWrite) :
execUncoalescedPackedWrites st (w₁ ++ w₂) =
execUncoalescedPackedWrites (execUncoalescedPackedWrites st w₁) w₂ := by
induction w₁ generalizing st with
| nil => rfl
| cons wr rest ih => exact ih (execSingleUncoalescedWrite st wr)
/-- Coalesced single-`SLOAD`/single-`SSTORE` packed writes distribute over list append (`w₁ ++ w₂`). -/
@[simp]
theorem execCoalescedPackedWrites_append
(st : SlotStorageState) (w₁ w₂ : List PackedFieldWrite) :
execCoalescedPackedWrites st (w₁ ++ w₂) =
execCoalescedPackedWrites (execCoalescedPackedWrites st w₁) w₂ := by
simp only [execCoalescedPackedWrites, sstoreSlot, sloadSlot,
applyPackedWritesInRegister_append]
/-- Coalesced packed writes preserve the free-memory pointer `fmp` (`0x40`). -/
@[simp]
theorem execCoalescedPackedWrites_fmp_preserved
(st : SlotStorageState) (writes : List PackedFieldWrite) :
(execCoalescedPackedWrites st writes).fmp = st.fmp :=
rfl
/-- Coalesced packed writes preserve the commitment root of all other storage slots (`otherSlotsRoot`). -/
@[simp]
theorem execCoalescedPackedWrites_otherSlotsRoot_preserved
(st : SlotStorageState) (writes : List PackedFieldWrite) :
(execCoalescedPackedWrites st writes).otherSlotsRoot = st.otherSlotsRoot :=
rfl
/-- Uncoalesced packed writes preserve the free-memory pointer `fmp` (`0x40`). -/
@[simp]
theorem execUncoalescedPackedWrites_fmp_preserved
(st : SlotStorageState) (writes : List PackedFieldWrite) :
(execUncoalescedPackedWrites st writes).fmp = st.fmp := by
rw [← execCoalescedPackedWrites_eq_uncoalesced]
rfl
/-- Uncoalesced packed writes preserve the commitment root of all other storage slots (`otherSlotsRoot`). -/
@[simp]
theorem execUncoalescedPackedWrites_otherSlotsRoot_preserved
(st : SlotStorageState) (writes : List PackedFieldWrite) :
(execUncoalescedPackedWrites st writes).otherSlotsRoot = st.otherSlotsRoot := by
rw [← execCoalescedPackedWrites_eq_uncoalesced]
rfl
/-- For any batch of `n ≥ 2` packed writes, coalesced execution consumes strictly less
warm `SLOAD`/`SSTORE` gas than uncoalesced execution. -/
theorem coalescedPackedWritesGas_lt_uncoalesced (n : Nat) (hn : n ≥ 2) :
coalescedPackedWritesGas n < uncoalescedPackedWritesGas n := by
have hne : (n == 0) = false := beq_false_of_ne (by omega)
simp only [coalescedPackedWritesGas, uncoalescedPackedWritesGas,
warmSlotAccessPairGas, warmSloadGas, warmSstoreGas,
hne, Bool.false_eq_true, ↓reduceIte]
omega
/-- Warm `SLOAD`/`SSTORE` gas saved by packed-slot coalescing is monotone in the number of writes. -/
theorem slotCoalescingGasSaved_monotone (m n : Nat) (hmn : m ≤ n) :
slotCoalescingGasSaved m ≤ slotCoalescingGasSaved n := by
rcases Nat.eq_zero_or_pos m with rfl | hm
· simp only [slotCoalescingGasSaved, uncoalescedPackedWritesGas,
coalescedPackedWritesGas]
omega
· have hne_m : (m == 0) = false := beq_false_of_ne (by omega)
have hne_n : (n == 0) = false := beq_false_of_ne (by omega)
simp only [slotCoalescingGasSaved, uncoalescedPackedWritesGas,
coalescedPackedWritesGas, warmSlotAccessPairGas, warmSloadGas, warmSstoreGas,
hne_m, hne_n, Bool.false_eq_true, ↓reduceIte]
omega
end Compiler.Proofs.SlotCoalescingShim