-
Notifications
You must be signed in to change notification settings - Fork 48
/
EVM.hs
2810 lines (2499 loc) · 104 KB
/
EVM.hs
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
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ImplicitParams #-}
module EVM where
import Prelude hiding (exponent)
import Optics.Core
import Optics.State
import Optics.State.Operators
import Optics.Zoom
import Optics.Operators.Unsafe
import EVM.ABI
import EVM.Expr (readStorage, writeStorage, readByte, readWord, writeWord,
writeByte, bufLength, indexWord, litAddr, readBytes, word256At, copySlice, wordToAddr)
import EVM.Expr qualified as Expr
import EVM.FeeSchedule (FeeSchedule (..))
import EVM.Op
import EVM.Precompiled qualified
import EVM.Solidity
import EVM.Types
import EVM.Types qualified as Expr (Expr(Gas))
import EVM.Sign qualified
import EVM.Concrete qualified as Concrete
import Control.Monad.ST (ST)
import Control.Monad.State.Strict hiding (state)
import Data.Bits (FiniteBits, countLeadingZeros, finiteBitSize)
import Data.ByteArray qualified as BA
import Data.ByteString (ByteString)
import Data.ByteString qualified as BS
import Data.ByteString.Lazy (fromStrict)
import Data.ByteString.Lazy qualified as LS
import Data.ByteString.Char8 qualified as Char8
import Data.Foldable (toList)
import Data.List (find)
import Data.Map.Strict (Map)
import Data.Map.Strict qualified as Map
import Data.Maybe (fromMaybe, fromJust, isJust)
import Data.Set (insert, member, fromList)
import Data.Sequence (Seq)
import Data.Sequence qualified as Seq
import Data.Text (unpack, pack)
import Data.Text.Encoding (decodeUtf8)
import Data.Tree
import Data.Tree.Zipper qualified as Zipper
import Data.Typeable
import Data.Vector qualified as V
import Data.Vector.Storable qualified as SV
import Data.Vector.Storable.Mutable qualified as SV
import Data.Vector.Unboxed qualified as VUnboxed
import Data.Vector.Unboxed.Mutable qualified as VUnboxed.Mutable
import Data.Word (Word8, Word32, Word64)
import Witch (into, tryFrom, unsafeInto)
import Crypto.Hash (Digest, SHA256, RIPEMD160)
import Crypto.Hash qualified as Crypto
import Crypto.Number.ModArithmetic (expFast)
blankState :: VMOps t => ST s (FrameState t s)
blankState = do
memory <- ConcreteMemory <$> VUnboxed.Mutable.new 0
pure $ FrameState
{ contract = LitAddr 0
, codeContract = LitAddr 0
, code = RuntimeCode (ConcreteRuntimeCode "")
, pc = 0
, stack = mempty
, memory
, memorySize = 0
, calldata = mempty
, callvalue = Lit 0
, caller = LitAddr 0
, gas = initialGas
, returndata = mempty
, static = False
}
-- | An "external" view of a contract's bytecode, appropriate for
-- e.g. @EXTCODEHASH@.
bytecode :: Getter Contract (Maybe (Expr Buf))
bytecode = #code % to f
where f (InitCode _ _) = Just mempty
f (RuntimeCode (ConcreteRuntimeCode bs)) = Just $ ConcreteBuf bs
f (RuntimeCode (SymbolicRuntimeCode ops)) = Just $ Expr.fromList ops
f (UnknownCode _) = Nothing
-- * Data accessors
currentContract :: VM t s -> Maybe Contract
currentContract vm =
Map.lookup vm.state.codeContract vm.env.contracts
-- * Data constructors
makeVm :: VMOps t => VMOpts t -> ST s (VM t s)
makeVm o = do
let txaccessList = o.txAccessList
txorigin = o.origin
txtoAddr = o.address
initialAccessedAddrs = fromList $
[txorigin, txtoAddr, o.coinbase]
++ (fmap LitAddr [1..9])
++ (Map.keys txaccessList)
initialAccessedStorageKeys = fromList $ foldMap (uncurry (map . (,))) (Map.toList txaccessList)
touched = if o.create then [txorigin] else [txorigin, txtoAddr]
memory <- ConcreteMemory <$> VUnboxed.Mutable.new 0
pure $ VM
{ result = Nothing
, frames = mempty
, tx = TxState
{ gasprice = o.gasprice
, gaslimit = o.gaslimit
, priorityFee = o.priorityFee
, origin = txorigin
, toAddr = txtoAddr
, value = o.value
, substate = SubState mempty touched initialAccessedAddrs initialAccessedStorageKeys mempty
, isCreate = o.create
, txReversion = Map.fromList ((o.address,o.contract):o.otherContracts)
}
, logs = []
, traces = Zipper.fromForest []
, block = block
, state = FrameState
{ pc = 0
, stack = mempty
, memory
, memorySize = 0
, code = o.contract.code
, contract = o.address
, codeContract = o.address
, calldata = fst o.calldata
, callvalue = o.value
, caller = o.caller
, gas = o.gas
, returndata = mempty
, static = False
}
, env = env
, cache = cache
, burned = initialGas
, constraints = snd o.calldata
, iterations = mempty
, config = RuntimeConfig
{ allowFFI = o.allowFFI
, overrideCaller = Nothing
, baseState = o.baseState
}
, forks = Seq.singleton (ForkState env block cache "")
, currentFork = 0
}
where
env = Env
{ chainId = o.chainId
, contracts = Map.fromList ((o.address,o.contract):o.otherContracts)
, freshAddresses = 0
, freshGasVals = 0
}
block = Block
{ coinbase = o.coinbase
, timestamp = o.timestamp
, number = o.number
, prevRandao = o.prevRandao
, maxCodeSize = o.maxCodeSize
, gaslimit = o.blockGaslimit
, baseFee = o.baseFee
, schedule = o.schedule
}
cache = Cache mempty mempty
-- | Initialize an abstract contract with unknown code
unknownContract :: Expr EAddr -> Contract
unknownContract addr = Contract
{ code = UnknownCode addr
, storage = AbstractStore addr Nothing
, origStorage = AbstractStore addr Nothing
, balance = Balance addr
, nonce = Nothing
, codehash = hashcode (UnknownCode addr)
, opIxMap = mempty
, codeOps = mempty
, external = False
}
-- | Initialize an abstract contract with known code
abstractContract :: ContractCode -> Expr EAddr -> Contract
abstractContract code addr = Contract
{ code = code
, storage = AbstractStore addr Nothing
, origStorage = AbstractStore addr Nothing
, balance = Balance addr
, nonce = if isCreation code then Just 1 else Just 0
, codehash = hashcode code
, opIxMap = mkOpIxMap code
, codeOps = mkCodeOps code
, external = False
}
-- | Initialize an empty contract without code
emptyContract :: Contract
emptyContract = initialContract (RuntimeCode (ConcreteRuntimeCode ""))
-- | Initialize empty contract with given code
initialContract :: ContractCode -> Contract
initialContract code = Contract
{ code = code
, storage = ConcreteStore mempty
, origStorage = ConcreteStore mempty
, balance = Lit 0
, nonce = if isCreation code then Just 1 else Just 0
, codehash = hashcode code
, opIxMap = mkOpIxMap code
, codeOps = mkCodeOps code
, external = False
}
isCreation :: ContractCode -> Bool
isCreation = \case
InitCode _ _ -> True
RuntimeCode _ -> False
UnknownCode _ -> False
-- * Opcode dispatch (exec1)
-- | Update program counter
next :: (?op :: Word8) => EVM t s ()
next = modifying (#state % #pc) (+ (opSize ?op))
-- | Executes the EVM one step
exec1 :: forall (t :: VMType) s. VMOps t => EVM t s ()
exec1 = do
vm <- get
let
-- Convenient aliases
stk = vm.state.stack
self = vm.state.contract
this = fromMaybe (internalError "state contract") (Map.lookup self vm.env.contracts)
fees@FeeSchedule {..} = vm.block.schedule
doStop = finishFrame (FrameReturned mempty)
litSelf = maybeLitAddr self
if isJust litSelf && (fromJust litSelf) > 0x0 && (fromJust litSelf) <= 0x9 then do
-- call to precompile
let ?op = 0x00 -- dummy value
let calldatasize = bufLength vm.state.calldata
copyBytesToMemory vm.state.calldata calldatasize (Lit 0) (Lit 0)
executePrecompile (fromJust litSelf) vm.state.gas (Lit 0) calldatasize (Lit 0) (Lit 0) []
vmx <- get
case vmx.state.stack of
x:_ -> case x of
Lit 0 ->
fetchAccount self $ \_ -> do
touchAccount self
vmError PrecompileFailure
Lit _ ->
fetchAccount self $ \_ -> do
touchAccount self
out <- use (#state % #returndata)
finishFrame (FrameReturned out)
e -> partial $
UnexpectedSymbolicArg vmx.state.pc "precompile returned a symbolic value" (wrap [e])
_ ->
underrun
else if vm.state.pc >= opslen vm.state.code
then doStop
else do
let ?op = case vm.state.code of
UnknownCode _ -> internalError "Cannot execute unknown code"
InitCode conc _ -> BS.index conc vm.state.pc
RuntimeCode (ConcreteRuntimeCode bs) -> BS.index bs vm.state.pc
RuntimeCode (SymbolicRuntimeCode ops) ->
fromMaybe (internalError "could not analyze symbolic code") $
maybeLitByte $ ops V.! vm.state.pc
case getOp (?op) of
OpPush0 -> do
limitStack 1 $
burn g_base $ do
next
pushSym (Lit 0)
OpPush n' -> do
let n = into n'
!xs = case vm.state.code of
UnknownCode _ -> internalError "Cannot execute unknown code"
InitCode conc _ -> Lit $ word $ padRight n $ BS.take n (BS.drop (1 + vm.state.pc) conc)
RuntimeCode (ConcreteRuntimeCode bs) -> Lit $ word $ BS.take n $ BS.drop (1 + vm.state.pc) bs
RuntimeCode (SymbolicRuntimeCode ops) ->
let bytes = V.take n $ V.drop (1 + vm.state.pc) ops
in readWord (Lit 0) $ Expr.fromList $ padLeft' 32 bytes
limitStack 1 $
burn g_verylow $ do
next
pushSym xs
OpDup i ->
case preview (ix (into i - 1)) stk of
Nothing -> underrun
Just y ->
limitStack 1 $
burn g_verylow $ do
next
pushSym y
OpSwap i ->
if length stk < (into i) + 1
then underrun
else
burn g_verylow $ do
next
zoom (#state % #stack) $ do
assign (ix 0) (stk ^?! ix (into i))
assign (ix (into i)) (stk ^?! ix 0)
OpLog n ->
notStatic $
case stk of
(xOffset:xSize:xs) ->
if length xs < (into n)
then underrun
else do
bytes <- readMemory xOffset xSize
let (topics, xs') = splitAt (into n) xs
logs' = (LogEntry (WAddr self) bytes topics) : vm.logs
burnLog xSize n $
accessMemoryRange xOffset xSize $ do
traceTopLog logs'
next
assign (#state % #stack) xs'
assign #logs logs'
_ ->
underrun
OpStop -> doStop
OpAdd -> stackOp2 g_verylow Expr.add
OpMul -> stackOp2 g_low Expr.mul
OpSub -> stackOp2 g_verylow Expr.sub
OpDiv -> stackOp2 g_low Expr.div
OpSdiv -> stackOp2 g_low Expr.sdiv
OpMod -> stackOp2 g_low Expr.mod
OpSmod -> stackOp2 g_low Expr.smod
OpAddmod -> stackOp3 g_mid Expr.addmod
OpMulmod -> stackOp3 g_mid Expr.mulmod
OpLt -> stackOp2 g_verylow Expr.lt
OpGt -> stackOp2 g_verylow Expr.gt
OpSlt -> stackOp2 g_verylow Expr.slt
OpSgt -> stackOp2 g_verylow Expr.sgt
OpEq -> stackOp2 g_verylow Expr.eq
OpIszero -> stackOp1 g_verylow Expr.iszero
OpAnd -> stackOp2 g_verylow Expr.and
OpOr -> stackOp2 g_verylow Expr.or
OpXor -> stackOp2 g_verylow Expr.xor
OpNot -> stackOp1 g_verylow Expr.not
OpByte -> stackOp2 g_verylow (\i w -> Expr.padByte $ Expr.indexWord i w)
OpShl -> stackOp2 g_verylow Expr.shl
OpShr -> stackOp2 g_verylow Expr.shr
OpSar -> stackOp2 g_verylow Expr.sar
-- more accurately referred to as KECCAK
OpSha3 ->
case stk of
xOffset:xSize:xs ->
burnSha3 xSize $
accessMemoryRange xOffset xSize $ do
hash <- readMemory xOffset xSize >>= \case
orig@(ConcreteBuf bs) ->
whenSymbolicElse
(pure $ Keccak orig)
(pure $ Lit (keccak' bs))
buf -> pure $ Keccak buf
next
assign (#state % #stack) (hash : xs)
_ -> underrun
OpAddress ->
limitStack 1 $
burn g_base (next >> pushAddr self)
OpBalance ->
case stk of
x:xs -> forceAddr x "BALANCE" $ \a ->
accessAndBurn a $
fetchAccount a $ \c -> do
next
assign (#state % #stack) xs
pushSym c.balance
[] ->
underrun
OpOrigin ->
limitStack 1 . burn g_base $
next >> pushAddr vm.tx.origin
OpCaller ->
limitStack 1 . burn g_base $
next >> pushAddr vm.state.caller
OpCallvalue ->
limitStack 1 . burn g_base $
next >> pushSym vm.state.callvalue
OpCalldataload -> stackOp1 g_verylow $
\ind -> Expr.readWord ind vm.state.calldata
OpCalldatasize ->
limitStack 1 . burn g_base $
next >> pushSym (bufLength vm.state.calldata)
OpCalldatacopy ->
case stk of
xTo:xFrom:xSize:xs ->
burnCalldatacopy xSize $
accessMemoryRange xTo xSize $ do
next
assign (#state % #stack) xs
copyBytesToMemory vm.state.calldata xSize xFrom xTo
_ -> underrun
OpCodesize ->
limitStack 1 . burn g_base $
next >> pushSym (codelen vm.state.code)
OpCodecopy ->
case stk of
memOffset:codeOffset:n:xs ->
burnCodecopy n $ do
accessMemoryRange memOffset n $ do
next
assign (#state % #stack) xs
case toBuf vm.state.code of
Just b -> copyBytesToMemory b n codeOffset memOffset
Nothing -> internalError "Cannot produce a buffer from UnknownCode"
_ -> underrun
OpGasprice ->
limitStack 1 . burn g_base $
next >> push vm.tx.gasprice
OpExtcodesize ->
case stk of
x':xs -> forceAddr x' "EXTCODESIZE" $ \x -> do
let impl = accessAndBurn x $
fetchAccount x $ \c -> do
next
assign (#state % #stack) xs
case view bytecode c of
Just b -> pushSym (bufLength b)
Nothing -> pushSym $ CodeSize x
case x of
a@(LitAddr _) -> if a == cheatCode
then do
next
assign (#state % #stack) xs
pushSym (Lit 1)
else impl
_ -> impl
[] ->
underrun
OpExtcodecopy ->
case stk of
extAccount':memOffset:codeOffset:codeSize:xs ->
forceAddr extAccount' "EXTCODECOPY" $ \extAccount -> do
burnExtcodecopy extAccount codeSize $
accessMemoryRange memOffset codeSize $
fetchAccount extAccount $ \c -> do
next
assign (#state % #stack) xs
case view bytecode c of
Just b -> copyBytesToMemory b codeSize codeOffset memOffset
Nothing -> do
pc <- use (#state % #pc)
partial $ UnexpectedSymbolicArg pc "Cannot copy from unknown code at" (wrap [extAccount])
_ -> underrun
OpReturndatasize ->
limitStack 1 . burn g_base $
next >> pushSym (bufLength vm.state.returndata)
OpReturndatacopy ->
case stk of
xTo:xFrom:xSize:xs ->
burnReturndatacopy xSize $
accessMemoryRange xTo xSize $ do
next
assign (#state % #stack) xs
let jump True = vmError ReturnDataOutOfBounds
jump False = copyBytesToMemory vm.state.returndata xSize xFrom xTo
case (xFrom, bufLength vm.state.returndata, xSize) of
(Lit f, Lit l, Lit sz) ->
jump $ l < f + sz || f + sz < f
_ -> do
let oob = Expr.lt (bufLength vm.state.returndata) (Expr.add xFrom xSize)
overflow = Expr.lt (Expr.add xFrom xSize) (xFrom)
branch (Expr.or oob overflow) jump
_ -> underrun
OpExtcodehash ->
case stk of
x':xs -> forceAddr x' "EXTCODEHASH" $ \x ->
accessAndBurn x $ do
next
assign (#state % #stack) xs
fetchAccount x $ \c ->
if accountEmpty c
then push (W256 0)
else case view bytecode c of
Just b -> pushSym $ keccak b
Nothing -> pushSym $ CodeHash x
[] ->
underrun
OpBlockhash -> do
-- We adopt the fake block hash scheme of the VMTests,
-- so that blockhash(i) is the hash of i as decimal ASCII.
stackOp1 g_blockhash $ \case
Lit i -> if i + 256 < vm.block.number || i >= vm.block.number
then Lit 0
else (into i :: Integer) & show & Char8.pack & keccak' & Lit
i -> BlockHash i
OpCoinbase ->
limitStack 1 . burn g_base $
next >> pushAddr vm.block.coinbase
OpTimestamp ->
limitStack 1 . burn g_base $
next >> pushSym vm.block.timestamp
OpNumber ->
limitStack 1 . burn g_base $
next >> push vm.block.number
OpPrevRandao -> do
limitStack 1 . burn g_base $
next >> push vm.block.prevRandao
OpGaslimit ->
limitStack 1 . burn g_base $
next >> push (into vm.block.gaslimit)
OpChainid ->
limitStack 1 . burn g_base $
next >> push vm.env.chainId
OpSelfbalance ->
limitStack 1 . burn g_low $
next >> pushSym this.balance
OpBaseFee ->
limitStack 1 . burn g_base $
next >> push vm.block.baseFee
OpPop ->
case stk of
_:xs -> burn g_base (next >> assign (#state % #stack) xs)
_ -> underrun
OpMload ->
case stk of
x:xs ->
burn g_verylow $
accessMemoryWord x $ do
next
buf <- readMemory x (Lit 32)
let w = Expr.readWordFromBytes (Lit 0) buf
assign (#state % #stack) (w : xs)
_ -> underrun
OpMstore ->
case stk of
x:y:xs ->
burn g_verylow $
accessMemoryWord x $ do
next
gets (.state.memory) >>= \case
ConcreteMemory mem -> do
case y of
Lit w ->
copyBytesToMemory (ConcreteBuf (word256Bytes w)) (Lit 32) (Lit 0) x
_ -> do
-- copy out and move to symbolic memory
buf <- freezeMemory mem
assign (#state % #memory) (SymbolicMemory $ writeWord x y buf)
SymbolicMemory mem ->
assign (#state % #memory) (SymbolicMemory $ writeWord x y mem)
assign (#state % #stack) xs
_ -> underrun
OpMstore8 ->
case stk of
x:y:xs ->
burn g_verylow $
accessMemoryRange x (Lit 1) $ do
let yByte = indexWord (Lit 31) y
next
gets (.state.memory) >>= \case
ConcreteMemory mem -> do
case yByte of
LitByte byte ->
copyBytesToMemory (ConcreteBuf (BS.pack [byte])) (Lit 1) (Lit 0) x
_ -> do
-- copy out and move to symbolic memory
buf <- freezeMemory mem
assign (#state % #memory) (SymbolicMemory $ writeByte x yByte buf)
SymbolicMemory mem ->
assign (#state % #memory) (SymbolicMemory $ writeByte x yByte mem)
assign (#state % #stack) xs
_ -> underrun
OpSload ->
case stk of
x:xs -> do
acc <- accessStorageForGas self x
let cost = if acc then g_warm_storage_read else g_cold_sload
burn cost $
accessStorage self x $ \y -> do
next
assign (#state % #stack) (y:xs)
_ -> underrun
OpSstore ->
notStatic $
case stk of
x:new:xs ->
accessStorage self x $ \current -> do
ensureGas g_callstipend $ do
let
original =
case Expr.concKeccakSimpExpr $ SLoad x this.origStorage of
Lit v -> v
_ -> 0
storage_cost =
case (maybeLitWord current, maybeLitWord new) of
(Just current', Just new') ->
if (current' == new') then g_sload
else if (current' == original) && (original == 0) then g_sset
else if (current' == original) then g_sreset
else g_sload
-- if any of the arguments are symbolic,
-- assume worst case scenario
_-> g_sset
acc <- accessStorageForGas self x
let cold_storage_cost = if acc then 0 else g_cold_sload
burn (storage_cost + cold_storage_cost) $ do
next
assign (#state % #stack) xs
modifying (#env % #contracts % ix self % #storage) (writeStorage x new)
case (maybeLitWord current, maybeLitWord new) of
(Just current', Just new') ->
unless (current' == new') $
if current' == original then
when (original /= 0 && new' == 0) $
refund (g_sreset + g_access_list_storage_key)
else do
when (original /= 0) $
if current' == 0
then unRefund (g_sreset + g_access_list_storage_key)
else when (new' == 0) $ refund (g_sreset + g_access_list_storage_key)
when (original == new') $
if original == 0
then refund (g_sset - g_sload)
else refund (g_sreset - g_sload)
-- if any of the arguments are symbolic,
-- don't change the refund counter
_ -> noop
_ -> underrun
OpJump ->
case stk of
x:xs ->
burn g_mid $ forceConcrete x "JUMP: symbolic jumpdest" $ \x' ->
case toInt x' of
Nothing -> vmError BadJumpDestination
Just i -> checkJump i xs
_ -> underrun
OpJumpi ->
case stk of
x:y:xs -> forceConcrete x "JUMPI: symbolic jumpdest" $ \x' ->
burn g_high $
let jump :: Bool -> EVM t s ()
jump False = assign (#state % #stack) xs >> next
jump _ = case toInt x' of
Nothing -> vmError BadJumpDestination
Just i -> checkJump i xs
in branch y jump
_ -> underrun
OpPc ->
limitStack 1 . burn g_base $
next >> push (unsafeInto vm.state.pc)
OpMsize ->
limitStack 1 . burn g_base $
next >> push (into vm.state.memorySize)
OpGas ->
limitStack 1 . burn g_base $
next >> pushGas
OpJumpdest -> burn g_jumpdest next
OpExp ->
-- NOTE: this can be done symbolically using unrolling like this:
-- https://hackage.haskell.org/package/sbv-9.0/docs/src/Data.SBV.Core.Model.html#.%5E
-- However, it requires symbolic gas, since the gas depends on the exponent
case stk of
base:exponent:xs ->
burnExp exponent $ do
next
(#state % #stack) .= Expr.exp base exponent : xs
_ -> underrun
OpSignextend -> stackOp2 g_low Expr.sex
OpCreate ->
notStatic $
case stk of
xValue:xOffset:xSize:xs ->
accessMemoryRange xOffset xSize $ do
availableGas <- use (#state % #gas)
let
(cost, gas') = costOfCreate fees availableGas xSize False
newAddr <- createAddress self this.nonce
_ <- accessAccountForGas newAddr
burn' cost $ do
initCode <- readMemory xOffset xSize
create self this xSize gas' xValue xs newAddr initCode
_ -> underrun
OpCall ->
case stk of
xGas:xTo':xValue:xInOffset:xInSize:xOutOffset:xOutSize:xs ->
branch (Expr.gt xValue (Lit 0)) $ \gt0 -> do
(if gt0 then notStatic else id) $
forceAddr xTo' "unable to determine a call target" $ \xTo ->
case gasTryFrom xGas of
Left _ -> vmError IllegalOverflow
Right gas ->
delegateCall this gas xTo xTo xValue xInOffset xInSize xOutOffset xOutSize xs $
\callee -> do
let from' = fromMaybe self vm.config.overrideCaller
zoom #state $ do
assign #callvalue xValue
assign #caller from'
assign #contract callee
assign (#config % #overrideCaller) Nothing
touchAccount from'
touchAccount callee
transfer from' callee xValue
_ ->
underrun
OpCallcode ->
case stk of
xGas:xTo':xValue:xInOffset:xInSize:xOutOffset:xOutSize:xs ->
forceAddr xTo' "unable to determine a call target" $ \xTo ->
case gasTryFrom xGas of
Left _ -> vmError IllegalOverflow
Right gas ->
delegateCall this gas xTo self xValue xInOffset xInSize xOutOffset xOutSize xs $ \_ -> do
zoom #state $ do
assign #callvalue xValue
assign #caller $ fromMaybe self vm.config.overrideCaller
assign (#config % #overrideCaller) Nothing
touchAccount self
_ ->
underrun
OpReturn ->
case stk of
xOffset:xSize:_ ->
accessMemoryRange xOffset xSize $ do
output <- readMemory xOffset xSize
let
codesize = fromMaybe (internalError "processing opcode RETURN. Cannot return dynamically sized abstract data")
. maybeLitWord . bufLength $ output
maxsize = vm.block.maxCodeSize
creation = case vm.frames of
[] -> vm.tx.isCreate
frame:_ -> case frame.context of
CreationContext {} -> True
CallContext {} -> False
if creation
then
if codesize > maxsize
then
finishFrame (FrameErrored (MaxCodeSizeExceeded maxsize codesize))
else do
let frameReturned = burn (g_codedeposit * unsafeInto codesize) $
finishFrame (FrameReturned output)
frameErrored = finishFrame $ FrameErrored InvalidFormat
case readByte (Lit 0) output of
LitByte 0xef -> frameErrored
LitByte _ -> frameReturned
y -> branch (Expr.eqByte y (LitByte 0xef)) $ \case
True -> frameErrored
False -> frameReturned
else
finishFrame (FrameReturned output)
_ -> underrun
OpDelegatecall ->
case stk of
xGas:xTo:xInOffset:xInSize:xOutOffset:xOutSize:xs ->
case wordToAddr xTo of
Nothing -> do
loc <- codeloc
let msg = "Unable to determine a call target"
partial $ UnexpectedSymbolicArg (snd loc) msg [SomeExpr xTo]
Just xTo' ->
case gasTryFrom xGas of
Left _ -> vmError IllegalOverflow
Right gas ->
delegateCall this gas xTo' self (Lit 0) xInOffset xInSize xOutOffset xOutSize xs $
\_ -> touchAccount self
_ -> underrun
OpCreate2 -> notStatic $
case stk of
xValue:xOffset:xSize:xSalt':xs ->
forceConcrete xSalt' "CREATE2" $ \(xSalt) ->
accessMemoryRange xOffset xSize $ do
availableGas <- use (#state % #gas)
buf <- readMemory xOffset xSize
forceConcreteBuf buf "CREATE2" $
\initCode -> do
let
(cost, gas') = costOfCreate fees availableGas xSize True
newAddr <- create2Address self xSalt initCode
_ <- accessAccountForGas newAddr
burn' cost $
create self this xSize gas' xValue xs newAddr (ConcreteBuf initCode)
_ -> underrun
OpStaticcall ->
case stk of
xGas:xTo:xInOffset:xInSize:xOutOffset:xOutSize:xs ->
case wordToAddr xTo of
Nothing -> do
loc <- codeloc
let msg = "Unable to determine a call target"
partial $ UnexpectedSymbolicArg (snd loc) msg [SomeExpr xTo]
Just xTo' ->
case gasTryFrom xGas of
Left _ -> vmError IllegalOverflow
Right gas ->
delegateCall this gas xTo' xTo' (Lit 0) xInOffset xInSize xOutOffset xOutSize xs $
\callee -> do
zoom #state $ do
assign #callvalue (Lit 0)
assign #caller $ fromMaybe self (vm.config.overrideCaller)
assign #contract callee
assign #static True
assign (#config % #overrideCaller) Nothing
touchAccount self
touchAccount callee
_ ->
underrun
OpSelfdestruct ->
notStatic $
case stk of
[] -> underrun
(xTo':_) -> forceAddr xTo' "SELFDESTRUCT" $ \case
xTo@(LitAddr _) -> do
acc <- accessAccountForGas xTo
let cost = if acc then 0 else g_cold_account_access
funds = this.balance
recipientExists = accountExists xTo vm
branch (Expr.iszero $ Expr.eq funds (Lit 0)) $ \hasFunds -> do
let c_new = if (not recipientExists) && hasFunds
then g_selfdestruct_newaccount
else 0
burn (g_selfdestruct + c_new + cost) $ do
selfdestruct self
touchAccount xTo
if hasFunds
then fetchAccount xTo $ \_ -> do
#env % #contracts % ix xTo % #balance %= (Expr.add funds)
assign (#env % #contracts % ix self % #balance) (Lit 0)
doStop
else do
doStop
a -> do
pc <- use (#state % #pc)
partial $ UnexpectedSymbolicArg pc "trying to self destruct to a symbolic address" (wrap [a])
OpRevert ->
case stk of
xOffset:xSize:_ ->
accessMemoryRange xOffset xSize $ do
output <- readMemory xOffset xSize
finishFrame (FrameReverted output)
_ -> underrun
OpUnknown xxx ->
vmError $ UnrecognizedOpcode xxx
transfer :: VMOps t => Expr EAddr -> Expr EAddr -> Expr EWord -> EVM t s ()
transfer _ _ (Lit 0) = pure ()
transfer src dst val = do
sb <- preuse $ #env % #contracts % ix src % #balance
db <- preuse $ #env % #contracts % ix dst % #balance
baseState <- use (#config % #baseState)
let mkc = case baseState of
AbstractBase -> unknownContract
EmptyBase -> const emptyContract
case (sb, db) of
-- both sender and recipient in state
(Just srcBal, Just _) ->
branch (Expr.gt val srcBal) $ \case
True -> vmError $ BalanceTooLow val srcBal
False -> do
(#env % #contracts % ix src % #balance) %= (`Expr.sub` val)
(#env % #contracts % ix dst % #balance) %= (`Expr.add` val)
-- sender not in state
(Nothing, Just _) -> do
case src of
LitAddr _ -> do
(#env % #contracts) %= (Map.insert src (mkc src))
transfer src dst val
SymAddr _ -> do
pc <- use (#state % #pc)
partial $ UnexpectedSymbolicArg pc "Attempting to transfer eth from a symbolic address that is not present in the state" (wrap [src])
GVar _ -> internalError "Unexpected GVar"
-- recipient not in state
(_ , Nothing) -> do
case dst of
LitAddr _ -> do
(#env % #contracts) %= (Map.insert dst (mkc dst))
transfer src dst val
SymAddr _ -> do
pc <- use (#state % #pc)
partial $ UnexpectedSymbolicArg pc "Attempting to transfer eth to a symbolic address that is not present in the state" (wrap [dst])
GVar _ -> internalError "Unexpected GVar"
-- | Checks a *CALL for failure; OOG, too many callframes, memory access etc.
callChecks
:: forall (t :: VMType) s. (?op :: Word8, VMOps t)
=> Contract
-> Gas t
-> Expr EAddr
-> Expr EAddr
-> Expr EWord
-> Expr EWord
-> Expr EWord
-> Expr EWord
-> Expr EWord
-> [Expr EWord]
-- continuation with gas available for call
-> (Gas t -> EVM t s ())
-> EVM t s ()
callChecks this xGas xContext xTo xValue xInOffset xInSize xOutOffset xOutSize xs continue = do
vm <- get
let fees = vm.block.schedule
accessMemoryRange xInOffset xInSize $
accessMemoryRange xOutOffset xOutSize $ do
availableGas <- use (#state % #gas)
let recipientExists = accountExists xContext vm
let from = fromMaybe vm.state.contract vm.config.overrideCaller
fromBal <- preuse $ #env % #contracts % ix from % #balance
costOfCall fees recipientExists xValue availableGas xGas xTo $ \cost gas' -> do
let checkCallDepth =
if length vm.frames >= 1024
then do
assign (#state % #stack) (Lit 0 : xs)
assign (#state % #returndata) mempty
pushTrace $ ErrorTrace CallDepthLimitReached
next
else continue (toGas gas')
case (fromBal, xValue) of
-- we're not transferring any value, and can skip the balance check