Repository navigation
Expand file tree
/
Copy pathInvariant.lean
More file actions
2825 lines (2571 loc) · 135 KB
/
Copy pathInvariant.lean
File metadata and controls
2825 lines (2571 loc) · 135 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
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Ethereum.Theory.StaticStorage
import Fe.EVM.FrameCalls
import Ethereum.Theory.ReturnDataBound
/-!
# A contract invariant through reentrant message calls
Over EVMLean alone (no `Fe` module): a contract at address `a` keeps an invariant on its account
through every message call and creation, at every depth, if each frame that runs its code keeps
the invariant whenever the calls and creations below that frame do. This is the theorem the
standard method rests on: assume the invariant on entry to every public function, re-establish it
at every normal return and before every external call, since the callee may call back in. The
theorem is relative to an admission condition on the frames at `a`, for invariants whose
per-frame proof needs something of the call (a calldata bound, keys that do not collide).
## The statement
`Holds a P σ`: `a`'s account exists in `σ` and satisfies `P : Account → Prop`. The invariant sees
`a`'s account only.
`admits : AccountMap → ExecutionEnv → Prop` is the admission condition, on the account map a frame
at `a` starts from and its environment.
`callsAt : CallsAt` describes the calls and creations a frame at `a` makes: `callsAt Q σ σ₀ g A I`
says that they satisfy `Q`, for the frame's account map, original account map, gas, substate and
environment. `XiOk` is the description by the bytecode's steps; a model may give its own, such as
the calls it records under every feed, and a frame at `a` that makes no call may take `True`.
`Admitted a admits callsAt T`, for the inputs `T` of a message call: in the execution of `T`,
every successful frame at `a` is admitted. It is defined by recursion on the depth left below the
call (`Adm`): if `T` runs code and its frame succeeds, then, when it runs at `a`, the frame is
admitted and the calls and creations `callsAt` describes are admitted in turn, at the next depth;
elsewhere, every message call and creation the frame makes is, followed step by step (`XiOk`,
`XOk`, `XstepOk`, `stepOk`, defined in `Fe/EVM/FrameCalls.lean`). So it covers the frames at `a`
reached through any number of other contracts, and the frames below a frame at `a`, re-entry
included, as far as `callsAt` describes the calls a frame at `a` makes: with `callsAt := XiOk`,
all of them; with `callsAt := fun _ _ _ _ _ _ => True`, none, and the frames below a frame at `a`
need not be admitted. `AdmittedL` is the same for a creation, whose frame never runs at `a` with
effect: a creation that lands on `a`, which has code, leaves the account map as it was whatever its
frame does, so its frame is not asked to be admitted.
What it does not constrain:
- A frame that fails. Its changes are undone, so neither it nor the frames below it need be
admitted. A successful frame's nested call that fails is such a frame.
- A call that is not made (without the funds, at depth 1024) or a creation that is not made
(also with the creator's nonce at its limit): there is no frame.
- A precompile: it runs no frame.
`total σ`: the sum of all balances, as a natural number, over the account map's list of entries
(`toList`). Writing one account changes it by the difference of the balances (`total_insert`,
`total_of_some`, by a permutation of the entry lists).
`Enters : AccountMap → ExecutionEnv → UInt256 → Prop` is the entry condition, on how a frame at
`a` is entered: the account map before the value moves, the frame's environment, and the value
moved. `Enters σ I v := v = I.weiValue` says the call moves the value it reports; WETH9 adds
`I.source ≠ a`, since a frame entered from `a` itself with value is credited ether that did not
move. It is not hardcoded, as a contract may call itself. `FromOthers a Enters`: every entry
from another account by a call that moves the value it reports satisfies `Enters`. That is what
the transaction's outermost call and the frames elsewhere give (below).
`ThetaGood a P Trusted Enters admits callsAt e`: every admitted message call at depth `e` ends
where `Holds` holds, if it starts where `Holds` holds both before and after its value moves
(`sendEth`, as `Θ` moves it), its calldata size fits a word, it runs code `Trusted` admits (or a
precompile) when its recipient is `a`, the payer has the value, the balances add up to less than
`2 ^ 256`, and, when its recipient is `a`, its entry satisfies `Enters` or `P` sees only the code
(`GoodTheta`). It ends with no more ether in total than it started with. It
also keeps `a` out of the created accounts and the self-destruct set of the substate (`SubOk`), if
the substate it starts with does. `LambdaGood a P admits callsAt e` is the same for `Lambda`, with
the creator's payment (`debit`, `GoodLambda`), when the creator has the endowment and a nonce.
`Deeper` is both, at every depth below a given one. The substate part does not depend on `P`: a
model that makes calls under a feed of arbitrary substates uses only the account part.
`FrameHyp a P Trusted Enters admits callsAt`, the per-frame hypothesis: every successful `Ξ` with
code owner `a`, running code `Trusted` admits, with calldata that fits a word, admitted, ends with
`a`'s account satisfying `P`, if its code is still what it was. The frame knows how it was
entered: from an account map `σpre` where `Holds` holds and the balances add up to less than
`2 ^ 256`, by moving `v`, which the source has, from the source to `a` (`σ = sendEth a source v
true σpre`), with `Enters σpre I v`, and `Holds` holds after the move too. The frame may assume
`Deeper` (the admitted calls and creations below it are good) and that the calls and creations
`callsAt` describes are admitted; it must show `Holds` before each call it makes, with any value
already taken from `a`, and, for a call to `a`, `Enters` of that call. That the code is kept, and
the substate part, need not be shown: `Xi_code` proves them of every frame, whatever it runs, and
also that it adds no ether.
Every frame at `a` is entered so, given `FromOthers a Enters`. `Θ` moves the value it is given
and reports `v'`. The transaction's call comes from the sender, which is not `a` (EIP-3607), and
moves the value it reports. A frame elsewhere, at `b`, makes only `CALL` and `CALLCODE` (source
`b`, the value moved and reported), `STATICCALL` (source `b`, zero and zero) and `DELEGATECALL`
(recipient `b`, not `a`), which the walk checks (`call_holds`). The calls a frame at `a` makes
are its own proof's to state, so `Deeper` asks `Enters` of them. When `P` sees only the code, as
for `code_good`, the entry plays no part. No creation runs at `a` with effect. The walk could
also show, of an entry from elsewhere, that its depth is one more than the caller's, that its
write permission is the caller's (or none, for `STATICCALL`) and that its sender is the
transaction's; `FromOthers` does not ask for these.
A frame at `a` that executes `SELFDESTRUCT` moves `a`'s balance out. That is not a balance
increase, so it is the frame's own effect, which `FrameHyp` speaks about: the frame's result must
satisfy `P`. It does not remove `a`: EVMLean adds the running account to the self-destruct set
only when the substate lists it among the accounts this transaction created, and `a` is never
listed (`SubOk`).
`good`: from `Admissible P Trusted`, `FromOthers a Enters` and `FrameHyp a P Trusted Enters
admits callsAt`, `ThetaGood` and `LambdaGood` hold at every depth. With `admits := fun _ _ => True`
and a `callsAt` that holds of every call when `Q` does (`XiOk`, or `True`), every execution is
admitted (`admitted_of_all`), and
the theorem is about every message call and creation.
`Fe.EVM.RefineInvariant` derives `FrameHyp` from a certificate of the bytecode.
`tx_holds`, the transaction: `Υ` keeps `Holds`, and adds no ether, if it starts where the
balances add up to less than `2 ^ 256`, the outermost call or creation, as `Υ` makes it (`txCall`),
is admitted (`TxAdmitted`), and these conditions hold:
- The sender has no code. `Υ` does not check this; EIP-3607 makes such a transaction invalid,
and EVMLean's conformance runner rejects it (`SENDER_NOT_EOA`) before calling `Υ`. Since `a`
has code, the sender is not `a`, so the upfront payment and the gas refund do not touch `a`.
- The transaction's data size fits a word, as a frame's calldata must.
- The transaction is valid as EVMLean's conformance runner checks (`validateTransaction`): the
sender can pay the gas limit at the price `Υ` charges, the blob fee and the value; the priority
fee is at most the price (the price covers the base fee); the sender's nonce is below
`2 ^ 64 - 1` (EIP-2681), so the increment does not wrap and the creator of a creation has a
nonce. These are stated in `Υ`'s own terms (`txPrice`, `txFee`, `calcBlobFee`).
`Υ`'s accounting: the sender pays `gasLimit * price + blobFee` upfront (`total_txState`); the call
adds no ether; the refund and the priority fee are at most the upfront gas payment, because the
call returns no more gas than it was given (`Theta_gas_le`, `lambda_gas_le`) (`Holds.fees`); the
erasures remove ether and clearing transient storage keeps it (`total_txTail`). The blob fee is
burnt.
`Υ` erases the accounts in the self-destruct set its message call or creation returns; `a` is not
among them. The transaction's call starts with no created accounts and an empty self-destruct set,
and every call and creation keeps `SubOk`: a creation lists only an address without code, which
`a` is not, and `SELFDESTRUCT` adds the running account only when it is listed. A call or creation
that fails returns the substate it was given (a creation with its created accounts restored), and a
precompile returns it unchanged (`precompiled_Theta_substate`).
`P` must also tolerate clearing the transient storage, which `Υ` does at the end; this is a
hypothesis of `tx_holds` only, since nothing inside a transaction clears it. `a`, having code,
is never a dead account.
`deploy_holds`, the base case: a creation that succeeds ends with `Holds` at the address it
created, if the account its init code leaves there, with the code the init code returns, satisfies
`P`. `lambda_success` says what a successful creation did: the target had no nonce, code or
storage (EIP-7610; otherwise the init code is `INVALID` and fails), so the init code ran from an
account with empty storage, and `Lambda` installed the returned code over the account the init
code left. During the creation `a` has no code yet, so the theorems above apply only from then
on.
## The proof
Induction on the depth left below a call (`1024 - e`, `good_core`); fuel plays no part in it.
EVMLean's `Ξ` runs `X` with fuel `g + 1`, and `X` runs out of fuel only with an `.error`, after
which `Θ` keeps the account map it started from, so only successful runs need an argument, and
those are followed step by step (`X_holds`, by induction on the fuel of that one run). A frame
calls `Θ` and `Lambda` one level deeper; at depth 1024 it makes no call.
- `Xi_holds`, the frame property, the one walk over EVMLean's instructions: a frame whose code
owner is not `a` changes `a`'s account only through the calls and creations it makes and by
sending value to `a` (a `CALL` with value, a `SELFDESTRUCT` naming `a`). The same walk carries
`SubOk` for every frame: an instruction other than a call, creation or `SELFDESTRUCT` leaves
the created accounts and the self-destruct set as they were (`step_sets`, by instruction group,
since EVMLean has no lemmas on the substate). It takes the condition
on the calls the frame makes as a parameter `Q`, which the step functions `stepOk` and so on
read off the same instructions. `SSTORE` and `TSTORE` write the frame's own account. The
instructions that leave the account map alone are EVMLean's `static_step_*_accountMap_eq`.
It also covers a frame at `a` when `P` sees only the code (`OwnerOk`): no instruction changes
the code of an account. `code_good` and `Xi_code` are that case.
- `theta_good`: an admitted call to `a` runs `a`'s code, which `Trusted` admits, and the
per-frame hypothesis applies, entered from the call's account map by its value; any other call
runs at another address and `Xi_holds` applies; a precompile leaves the account map as it was or
as the value transfer made it.
- `lambda_good`: a creation at an address other than `a` runs there and `Xi_holds` applies; one
at `a` fails, because `a` has code, and leaves the account map as it was.
## The conditions, and why each is needed
`Admissible P Trusted`:
- `balance`: `P` tolerates an increase of the balance that does not wrap. Value reaches `a`
without running its code: a transfer, a `SELFDESTRUCT` naming `a`, the priority fee when `a`
is the beneficiary. An invariant that bounds the balance from below ("the balance covers the
supply") is closed under such increases. No increase wraps: each comes from another account's
balance, or from the gas the sender paid, and the sum of all balances bounds them. EVMLean
adds modulo `2 ^ 256` without a bound of its own; the bound is that the balances add up to less
than `2 ^ 256` where the transaction (or the outermost call) starts, which the chain satisfies,
and every step keeps the sum from growing:
- A value transfer moves `v` from a payer that has it (`total_sendEth`); `CALL` and `CREATE`
check that before making the call, and `Θ`'s caller must state it (`GoodTheta`).
- A creation moves its endowment to the new account (`LambdaCall.frame_total`); the creator
has a nonce, so the new address is not the creator's.
- `SELFDESTRUCT` moves the balance to an existing account or a new one, or burns it when it
names itself in the transaction that created it (`total_sd_move`, `total_sd_new`,
`total_insert_insert_zero`).
- A failed call or creation returns the account map it was given.
Balance that leaves `a` (a `CALL` with value from `a`, a creation `a` pays for, `SELFDESTRUCT`
at `a`) is the frame's own effect: `GoodTheta` and `GoodLambda` ask for `Holds` after the value
is taken, and `FrameHyp` for `P` after the frame.
- `code`: `a` has code, so no creation can land on `a` (`Lambda` keeps the account map when the
target has code or a nonce).
- `trusted`: a `CALL` or `STATICCALL` to `a` runs the code `a` has, which must be code the
per-frame hypothesis covers.
`Trusted` is the condition on `DELEGATECALL`: a frame at `a` may assume `Deeper` only of calls
that run trusted code when their recipient is `a`. A `DELEGATECALL` or `CALLCODE` from `a` runs
other code at `a`, which writes `a`'s storage directly, so the per-frame hypothesis cannot be shown
for a contract that delegates to code it has no contract for. `Trusted` may admit such code
alongside the contract's own, with the per-frame hypothesis shown for it too.
`SELFDESTRUCT` and code replacement follow EVMLean's rules (Cancun and later): `SELFDESTRUCT`
moves the balance, and removes the account only at the end of a transaction that created it. No
instruction replaces code; a creation sets code only at an address without code or nonce.
## What remains
- A sequence of transactions, or a block, is the iteration of `tx_holds`; it is not stated.
-/
namespace Ethereum.EVM.Invariant
/-! ## The invariant -/
section Defs
variable (a : AccountAddress) (P : Account → Prop) (Trusted : ByteArray → Prop)
/-- `a`'s account exists and satisfies `P`. -/
def Holds (σ : AccountMap) : Prop := ∃ acc, σ[a]? = some acc ∧ P acc
/-- The code a message call runs is one `Trusted` admits, or a precompile. -/
def CodeOk : ToExecute → Prop
| .Precompiled _ => True
| .Code d => Trusted d
/-- The balance `s` pays before a creation runs, as `Lambda` takes it. -/
def debit (σ : AccountMap) (s : AccountAddress) (v : UInt256) : AccountMap :=
match σ.get? s with
| none => σ
| some ac => σ.insert s {ac with balance := ac.balance - v}
/-- `P` sees an account only through its code. -/
def CodeOnly : Prop := ∀ acc acc', acc.code = acc'.code → P acc → P acc'
/-- What `P` must allow. -/
structure Admissible : Prop where
/-- Value can arrive without a call: by a transfer, a `SELFDESTRUCT`, a fee. Only increases that
do not wrap: the sum of all balances bounds every balance and every increase. -/
balance : ∀ acc v, P acc → acc.balance.toNat + v.toNat < UInt256.size →
P {acc with balance := acc.balance + v}
/-- `a` has code, so no creation can land on it. -/
code : ∀ acc, P acc → acc.code.size ≠ 0
/-- A message call to `a` runs code that `Trusted` admits. -/
trusted : ∀ acc, P acc → Trusted acc.code
end Defs
/-! ## The sum of all balances -/
theorem UInt256.sub_zero' (x : UInt256) : x - ⟨0⟩ = x := by
cases x
show UInt256.mk _ = _
simp
/-- The sum of all balances, as a natural number. -/
def total (σ : AccountMap) : ℕ := (σ.toList.map fun p => p.2.balance.toNat).sum
theorem toList_nodup (σ : AccountMap) : σ.toList.Nodup :=
(Std.ExtTreeMap.distinct_keys_toList (t := σ)).imp fun h he =>
h (by rw [he]; exact Std.ReflCmp.compare_self)
theorem total_perm {σ : AccountMap} {l : List (AccountAddress × Account)} (h : σ.toList.Perm l) :
total σ = (l.map fun p => p.2.balance.toNat).sum := by
unfold total
exact (h.map _).sum_eq
/-- The account map with `k` set to `x` lists `(k, x)` and the rest without `k`. -/
theorem toList_insert_perm (σ : AccountMap) (k : AccountAddress) (x : Account) :
(σ.insert k x).toList.Perm ((k, x) :: (σ.erase k).toList) := by
rw [List.perm_ext_iff_of_nodup (toList_nodup _)]
· rintro ⟨k', v'⟩
simp only [Std.ExtTreeMap.mem_toList_iff_getElem?_eq_some, List.mem_cons, Prod.mk.injEq,
Std.ExtTreeMap.getElem?_insert, Std.ExtTreeMap.getElem?_erase]
by_cases hk : k = k'
· subst hk; simp [eq_comm]
· simp [Std.LawfulEqCmp.compare_eq_iff_eq, hk, Ne.symm hk]
· refine List.nodup_cons.mpr ⟨fun hm => ?_, toList_nodup _⟩
rw [Std.ExtTreeMap.mem_toList_iff_getElem?_eq_some, Std.ExtTreeMap.getElem?_erase_self] at hm
cases hm
theorem total_insert (σ : AccountMap) (k : AccountAddress) (x : Account) :
total (σ.insert k x) = x.balance.toNat + total (σ.erase k) := by
rw [total_perm (toList_insert_perm σ k x)]
simp [total]
theorem total_of_some {σ : AccountMap} {k : AccountAddress} {x : Account} (h : σ[k]? = some x) :
total σ = x.balance.toNat + total (σ.erase k) := by
have : σ.insert k x = σ := by
apply Std.ExtTreeMap.ext_getElem?
intro k'
rw [Std.ExtTreeMap.getElem?_insert]
split
· rename_i hc
rw [Std.LawfulEqCmp.eq_of_compare hc] at h
exact h.symm
· rfl
rw [← total_insert, this]
theorem total_of_none {σ : AccountMap} {k : AccountAddress} (h : σ[k]? = none) :
total σ = total (σ.erase k) := by
congr 1
apply Std.ExtTreeMap.ext_getElem?
intro k'
rw [Std.ExtTreeMap.getElem?_erase]
split
· rename_i hc
rw [← Std.LawfulEqCmp.eq_of_compare hc]
exact h
· rfl
theorem total_insert_some {σ : AccountMap} {k : AccountAddress} {x y : Account}
(h : σ[k]? = some y) : total (σ.insert k x) + y.balance.toNat = total σ + x.balance.toNat := by
rw [total_insert, total_of_some h]; omega
theorem total_insert_none {σ : AccountMap} {k : AccountAddress} {x : Account}
(h : σ[k]? = none) : total (σ.insert k x) = total σ + x.balance.toNat := by
rw [total_insert, total_of_none h]; omega
theorem total_insert_same {σ : AccountMap} {k : AccountAddress} {x y : Account}
(h : σ[k]? = some y) (hb : x.balance = y.balance) : total (σ.insert k x) = total σ := by
have := total_insert_some (x := x) h
rw [hb] at this; omega
theorem balance_le_total {σ : AccountMap} {k : AccountAddress} {x : Account}
(h : σ[k]? = some x) : x.balance.toNat ≤ total σ := by
rw [total_of_some h]; omega
theorem two_le_total {σ : AccountMap} {k j : AccountAddress} {x y : Account}
(hk : σ[k]? = some x) (hj : σ[j]? = some y) (hne : k ≠ j) :
x.balance.toNat + y.balance.toNat ≤ total σ := by
have hj' : (σ.erase k)[j]? = some y := by
rw [Std.ExtTreeMap.getElem?_erase]
simp [Std.LawfulEqCmp.compare_eq_iff_eq, hne, hj]
rw [total_of_some hk]
have := balance_le_total hj'
omega
/-- The balance of an account, zero if there is none, as `CALL` and `CREATE` read it. -/
def balOf (σ : AccountMap) (k : AccountAddress) : UInt256 := σ.get? k |>.option ⟨0⟩ (·.balance)
theorem UInt256.toNat_lt (x : UInt256) : x.toNat < UInt256.size := x.val.isLt
theorem UInt256.toNat_add_of_lt {x y : UInt256} (h : x.toNat + y.toNat < UInt256.size) :
(x + y).toNat = x.toNat + y.toNat := by
show (x.val + y.val).val = _
rw [Fin.val_add]
exact Nat.mod_eq_of_lt h
theorem UInt256.toNat_sub_of_le {x y : UInt256} (h : y ≤ x) :
(x - y).toNat = x.toNat - y.toNat := by
show (x.val - y.val).val = _
exact Fin.sub_val_of_le h
theorem UInt256.add_sub_cancel' (x y : UInt256) : x + y - y = x := by
cases x; cases y
show UInt256.mk _ = _
congr 1
exact add_sub_cancel_right _ _
theorem balOf_of_some {σ : AccountMap} {k : AccountAddress} {x : Account} (h : σ[k]? = some x) :
balOf σ k = x.balance := by
simp [balOf, Std.ExtTreeMap.get?_eq_getElem?, h, Option.option]
theorem balOf_of_none {σ : AccountMap} {k : AccountAddress} (h : σ[k]? = none) :
balOf σ k = ⟨0⟩ := by
simp [balOf, Std.ExtTreeMap.get?_eq_getElem?, h, Option.option]
theorem UInt256.eq_zero_of_le_zero {v : UInt256} (h : v ≤ ⟨0⟩) : v = ⟨0⟩ := by
cases v with
| mk val =>
congr 1
exact Fin.ext (Nat.le_zero.mp h)
theorem total_insert_bal (σ : AccountMap) (k : AccountAddress) (x : Account) :
total (σ.insert k x) + (balOf σ k).toNat = total σ + x.balance.toNat := by
cases h : σ[k]? with
| none => rw [total_insert_none h, balOf_of_none h]; rfl
| some y => rw [balOf_of_some h]; exact total_insert_some h
theorem balOf_insert_self (σ : AccountMap) (k : AccountAddress) (x : Account) :
balOf (σ.insert k x) k = x.balance :=
balOf_of_some (by simp)
theorem balOf_eq_getD (σ : AccountMap) (k : AccountAddress) :
balOf σ k = (σ.get? k |>.getD default).balance := by
unfold balOf
cases σ.get? k <;> rfl
theorem getElem?_insert_ne' {σ : AccountMap} {k k' : AccountAddress} {x : Account}
(h : k ≠ k') : (σ.insert k x)[k']? = σ[k']? := by
rw [Std.ExtTreeMap.getElem?_insert]
simp [Std.LawfulEqCmp.compare_eq_iff_eq, h]
/-- A value transfer, when the payer has the value, keeps the sum of balances. -/
theorem total_sendEth {σ : AccountMap} {r s : AccountAddress} {v : UInt256}
(hv : v ≤ balOf σ s) (hT : total σ < UInt256.size) :
total (sendEth r s v true σ) = total σ := by
unfold sendEth
simp only [ite_true, Std.ExtTreeMap.get?_eq_getElem?]
by_cases hrs : r = s
· subst hrs
cases hr : σ[r]? with
| none =>
rw [balOf_of_none hr] at hv
have := UInt256.eq_zero_of_le_zero hv
subst this
have h0 : ((⟨0⟩ : UInt256) != UInt256.ofNat 0) = false := rfl
simp only [hr, h0, Bool.false_eq_true, ite_false]
| some acc =>
simp only [Std.ExtTreeMap.getElem?_insert_self]
have h1 := total_insert_some (x := { acc with balance := acc.balance + v }) hr
have h2 := total_insert_some (σ := σ.insert r { acc with balance := acc.balance + v })
(x := { acc with balance := acc.balance + v - v }) (Std.ExtTreeMap.getElem?_insert_self)
simp only [UInt256.add_sub_cancel'] at h1 h2 ⊢
omega
· cases hs : σ[s]? with
| none =>
rw [balOf_of_none hs] at hv
have := UInt256.eq_zero_of_le_zero hv
subst this
have h0 : ((⟨0⟩ : UInt256) != UInt256.ofNat 0) = false := rfl
cases hr : σ[r]? with
| none => simp only [h0, Bool.false_eq_true, ite_false, hs]
| some acc =>
simp only [getElem?_insert_ne' hrs, hs]
exact total_insert_same hr (by
show acc.balance + ⟨0⟩ = acc.balance
cases acc.balance; show UInt256.mk _ = _; simp)
| some sacc =>
rw [balOf_of_some hs] at hv
have hsub := UInt256.toNat_sub_of_le hv
have hvle : v.toNat ≤ sacc.balance.toNat := hv
cases hr : σ[r]? with
| none =>
by_cases hv0 : v = UInt256.ofNat 0
· subst hv0
simp only [bne_self_eq_false, Bool.false_eq_true, ite_false, hs]
exact total_insert_same hs (UInt256.sub_zero' _)
· simp only [hv0, bne_iff_ne, ne_eq, not_false_eq_true, ite_true,
getElem?_insert_ne' hrs, hs]
have h1 := total_insert_none (x := { (default : Account) with balance := v }) hr
have h2 := total_insert_some (σ := σ.insert r { (default : Account) with balance := v })
(x := { sacc with balance := sacc.balance - v })
(by rw [getElem?_insert_ne' hrs]; exact hs)
simp only at h1 h2
omega
| some racc =>
simp only [getElem?_insert_ne' hrs, hs]
have hle := two_le_total hr hs hrs
have hadd := UInt256.toNat_add_of_lt (x := racc.balance) (y := v) (by omega)
have h1 := total_insert_some (x := { racc with balance := racc.balance + v }) hr
have h2 := total_insert_some
(σ := σ.insert r { racc with balance := racc.balance + v })
(x := { sacc with balance := sacc.balance - v })
(by rw [getElem?_insert_ne' hrs]; exact hs)
simp only at h1 h2
omega
section HoldsLemmas
variable {a : AccountAddress} {P : Account → Prop} {Trusted : ByteArray → Prop}
theorem Holds.insert_ne {σ : AccountMap} {k : AccountAddress} {x : Account} (hk : k ≠ a)
(h : Holds a P σ) : Holds a P (σ.insert k x) := by
obtain ⟨acc, hacc, hP⟩ := h
refine ⟨acc, ?_, hP⟩
rw [Std.ExtTreeMap.getElem?_insert]
simp [Std.LawfulEqCmp.compare_eq_iff_eq, hk, hacc]
theorem Holds.insert_self {σ : AccountMap} {x : Account} (hx : P x) :
Holds a P (σ.insert a x) :=
⟨x, by simp, hx⟩
theorem Holds.get {σ : AccountMap} (h : Holds a P σ) :
∃ acc, σ.get? a = some acc ∧ P acc := by
simpa [Std.ExtTreeMap.get?_eq_getElem?] using! h
theorem Holds.of_eq {σ τ : AccountMap} (h : Holds a P σ) (he : τ = σ) : Holds a P τ :=
he ▸ h
/-- A write to the account of a frame's owner keeps `Holds` when the owner is not `a`, or when
`P` sees only the code and the write keeps it. -/
theorem Holds.insert_owner {σ : AccountMap} {k : AccountAddress} {x : Account}
(hk : k ≠ a ∨ CodeOnly P) (hx : ∀ old, σ[k]? = some old → old.code = x.code)
(h : Holds a P σ) : Holds a P (σ.insert k x) := by
by_cases hka : k = a
· subst hka
obtain ⟨acc, hacc, hP⟩ := h
exact Holds.insert_self (hk.resolve_left (fun h => h rfl) acc x (hx acc hacc) hP)
· exact h.insert_ne hka
theorem Holds.transfer (hadm : Admissible P Trusted) {σ : AccountMap} {r s : AccountAddress}
{v : UInt256} (hs : s ≠ a ∨ v = ⟨0⟩ ∨ CodeOnly P) (hv : v ≤ balOf σ s)
(hT : total σ < UInt256.size) (h : Holds a P σ) :
Holds a P (sendEth r s v true σ) := by
have h1 : Holds a P (match σ.get? r with
| none =>
if (v != UInt256.ofNat 0) = true then
σ.insert r
{ nonce := (default : Account).nonce, balance := v,
storage := (default : Account).storage, code := (default : Account).code,
tstorage := (default : Account).tstorage }
else σ
| some acc =>
σ.insert r
{ nonce := acc.nonce, balance := acc.balance + v, storage := acc.storage,
code := acc.code, tstorage := acc.tstorage }) := by
obtain ⟨acc, hacc, hP⟩ := h
split
· rename_i hr
have hra : r ≠ a := by
rintro rfl
simp [Std.ExtTreeMap.get?_eq_getElem?, hacc] at hr
split
· exact Holds.insert_ne hra ⟨acc, hacc, hP⟩
· exact ⟨acc, hacc, hP⟩
· rename_i accr hr
by_cases hra : r = a
· subst hra
have : accr = acc := by
simpa [Std.ExtTreeMap.get?_eq_getElem?, hacc] using hr.symm
subst this
have hacc' : σ[r]? = some accr := by simpa [Std.ExtTreeMap.get?_eq_getElem?] using hr
refine Holds.insert_self ?_
rcases hs with hsa | hv0 | hco
· cases hsv : σ[s]? with
| none =>
rw [balOf_of_none hsv] at hv
have hv0 := UInt256.eq_zero_of_le_zero hv
subst hv0
exact hadm.balance _ _ hP (by simpa using UInt256.toNat_lt accr.balance)
| some sacc =>
rw [balOf_of_some hsv] at hv
have hle := two_le_total hacc' hsv (Ne.symm hsa)
have hvle : v.toNat ≤ sacc.balance.toNat := hv
exact hadm.balance _ _ hP (by omega)
· subst hv0
exact hadm.balance _ _ hP (by simpa using UInt256.toNat_lt accr.balance)
· exact hco accr _ rfl hP
· exact Holds.insert_ne hra ⟨acc, hacc, hP⟩
have h2 : ∀ τ : AccountMap, Holds a P τ → Holds a P (match τ.get? s with
| none => τ
| some acc =>
τ.insert s
{ nonce := acc.nonce, balance := acc.balance - v, storage := acc.storage,
code := acc.code, tstorage := acc.tstorage }) := by
intro τ hτ
split
· exact hτ
· rename_i accs hs'
by_cases hsa : s = a
· subst hsa
obtain ⟨acc, hacc, hP⟩ := hτ
have : accs = acc := by
simpa [Std.ExtTreeMap.get?_eq_getElem?, hacc] using hs'.symm
subst this
refine Holds.insert_self ?_
rcases hs with hs | hv | hco
· exact absurd rfl hs
· subst hv
simpa [UInt256.sub_zero'] using hP
· exact hco accs _ rfl hP
· exact Holds.insert_ne hsa hτ
exact h2 _ h1
theorem Holds.pay {σ : AccountMap} {s : AccountAddress} {v : UInt256}
(hs : s ≠ a ∨ CodeOnly P) (h : Holds a P σ) : Holds a P (debit σ s v) := by
unfold debit
split
· exact h
· rename_i ac hac
refine h.insert_owner hs fun old hold => ?_
have : old = ac := by simpa [Std.ExtTreeMap.get?_eq_getElem?, hold] using hac
subst this
rfl
theorem Holds.ite {σ τ : AccountMap} {c : Prop} [Decidable c] (hσ : Holds a P σ)
(hτ : Holds a P τ) : Holds a P (if c then σ else τ) := by
split
· exact hσ
· exact hτ
theorem Holds.lambdaStar {σ : AccountMap} {s a' : AccountAddress} {v : UInt256} {x : Account}
(ha' : a' ≠ a) (hdebit : Holds a P (debit σ s v)) :
Holds a P (match σ.get? s with
| none => σ
| some ac => (σ.insert s {ac with balance := ac.balance - v}).insert a' x) := by
unfold debit at hdebit
split
· rename_i hs
rw [hs] at hdebit
exact hdebit
· rename_i ac hs
rw [hs] at hdebit
exact hdebit.insert_ne ha'
theorem codeOk_toExecute (hadm : Admissible P Trusted) {fork : Fork} {σ : AccountMap}
(h : Holds a P σ) : CodeOk Trusted (toExecute fork σ a) := by
obtain ⟨acc, hacc, hP⟩ := h.get
unfold toExecute
split
· trivial
· simp only [Id.run, hacc]
exact hadm.trusted acc hP
theorem codeOk_of_all {Trusted : ByteArray → Prop} (h : ∀ d, Trusted d) (c : ToExecute) :
CodeOk Trusted c := by
cases c
· exact h _
· trivial
end HoldsLemmas
/-! ## The substate -/
/-- `a` is neither among the accounts created in this transaction nor in the self-destruct set.
`Υ` erases the accounts in that set at the end of the transaction. -/
def SubOk (a : AccountAddress) (A : Substate) : Prop :=
a ∉ A.createdAccounts.toList ∧ a ∉ A.selfDestructSet.toList
/-- The created accounts and the self-destruct set are as they were. -/
def SameSets (A A' : Substate) : Prop :=
A'.createdAccounts = A.createdAccounts ∧ A'.selfDestructSet = A.selfDestructSet
section Sets
variable {state state' : State}
theorem sets_execUnOp {f : Primop.Unary} (h : execUnOp f state = .ok state') :
SameSets state.substate state'.substate := by
unfold execUnOp at h; split at h <;> try contradiction
injection h with h; rw [← h]; exact ⟨rfl, rfl⟩
theorem sets_execBinOp {f : Primop.Binary} (h : execBinOp f state = .ok state') :
SameSets state.substate state'.substate := by
unfold execBinOp at h; split at h <;> try contradiction
injection h with h; rw [← h]; exact ⟨rfl, rfl⟩
theorem sets_execTriOp {f : Primop.Ternary} (h : execTriOp f state = .ok state') :
SameSets state.substate state'.substate := by
unfold execTriOp at h; split at h <;> try contradiction
injection h with h; rw [← h]; exact ⟨rfl, rfl⟩
theorem sets_machineStateOp {f : MachineState → UInt256} (h : machineStateOp f state = .ok state') :
SameSets state.substate state'.substate := by
unfold machineStateOp at h
injection h with h; rw [← h]; exact ⟨rfl, rfl⟩
theorem sets_executionEnvOp {f : ExecutionEnv → UInt256} (h : executionEnvOp f state = .ok state') :
SameSets state.substate state'.substate := by
unfold executionEnvOp at h
injection h with h; rw [← h]; exact ⟨rfl, rfl⟩
theorem sets_unaryStateOp {f : State → UInt256 → State × UInt256}
(hf : ∀ s v, SameSets s.substate (f s v).1.substate) (h : unaryStateOp f state = .ok state') :
SameSets state.substate state'.substate := by
unfold unaryStateOp at h; split at h <;> try contradiction
injection h with h; rw [← h]; exact hf _ _
theorem sets_stateOp {f : State → UInt256} (h : stateOp f state = .ok state') :
SameSets state.substate state'.substate := by
unfold stateOp at h
injection h with h; rw [← h]; exact ⟨rfl, rfl⟩
theorem sets_binaryMachineStateOp {f : MachineState → UInt256 → UInt256 → MachineState}
(h : binaryMachineStateOp f state = .ok state') : SameSets state.substate state'.substate := by
unfold binaryMachineStateOp at h; split at h <;> try contradiction
injection h with h; rw [← h]; exact ⟨rfl, rfl⟩
theorem sets_binaryMachineStateOp' {f : MachineState → UInt256 → UInt256 → UInt256 × MachineState}
(h : binaryMachineStateOp' f state = .ok state') : SameSets state.substate state'.substate := by
unfold binaryMachineStateOp' at h; split at h <;> try contradiction
injection h with h; rw [← h]; exact ⟨rfl, rfl⟩
theorem sets_ternaryMachineStateOp
{f : MachineState → UInt256 → UInt256 → UInt256 → MachineState}
(h : ternaryMachineStateOp f state = .ok state') : SameSets state.substate state'.substate := by
unfold ternaryMachineStateOp at h; split at h <;> try contradiction
injection h with h; rw [← h]; exact ⟨rfl, rfl⟩
theorem sets_ternaryCopyOp {f : State → UInt256 → UInt256 → UInt256 → State}
(hf : ∀ s a b c, SameSets s.substate (f s a b c).substate)
(h : ternaryCopyOp f state = .ok state') : SameSets state.substate state'.substate := by
unfold ternaryCopyOp at h; split at h <;> try contradiction
injection h with h; rw [← h]; exact hf _ _ _ _
theorem sets_quaternaryCopyOp {f : State → UInt256 → UInt256 → UInt256 → UInt256 → State}
(hf : ∀ s a b c d, SameSets s.substate (f s a b c d).substate)
(h : quaternaryCopyOp f state = .ok state') : SameSets state.substate state'.substate := by
unfold quaternaryCopyOp at h; split at h <;> try contradiction
injection h with h; rw [← h]; exact hf _ _ _ _ _
theorem sets_binaryStateOp {f : State → UInt256 → UInt256 → State}
(hf : ∀ s a b, SameSets s.substate (f s a b).substate)
(h : binaryStateOp f state = .ok state') : SameSets state.substate state'.substate := by
unfold binaryStateOp at h; split at h <;> try contradiction
injection h with h; rw [← h]; exact hf _ _ _
theorem sets_dup {n : ℕ} (h : dup n state = .ok state') :
SameSets state.substate state'.substate := by
unfold dup at h
by_cases hlen : (List.take n state.machineState.stack).length = n
· rw [ite_eq_left hlen] at h
injection h with h; rw [← h]; exact ⟨rfl, rfl⟩
· rw [ite_eq_right hlen] at h
contradiction
theorem sets_swap {n : ℕ} (h : swap n state = .ok state') :
SameSets state.substate state'.substate := by
unfold swap at h
by_cases hlen : (List.take (n + 1) state.machineState.stack).length = n + 1
· rw [ite_eq_left hlen] at h
injection h with h; rw [← h]; exact ⟨rfl, rfl⟩
· rw [ite_eq_right hlen] at h
contradiction
theorem sets_sstore (s : State) (k v : UInt256) : SameSets s.substate (s.sstore k v).substate := by
unfold Ethereum.State.sstore
simp only [Ethereum.State.lookupAccount]
rcases s.accountMap.get? s.executionEnv.codeOwner with _ | acc <;> exact ⟨rfl, rfl⟩
theorem sets_tstore (s : State) (k v : UInt256) : SameSets s.substate (s.tstore k v).substate := by
unfold Ethereum.State.tstore
simp only [Ethereum.State.lookupAccount]
rcases s.accountMap.get? s.executionEnv.codeOwner with _ | acc <;> exact ⟨rfl, rfl⟩
theorem sets_extCodeHash (s : State) (v : UInt256) :
SameSets s.substate (s.extCodeHash v).1.substate := by
unfold Ethereum.State.extCodeHash
dsimp only
split <;> exact ⟨rfl, rfl⟩
/-- An instruction other than a system one leaves the created accounts and the self-destruct set
as they were. -/
theorem step_sets {op : Operation} {gasCost : ℕ} {arg : Option (UInt256 × Nat)}
(hop : ∀ s, op ≠ .System s) (h : step gasCost (op, arg) state = .ok state') :
SameSets state.substate state'.substate := by
rcases op with op | op | op | op | op | op | op | op | op | op | op
rotate_right
· exact absurd rfl (hop op)
all_goals cases op <;> simp [step] at h
all_goals first
| (have hs := sets_execUnOp h; exact hs)
| (split at h <;> first | contradiction | (have hs := sets_execUnOp h; exact hs))
| (have hs := sets_execBinOp h; exact hs)
| (have hs := sets_execTriOp h; exact hs)
| (have hs := sets_machineStateOp h; exact hs)
| (have hs := sets_executionEnvOp h; exact hs)
| (have hs := sets_stateOp h; exact hs)
| (have hs := sets_binaryMachineStateOp h; exact hs)
| (have hs := sets_binaryMachineStateOp' h; exact hs)
| (have hs := sets_ternaryMachineStateOp h; exact hs)
| (have hs := sets_dup h; exact hs)
| (have hs := sets_swap h; exact hs)
| (have hs := sets_binaryStateOp sets_sstore h; exact hs)
| (have hs := sets_binaryStateOp sets_tstore h; exact hs)
| (have hs := sets_unaryStateOp
(by intros; first | exact ⟨rfl, rfl⟩ | exact sets_extCodeHash _ _) h
exact hs)
| (have hs := sets_ternaryCopyOp (by intros; exact ⟨rfl, rfl⟩) h; exact hs)
| (have hs := sets_quaternaryCopyOp (by intros; exact ⟨rfl, rfl⟩) h; exact hs)
| (rw [← h]; exact ⟨rfl, rfl⟩)
| (simp only [log0Op, log1Op, log2Op, log3Op, log4Op, evmLogOp] at h
split at h <;> try contradiction
injection h with hst
rw [← hst]
exact ⟨rfl, rfl⟩)
| (split at h <;> try contradiction
injection h with hst
rw [← hst]
exact ⟨rfl, rfl⟩)
end Sets
theorem SubOk.ite {a : AccountAddress} {A B : Substate} {c : Prop} [Decidable c]
(hA : SubOk a A) (hB : SubOk a B) : SubOk a (if c then A else B) := by
split
· exact hA
· exact hB
theorem SubOk.of_sets {a : AccountAddress} {A A' : Substate} (h : SubOk a A)
(hs : SameSets A A') : SubOk a A' := by
obtain ⟨h1, h2⟩ := h
exact ⟨hs.1 ▸ h1, hs.2 ▸ h2⟩
/-- `SELFDESTRUCT` adds the running account to the self-destruct set only when it is among the
accounts this transaction created, which `a` is not. -/
theorem SubOk.selfdestruct {a o r : AccountAddress} {A : Substate} (h : SubOk a A)
(ho : o ∈ A.createdAccounts) :
SubOk a { A with selfDestructSet := A.selfDestructSet.insert o,
accessedAccounts := A.accessedAccounts.insert r } := by
refine ⟨h.1, fun hmem => ?_⟩
rcases RBTree.RBSet.mem_toList_insert.mp hmem with ⟨hmem, -⟩ | rfl
· exact h.2 hmem
· obtain ⟨y, hy, hcmp⟩ := RBTree.RBSet.mem_iff_mem_toList.mp ho
rw [Std.LawfulEqCmp.eq_of_compare hcmp] at h
exact h.1 hy
/-! ## What the calls must do -/
/-- The environment `Θ` runs code `code` in. -/
def ThetaCall.env (T : ThetaCall) (code : ByteArray) : ExecutionEnv :=
{ codeOwner := T.r, sender := T.o, gasPrice := T.p.toNat, calldata := T.d, source := T.s,
weiValue := T.v', depth := T.e, perm := T.w, code := code, header := T.H,
blobVersionedHashes := T.bvh, blocks := T.blocks }
section Good
variable (a : AccountAddress) (P : Account → Prop) (Trusted : ByteArray → Prop)
(Enters : AccountMap → ExecutionEnv → UInt256 → Prop)
/-- Every entry into a frame at `a` from another account, by a call that moves the value it
reports, satisfies `Enters`: what frames elsewhere and the transaction's outermost call give. -/
def FromOthers : Prop := ∀ σ (I : ExecutionEnv) v, I.source ≠ a → v = I.weiValue → Enters σ I v
/-- A message call keeps `Holds`, if it starts from a state where it holds both before and after
the value moves, has calldata that fits a word, and, when its recipient is `a`, runs `Trusted`
code and is entered as `Enters` allows (unless `P` sees only the code); and it keeps `SubOk`
of the substate. -/
def GoodTheta (T : ThetaCall) : Prop :=
T.d.size < UInt256.size → (T.r = a → CodeOk Trusted T.c) →
(T.r = a → (∀ code, T.c = .Code code → Enters T.σ (T.env code) T.v) ∨ CodeOnly P) →
T.v ≤ balOf T.σ T.s →
total T.σ < UInt256.size → Holds a P T.σ → Holds a P (sendEth T.r T.s T.v true T.σ) →
Holds a P T.run.1 ∧ (SubOk a T.A → SubOk a T.run.2.2.1) ∧ total T.run.1 ≤ total T.σ
/-- A creation keeps `Holds`, if it holds before and after the creator pays; and it keeps `SubOk`
of the substate. -/
def GoodLambda (L : LambdaCall) : Prop :=
L.v ≤ balOf L.σ L.s → (L.σ.getD L.s default).nonce ≠ ⟨0⟩ → total L.σ < UInt256.size →
Holds a P L.σ → Holds a P (debit L.σ L.s L.v) →
Holds a P L.run.2.1 ∧ (SubOk a L.A → SubOk a L.run.2.2.2.1) ∧
total L.run.2.1 ≤ total L.σ
end Good
/-! ## The frame property -/
section Frame
variable {a : AccountAddress} {P : Account → Prop} {Trusted : ByteArray → Prop}
{Enters : AccountMap → ExecutionEnv → UInt256 → Prop}
variable (a P Trusted) in
/-- A frame owned by `o` writes `a`'s account only through what it calls, or `P` sees only code
and any code may run at `a`. -/
def OwnerOk (o : AccountAddress) : Prop := o ≠ a ∨ (CodeOnly P ∧ ∀ d, Trusted d)
theorem OwnerOk.ne_or_codeOnly {o : AccountAddress} (h : OwnerOk a P Trusted o) :
o ≠ a ∨ CodeOnly P :=
h.imp id (·.1)
theorem sstore_accountMap (state : State) (k v : UInt256) :
(state.sstore k v).accountMap = state.accountMap ∨
∃ acc x, state.accountMap[state.executionEnv.codeOwner]? = some acc ∧
acc.code = x.code ∧ acc.balance = x.balance ∧
(state.sstore k v).accountMap = state.accountMap.insert state.executionEnv.codeOwner x := by
unfold Ethereum.State.sstore
simp only [Ethereum.State.lookupAccount]
rcases h : state.accountMap.get? state.executionEnv.codeOwner with _ | acc
· exact Or.inl (by simp [Option.option])
· refine Or.inr ⟨acc, acc.updateStorage k v, ?_, ?_, ?_, ?_⟩
· simpa [Std.ExtTreeMap.get?_eq_getElem?] using h
· unfold Account.updateStorage; split <;> rfl
· unfold Account.updateStorage; split <;> rfl
· simp [Option.option, Ethereum.State.setAccount, Ethereum.State.addAccessedStorageKey]
theorem tstore_accountMap (state : State) (k v : UInt256) :
(state.tstore k v).accountMap = state.accountMap ∨
∃ acc x, state.accountMap[state.executionEnv.codeOwner]? = some acc ∧
acc.code = x.code ∧ acc.balance = x.balance ∧
(state.tstore k v).accountMap = state.accountMap.insert state.executionEnv.codeOwner x := by
unfold Ethereum.State.tstore
simp only [Ethereum.State.lookupAccount]
rcases h : state.accountMap.get? state.executionEnv.codeOwner with _ | acc
· exact Or.inl (by simp [Option.option])
· refine Or.inr ⟨acc, acc.updateTransientStorage k v, ?_, ?_, ?_, ?_⟩
· simpa [Std.ExtTreeMap.get?_eq_getElem?] using h
· unfold Account.updateTransientStorage; split <;> rfl
· unfold Account.updateTransientStorage; split <;> rfl
· simp [Option.option, Ethereum.State.updateAccount]
/-- A stack, memory, storage or control-flow instruction keeps `Holds`: only `SSTORE` and
`TSTORE` touch the account map, and only the frame owner's account. -/
theorem step_stackMemFlow {op : Operation.SMSFOp} {gasCost : Nat}
{arg : Option (UInt256 × Nat)} {state state' : State}
(hown : OwnerOk a P Trusted state.executionEnv.codeOwner) (hH : Holds a P state.accountMap)
(h : step gasCost (.StackMemFlow op, arg) state = .ok state') :
Holds a P state'.accountMap ∧ total state'.accountMap = total state.accountMap := by
have hsame : state'.accountMap = state.accountMap →
Holds a P state'.accountMap ∧ total state'.accountMap = total state.accountMap :=
fun he => ⟨hH.of_eq he, by rw [he]⟩
have hstore : ∀ {f : State → UInt256 → UInt256 → State},
(∀ st k v, (f st k v).accountMap = st.accountMap ∨
∃ acc x, st.accountMap[st.executionEnv.codeOwner]? = some acc ∧ acc.code = x.code ∧
acc.balance = x.balance ∧
(f st k v).accountMap = st.accountMap.insert st.executionEnv.codeOwner x) →
∀ {st st' : State}, st.accountMap = state.accountMap →
st.executionEnv.codeOwner = state.executionEnv.codeOwner →
binaryStateOp f st = .ok st' →
Holds a P st'.accountMap ∧ total st'.accountMap = total state.accountMap := by
intro f hf st st' hσ hown' hop
unfold binaryStateOp at hop
split at hop <;> try contradiction
rename_i k v _
injection hop with hst
subst hst
simp only [Ethereum.State.replaceStackAndIncrPC, Ethereum.State.incrPC]
rcases hf st k v with he | ⟨acc, x, hacc, hcode, hbal, he⟩
· exact ⟨hH.of_eq (he.trans hσ), by rw [he, hσ]⟩
· rw [he]
rw [hσ, hown'] at hacc ⊢
refine ⟨hH.insert_owner hown.ne_or_codeOnly fun old hold => ?_,
total_insert_same hacc hbal.symm⟩
rw [hacc] at hold
cases hold
exact hcode
cases op <;> simp [step] at h
all_goals first
| exact hsame (by simpa using static_binaryMachineStateOp_accountMap_eq h)
| exact hsame (by simpa using static_machineStateOp_accountMap_eq h)
| exact hsame (by simpa using static_ternaryMachineStateOp_accountMap_eq h)
| (have he := static_unaryStateOp_accountMap_eq (f := Ethereum.State.sload)
(by intro s v; simp [Ethereum.State.sload, Ethereum.State.addAccessedStorageKey,
Ethereum.State.lookupAccount]) h
exact hsame (by simpa using he))
| (have he := static_unaryStateOp_accountMap_eq (f := Ethereum.State.tload)
(by intro s v; simp [Ethereum.State.tload]) h
exact hsame (by simpa using he))
| exact hstore sstore_accountMap (by simp) (by simp) h
| exact hstore tstore_accountMap (by simp) (by simp) h
| (rw [← h]; exact ⟨hH, rfl⟩)
| (split at h <;> try contradiction
injection h with hst
rw [← hst]
exact ⟨hH, rfl⟩)
theorem readWithPadding_size_lt (mem : ByteArray) (o l : UInt256) :
(mem.readWithPadding o.toNat l.toNat).size < UInt256.size :=
Nat.lt_of_le_of_lt (ByteArray.readWithPadding_size_le mem o.toNat l.toNat) l.val.isLt
theorem succ_depth_val {e : Fin 1025} (h : e < 1024) : (e + 1).val = e.val + 1 := by
have hv : e.val < 1024 := by simpa using! h
rw [Fin.val_add_eq_of_add_lt] <;> simp; omega
/-- A `CALL`-family instruction keeps `Holds` when the message call it makes is good. -/
theorem call_holds {Q : CallPreds} {gasCost : Nat}
{gas source recipient t value value' inOffset inSize outOffset outSize x : UInt256}
{permission : Bool} {evmState state' : State} (hent : FromOthers a Enters)
(hQ : ∀ T : ThetaCall, T.e.val = evmState.executionEnv.depth.val + 1 → Q.theta T →
GoodTheta a P Trusted Enters T)
(hok : callOk Q gas source recipient t value value' inOffset inSize permission evmState)
(hH : Holds a P evmState.accountMap)
(hT : total evmState.accountMap < UInt256.size)
(hcode : AccountAddress.ofUInt256 recipient = a →
CodeOk Trusted (toExecute evmState.executionEnv.header.fork evmState.accountMap (AccountAddress.ofUInt256 t)))
(hval : AccountAddress.ofUInt256 recipient = a →
(AccountAddress.ofUInt256 source ≠ a ∧ value = value') ∨ CodeOnly P)
(hsrc : value ≤ balOf evmState.accountMap evmState.executionEnv.codeOwner →
value ≤ balOf evmState.accountMap (AccountAddress.ofUInt256 source))
(hpre : value ≤ balOf evmState.accountMap (AccountAddress.ofUInt256 source) →
Holds a P (sendEth (AccountAddress.ofUInt256 recipient)
(AccountAddress.ofUInt256 source) value true evmState.accountMap))
(h : call gasCost gas source recipient t value value' inOffset inSize outOffset outSize
permission evmState = .ok (x, state')) :
Holds a P state'.accountMap ∧ (SubOk a evmState.substate → SubOk a state'.substate) ∧
total state'.accountMap ≤ total evmState.accountMap := by
unfold call at h
simp at h
split at h
· rename_i hcall
rcases h with ⟨_, hstate⟩
rw [← hstate]
have hmade : value ≤ balOf evmState.accountMap evmState.executionEnv.codeOwner ∧
evmState.executionEnv.depth < 1024 := by
simpa [balOf, Std.ExtTreeMap.get?_eq_getElem?] using hcall
have hv := hsrc hmade.1
have hg := hQ _ (succ_depth_val hcall.2) (hok hmade)
(readWithPadding_size_lt _ _ _) hcode
(fun hr => (hval hr).imp_left fun h _ _ => hent _ _ _ h.1 h.2) hv hT hH (hpre hv)
exact ⟨hg.1, fun hS => hg.2.1 (hS.of_sets ⟨rfl, rfl⟩), hg.2.2⟩
· rcases h with ⟨_, hstate⟩
rw [← hstate]
exact ⟨hH, fun hS => hS.of_sets ⟨rfl, rfl⟩, le_refl _⟩
/-- A `CREATE` or `CREATE2` keeps `Holds` when the creation it makes is good. -/
theorem create_holds {Q : CallPreds} {value offset size x : UInt256} {salt : Option ByteArray}
{evmState state' : State}
(hown : OwnerOk a P Trusted evmState.executionEnv.codeOwner)
(hQl : ∀ L : LambdaCall, L.e.val = evmState.executionEnv.depth.val + 1 → Q.lambda L →
GoodLambda a P L)
(hok : createOk Q value offset size salt evmState)
(hH : Holds a P evmState.accountMap) (hT : total evmState.accountMap < UInt256.size)
(h : create value offset size salt evmState = .ok (x, state')) :