-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathEVM.hs
2324 lines (2066 loc) · 84.8 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 ImplicitParams #-}
{-# Language UndecidableInstances #-}
{-# Language ScopedTypeVariables #-}
{-# Language GADTs #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
module EVM where
import Prelude hiding (log, exponent, GT, LT)
import Optics.Core
import Optics.State
import Optics.State.Operators
import Optics.Zoom
import Optics.Operators.Unsafe
import EVM.ABI
import EVM.Concrete (createAddress, create2Address)
import EVM.Expr (readStorage, writeStorage, readByte, readWord, writeWord,
writeByte, bufLength, indexWord, litAddr, readBytes, word256At, copySlice)
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.Sign qualified
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)
import Data.Set (insert, member, fromList)
import Data.Sequence (Seq)
import Data.Sequence qualified as Seq
import Data.Text (unpack)
import Data.Text.Encoding (decodeUtf8, encodeUtf8)
import Data.Tree
import Data.Tree.Zipper qualified as Zipper
import Data.Tuple.Curry
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.Word (Word8, Word32, Word64)
import Crypto.Hash (Digest, SHA256, RIPEMD160)
import Crypto.Hash qualified as Crypto
import Crypto.Number.ModArithmetic (expFast)
blankState :: FrameState
blankState = FrameState
{ contract = 0
, codeContract = 0
, code = RuntimeCode (ConcreteRuntimeCode "")
, pc = 0
, stack = mempty
, memory = mempty
, memorySize = 0
, calldata = mempty
, callvalue = Lit 0
, caller = Lit 0
, gas = 0
, returndata = mempty
, static = False
}
-- | An "external" view of a contract's bytecode, appropriate for
-- e.g. @EXTCODEHASH@.
bytecode :: Getter Contract (Expr Buf)
bytecode = #contractcode % to f
where f (InitCode _ _) = mempty
f (RuntimeCode (ConcreteRuntimeCode bs)) = ConcreteBuf bs
f (RuntimeCode (SymbolicRuntimeCode ops)) = Expr.fromList ops
-- * Data accessors
currentContract :: VM -> Maybe Contract
currentContract vm =
Map.lookup vm.state.codeContract vm.env.contracts
-- * Data constructors
makeVm :: VMOpts -> VM
makeVm o =
let txaccessList = o.txAccessList
txorigin = o.origin
txtoAddr = o.address
initialAccessedAddrs = fromList $ [txorigin, txtoAddr, o.coinbase] ++ [1..9] ++ (Map.keys txaccessList)
initialAccessedStorageKeys = fromList $ foldMap (uncurry (map . (,))) (Map.toList txaccessList)
touched = if o.create then [txorigin] else [txorigin, txtoAddr]
in
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
--, _accessList = txaccessList
, isCreate = o.create
, txReversion = Map.fromList
[(o.address , o.contract )]
}
, logs = []
, traces = Zipper.fromForest []
, 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
}
, state = FrameState
{ pc = 0
, stack = mempty
, memory = mempty
, memorySize = 0
, code = o.contract.contractcode
, 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
{ sha3Crack = mempty
, chainId = o.chainId
, storage = o.initialStorage
, origStorage = mempty
, contracts = Map.fromList
[(o.address, o.contract )]
}
, cache = Cache mempty mempty mempty
, burned = 0
, constraints = snd o.calldata
, keccakEqs = mempty
, iterations = mempty
, allowFFI = o.allowFFI
, overrideCaller = Nothing
}
-- | Initialize empty contract with given code
initialContract :: ContractCode -> Contract
initialContract contractCode = Contract
{ contractcode = contractCode
, codehash = hashcode contractCode
, balance = 0
, nonce = if creation then 1 else 0
, opIxMap = mkOpIxMap contractCode
, codeOps = mkCodeOps contractCode
, external = False
} where
creation = case contractCode of
InitCode _ _ -> True
RuntimeCode _ -> False
-- * Opcode dispatch (exec1)
-- | Update program counter
next :: (?op :: Word8) => EVM ()
next = modifying (#state % #pc) (+ (opSize ?op))
-- | Executes the EVM one step
exec1 :: EVM ()
exec1 = do
vm <- get
let
-- Convenient aliases
mem = vm.state.memory
stk = vm.state.stack
self = vm.state.contract
this = fromMaybe (error "internal error: state contract") (Map.lookup self vm.env.contracts)
fees@FeeSchedule {..} = vm.block.schedule
doStop = finishFrame (FrameReturned mempty)
if self > 0x0 && self <= 0x9 then do
-- call to precompile
let ?op = 0x00 -- dummy value
case bufLength vm.state.calldata of
Lit calldatasize -> do
copyBytesToMemory vm.state.calldata (Lit calldatasize) (Lit 0) (Lit 0)
executePrecompile self vm.state.gas 0 calldatasize 0 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
e -> partial $
UnexpectedSymbolicArg vm.state.pc "cannot call precompiles with symbolic data" (wrap [e])
else if vm.state.pc >= opslen vm.state.code
then doStop
else do
let ?op = case vm.state.code of
InitCode conc _ -> BS.index conc vm.state.pc
RuntimeCode (ConcreteRuntimeCode bs) -> BS.index bs vm.state.pc
RuntimeCode (SymbolicRuntimeCode ops) ->
fromMaybe (error "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 = fromIntegral n'
!xs = case vm.state.code of
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 (fromIntegral i - 1)) stk of
Nothing -> underrun
Just y ->
limitStack 1 $
burn g_verylow $ do
next
pushSym y
OpSwap i ->
if length stk < (fromIntegral i) + 1
then underrun
else
burn g_verylow $ do
next
zoom (#state % #stack) $ do
assign (ix 0) (stk ^?! ix (fromIntegral i))
assign (ix (fromIntegral i)) (stk ^?! ix 0)
OpLog n ->
notStatic $
case stk of
(xOffset':xSize':xs) ->
if length xs < (fromIntegral n)
then underrun
else
forceConcrete2 (xOffset', xSize') "LOG" $ \(xOffset, xSize) -> do
let (topics, xs') = splitAt (fromIntegral n) xs
bytes = readMemory xOffset' xSize' vm
logs' = (LogEntry (litAddr self) bytes topics) : vm.logs
burn (g_log + g_logdata * (num xSize) + num n * g_logtopic) $
accessMemoryRange xOffset xSize $ do
traceTopLog logs'
next
assign (#state % #stack) xs'
assign #logs logs'
_ ->
underrun
OpStop -> doStop
OpAdd -> stackOp2 g_verylow (uncurry Expr.add)
OpMul -> stackOp2 g_low (uncurry Expr.mul)
OpSub -> stackOp2 g_verylow (uncurry Expr.sub)
OpDiv -> stackOp2 g_low (uncurry Expr.div)
OpSdiv -> stackOp2 g_low (uncurry Expr.sdiv)
OpMod -> stackOp2 g_low (uncurry Expr.mod)
OpSmod -> stackOp2 g_low (uncurry Expr.smod)
OpAddmod -> stackOp3 g_mid (uncurryN Expr.addmod)
OpMulmod -> stackOp3 g_mid (uncurryN Expr.mulmod)
OpLt -> stackOp2 g_verylow (uncurry Expr.lt)
OpGt -> stackOp2 g_verylow (uncurry Expr.gt)
OpSlt -> stackOp2 g_verylow (uncurry Expr.slt)
OpSgt -> stackOp2 g_verylow (uncurry Expr.sgt)
OpEq -> stackOp2 g_verylow (uncurry Expr.eq)
OpIszero -> stackOp1 g_verylow Expr.iszero
OpAnd -> stackOp2 g_verylow (uncurry Expr.and)
OpOr -> stackOp2 g_verylow (uncurry Expr.or)
OpXor -> stackOp2 g_verylow (uncurry Expr.xor)
OpNot -> stackOp1 g_verylow Expr.not
OpByte -> stackOp2 g_verylow (\(i, w) -> Expr.padByte $ Expr.indexWord i w)
OpShl -> stackOp2 g_verylow (uncurry Expr.shl)
OpShr -> stackOp2 g_verylow (uncurry Expr.shr)
OpSar -> stackOp2 g_verylow (uncurry Expr.sar)
-- more accurately refered to as KECCAK
OpSha3 ->
case stk of
xOffset':xSize':xs ->
forceConcrete xOffset' "sha3 offset must be concrete" $
\xOffset -> forceConcrete xSize' "sha3 size must be concrete" $ \xSize ->
burn (g_sha3 + g_sha3word * ceilDiv (num xSize) 32) $
accessMemoryRange xOffset xSize $ do
(hash, invMap) <- case readMemory xOffset' xSize' vm of
ConcreteBuf bs -> do
let hash' = keccak' bs
eqs <- use #keccakEqs
assign #keccakEqs $
PEq (Lit hash') (Keccak (ConcreteBuf bs)):eqs
pure (Lit hash', Map.singleton hash' bs)
buf -> pure (Keccak buf, mempty)
next
assign (#state % #stack) (hash : xs)
modifying (#env % #sha3Crack) ((<>) invMap)
_ -> underrun
OpAddress ->
limitStack 1 $
burn g_base (next >> push (num self))
OpBalance ->
case stk of
x':xs -> forceConcrete x' "BALANCE" $ \x ->
accessAndBurn (num x) $
fetchAccount (num x) $ \c -> do
next
assign (#state % #stack) xs
push (num c.balance)
[] ->
underrun
OpOrigin ->
limitStack 1 . burn g_base $
next >> push (num vm.tx.origin)
OpCaller ->
limitStack 1 . burn g_base $
next >> pushSym 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 ->
forceConcrete2 (xTo', xSize') "CALLDATACOPY" $
\(xTo, xSize) ->
burn (g_verylow + g_copy * ceilDiv (num xSize) 32) $
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 ->
forceConcrete2 (memOffset', n') "CODECOPY" $
\(memOffset,n) -> do
case toWord64 n of
Nothing -> vmError IllegalOverflow
Just n'' ->
if n'' <= ( (maxBound :: Word64) - g_verylow ) `div` g_copy * 32 then
burn (g_verylow + g_copy * ceilDiv (num n) 32) $
accessMemoryRange memOffset n $ do
next
assign (#state % #stack) xs
copyBytesToMemory (toBuf vm.state.code) n' codeOffset memOffset'
else vmError IllegalOverflow
_ -> underrun
OpGasprice ->
limitStack 1 . burn g_base $
next >> push vm.tx.gasprice
OpExtcodesize ->
case stk of
x':xs -> case x' of
Lit x -> if x == num cheatCode
then do
next
assign (#state % #stack) xs
pushSym (Lit 1)
else
accessAndBurn (num x) $
fetchAccount (num x) $ \c -> do
next
assign (#state % #stack) xs
pushSym (bufLength (view bytecode c))
_ -> do
assign (#state % #stack) xs
pushSym (CodeSize x')
next
[] ->
underrun
OpExtcodecopy ->
case stk of
extAccount':memOffset':codeOffset:codeSize':xs ->
forceConcrete3 (extAccount', memOffset', codeSize') "EXTCODECOPY" $
\(extAccount, memOffset, codeSize) -> do
acc <- accessAccountForGas (num extAccount)
let cost = if acc then g_warm_storage_read else g_cold_account_access
burn (cost + g_copy * ceilDiv (num codeSize) 32) $
accessMemoryRange memOffset codeSize $
fetchAccount (num extAccount) $ \c -> do
next
assign (#state % #stack) xs
copyBytesToMemory (view bytecode c) codeSize' codeOffset memOffset'
_ -> underrun
OpReturndatasize ->
limitStack 1 . burn g_base $
next >> pushSym (bufLength vm.state.returndata)
OpReturndatacopy ->
case stk of
xTo':xFrom:xSize':xs -> forceConcrete2 (xTo', xSize') "RETURNDATACOPY" $
\(xTo, xSize) ->
burn (g_verylow + g_copy * ceilDiv (num xSize) 32) $
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) of
(Lit f, Lit l) ->
jump $ l < f + xSize || f + xSize < f
_ -> do
let oob = Expr.lt (bufLength vm.state.returndata) (Expr.add xFrom xSize')
overflow = Expr.lt (Expr.add xFrom xSize') (xFrom)
loc <- codeloc
branch loc (Expr.or oob overflow) jump
_ -> underrun
OpExtcodehash ->
case stk of
x':xs -> forceConcrete x' "EXTCODEHASH" $ \x ->
accessAndBurn (num x) $ do
next
assign (#state % #stack) xs
fetchAccount (num x) $ \c ->
if accountEmpty c
then push (num (0 :: Int))
else pushSym $ keccak (view bytecode c)
[] ->
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 (num i :: Integer) & show & Char8.pack & keccak' & Lit
i -> BlockHash i
OpCoinbase ->
limitStack 1 . burn g_base $
next >> push (num 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 (num vm.block.gaslimit)
OpChainid ->
limitStack 1 . burn g_base $
next >> push vm.env.chainId
OpSelfbalance ->
limitStack 1 . burn g_low $
next >> push 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 -> forceConcrete x' "MLOAD" $ \x ->
burn g_verylow $
accessMemoryWord x $ do
next
assign (#state % #stack) (readWord (Lit x) mem : xs)
_ -> underrun
OpMstore ->
case stk of
x':y:xs -> forceConcrete x' "MSTORE index" $ \x ->
burn g_verylow $
accessMemoryWord x $ do
next
assign (#state % #memory) (writeWord (Lit x) y mem)
assign (#state % #stack) xs
_ -> underrun
OpMstore8 ->
case stk of
x':y:xs -> forceConcrete x' "MSTORE8" $ \x ->
burn g_verylow $
accessMemoryRange x 1 $ do
let yByte = indexWord (Lit 31) y
next
modifying (#state % #memory) (writeByte (Lit x) yByte)
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
availableGas <- use (#state % #gas)
if num availableGas <= g_callstipend then
finishFrame (FrameErrored (OutOfGas availableGas (num g_callstipend)))
else do
let
original =
case readStorage (litAddr self) x (ConcreteStore vm.env.origStorage) of
Just (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 % #storage) (writeStorage (litAddr self) 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 -> do
case stk of
(x:y:xs) -> forceConcrete x "JUMPI: symbolic jumpdest" $ \x' ->
burn g_high $
let jump :: Bool -> EVM ()
jump False = assign (#state % #stack) xs >> next
jump _ = case toInt x' of
Nothing -> vmError BadJumpDestination
Just i -> checkJump i xs
in do
loc <- codeloc
branch loc y jump
_ -> underrun
OpPc ->
limitStack 1 . burn g_base $
next >> push (num vm.state.pc)
OpMsize ->
limitStack 1 . burn g_base $
next >> push (num vm.state.memorySize)
OpGas ->
limitStack 1 . burn g_base $
next >> push (num (vm.state.gas - g_base))
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 -> forceConcrete exponent' "EXP: symbolic exponent" $ \exponent ->
let cost = if exponent == 0
then g_exp
else g_exp + g_expbyte * num (ceilDiv (1 + log2 exponent) 8)
in burn cost $ do
next
(#state % #stack) .= Expr.exp base exponent' : xs
_ -> underrun
OpSignextend -> stackOp2 g_low (uncurry Expr.sex)
OpCreate ->
notStatic $
case stk of
xValue':xOffset':xSize':xs -> forceConcrete3 (xValue', xOffset', xSize') "CREATE" $
\(xValue, xOffset, xSize) -> do
accessMemoryRange xOffset xSize $ do
availableGas <- use (#state % #gas)
let
newAddr = createAddress self this.nonce
(cost, gas') = costOfCreate fees availableGas xSize False
_ <- accessAccountForGas newAddr
burn cost $ do
let initCode = readMemory xOffset' xSize' vm
create self this xSize (num gas') xValue xs newAddr initCode
_ -> underrun
OpCall ->
case stk of
xGas':xTo:xValue':xInOffset':xInSize':xOutOffset':xOutSize':xs ->
forceConcrete6 (xGas', xValue', xInOffset', xInSize', xOutOffset', xOutSize') "CALL" $
\(xGas, xValue, xInOffset, xInSize, xOutOffset, xOutSize) ->
(if xValue > 0 then notStatic else id) $
delegateCall this (num xGas) xTo xTo xValue xInOffset xInSize xOutOffset xOutSize xs $ \callee -> do
let from' = fromMaybe self vm.overrideCaller
zoom #state $ do
assign #callvalue (Lit xValue)
assign #caller (litAddr from')
assign #contract callee
assign #overrideCaller Nothing
touchAccount from'
touchAccount callee
transfer from' callee xValue
_ ->
underrun
OpCallcode ->
case stk of
xGas':xTo:xValue':xInOffset':xInSize':xOutOffset':xOutSize':xs ->
forceConcrete6 (xGas', xValue', xInOffset', xInSize', xOutOffset', xOutSize') "CALLCODE" $
\(xGas, xValue, xInOffset, xInSize, xOutOffset, xOutSize) ->
delegateCall this (num xGas) xTo (litAddr self) xValue xInOffset xInSize xOutOffset xOutSize xs $ \_ -> do
zoom #state $ do
assign #callvalue (Lit xValue)
assign #caller $ litAddr $ fromMaybe self vm.overrideCaller
assign #overrideCaller Nothing
touchAccount self
_ ->
underrun
OpReturn ->
case stk of
xOffset':xSize':_ -> forceConcrete2 (xOffset', xSize') "RETURN" $ \(xOffset, xSize) ->
accessMemoryRange xOffset xSize $ do
let
output = readMemory xOffset' xSize' vm
codesize = fromMaybe (error "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 * num codesize) $
finishFrame (FrameReturned output)
frameErrored = finishFrame $ FrameErrored InvalidFormat
case readByte (Lit 0) output of
LitByte 0xef -> frameErrored
LitByte _ -> frameReturned
y -> do
loc <- codeloc
branch loc (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 ->
forceConcrete5 (xGas', xInOffset', xInSize', xOutOffset', xOutSize') "DELEGATECALL" $
\(xGas, xInOffset, xInSize, xOutOffset, xOutSize) ->
delegateCall this (num xGas) xTo (litAddr self) 0 xInOffset xInSize xOutOffset xOutSize xs $ \_ -> do
touchAccount self
_ -> underrun
OpCreate2 -> notStatic $
case stk of
xValue':xOffset':xSize':xSalt':xs ->
forceConcrete4 (xValue', xOffset', xSize', xSalt') "CREATE2" $
\(xValue, xOffset, xSize, xSalt) ->
accessMemoryRange xOffset xSize $ do
availableGas <- use (#state % #gas)
forceConcreteBuf (readMemory xOffset' xSize' vm) "CREATE2" $
\initCode -> do
let
newAddr = create2Address self xSalt initCode
(cost, gas') = costOfCreate fees availableGas xSize True
_ <- 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 ->
forceConcrete5 (xGas', xInOffset', xInSize', xOutOffset', xOutSize') "STATICCALL" $
\(xGas, xInOffset, xInSize, xOutOffset, xOutSize) -> do
delegateCall this (num xGas) xTo xTo 0 xInOffset xInSize xOutOffset xOutSize xs $ \callee -> do
zoom #state $ do
assign #callvalue (Lit 0)
assign #caller $ litAddr $ fromMaybe self (vm.overrideCaller)
assign #contract callee
assign #static True
assign #overrideCaller Nothing
touchAccount self
touchAccount callee
_ ->
underrun
OpSelfdestruct ->
notStatic $
case stk of
[] -> underrun
(xTo':_) -> forceConcrete xTo' "SELFDESTRUCT" $ \(num -> xTo) -> do
acc <- accessAccountForGas (num xTo)
let cost = if acc then 0 else g_cold_account_access
funds = this.balance
recipientExists = accountExists xTo vm
c_new = if not recipientExists && funds /= 0
then g_selfdestruct_newaccount
else 0
burn (g_selfdestruct + c_new + cost) $ do
selfdestruct self
touchAccount xTo
if funds /= 0
then fetchAccount xTo $ \_ -> do
#env % #contracts % ix xTo % #balance %= (+ funds)
assign (#env % #contracts % ix self % #balance) 0
doStop
else doStop
OpRevert ->
case stk of
xOffset':xSize':_ -> forceConcrete2 (xOffset', xSize') "REVERT" $ \(xOffset, xSize) ->
accessMemoryRange xOffset xSize $ do
let output = readMemory xOffset' xSize' vm
finishFrame (FrameReverted output)
_ -> underrun
OpUnknown xxx ->
vmError $ UnrecognizedOpcode xxx
transfer :: Addr -> Addr -> W256 -> EVM ()
transfer _ _ 0 = pure ()
transfer xFrom xTo xValue = do
sb <- preuse $ #env % #contracts % ix xFrom % #balance
case sb of
Just srcBal ->
if xValue > srcBal
then vmError $ BalanceTooLow xValue srcBal
else do
(#env % #contracts % ix xFrom % #balance) %= (subtract xValue)
(#env % #contracts % ix xTo % #balance) %= (+ xValue)
Nothing -> vmError $ BalanceTooLow xValue 0
-- | Checks a *CALL for failure; OOG, too many callframes, memory access etc.
callChecks
:: (?op :: Word8)
=> Contract -> Word64 -> Addr -> Addr -> W256 -> W256 -> W256 -> W256 -> W256 -> [Expr EWord]
-- continuation with gas available for call
-> (Word64 -> EVM ())
-> EVM ()
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
(cost, gas') <- costOfCall fees recipientExists xValue availableGas xGas xTo
burn (cost - gas') $ do
if xValue > num this.balance
then do
assign (#state % #stack) (Lit 0 : xs)
assign (#state % #returndata) mempty
pushTrace $ ErrorTrace (BalanceTooLow xValue this.balance)
next
else if length vm.frames >= 1024
then do
assign (#state % #stack) (Lit 0 : xs)
assign (#state % #returndata) mempty
pushTrace $ ErrorTrace CallDepthLimitReached
next
else continue gas'
precompiledContract
:: (?op :: Word8)
=> Contract
-> Word64
-> Addr
-> Addr
-> W256
-> W256 -> W256 -> W256 -> W256
-> [Expr EWord]
-> EVM ()
precompiledContract this xGas precompileAddr recipient xValue inOffset inSize outOffset outSize xs =
callChecks this xGas recipient precompileAddr xValue inOffset inSize outOffset outSize xs $ \gas' ->
do
executePrecompile precompileAddr gas' inOffset inSize outOffset outSize xs
self <- use (#state % #contract)
stk <- use (#state % #stack)
pc' <- use (#state % #pc)
result' <- use #result
case result' of
Nothing -> case stk of
x:_ -> case maybeLitWord x of
Just 0 ->
pure ()
Just 1 ->
fetchAccount recipient $ \_ -> do
transfer self recipient xValue
touchAccount self
touchAccount recipient
_ -> partial $ UnexpectedSymbolicArg pc' "unexpected return value from precompile" (wrap [x])
_ -> underrun
_ -> pure ()
executePrecompile
:: (?op :: Word8)
=> Addr
-> Word64 -> W256 -> W256 -> W256 -> W256 -> [Expr EWord]
-> EVM ()
executePrecompile preCompileAddr gasCap inOffset inSize outOffset outSize xs = do
vm <- get
let input = readMemory (Lit inOffset) (Lit inSize) vm
fees = vm.block.schedule
cost = costOfPrecompile fees preCompileAddr input
notImplemented = error $ "precompile at address " <> show preCompileAddr <> " not yet implemented"
precompileFail = burn (gasCap - cost) $ do
assign (#state % #stack) (Lit 0 : xs)
pushTrace $ ErrorTrace PrecompileFailure
next
if cost > gasCap then
burn gasCap $ do
assign (#state % #stack) (Lit 0 : xs)
next
else burn cost $
case preCompileAddr of
-- ECRECOVER
0x1 ->
-- TODO: support symbolic variant
forceConcreteBuf input "ECRECOVER" $ \input' -> do
case EVM.Precompiled.execute 0x1 (truncpadlit 128 input') 32 of
Nothing -> do
-- return no output for invalid signature
assign (#state % #stack) (Lit 1 : xs)
assign (#state % #returndata) mempty
next
Just output -> do
assign (#state % #stack) (Lit 1 : xs)
assign (#state % #returndata) (ConcreteBuf output)
copyBytesToMemory (ConcreteBuf output) (Lit outSize) (Lit 0) (Lit outOffset)
next
-- SHA2-256
0x2 ->
forceConcreteBuf input "SHA2-256" $ \input' -> do
let
hash = sha256Buf input'
sha256Buf x = ConcreteBuf $ BA.convert (Crypto.hash x :: Digest SHA256)
assign (#state % #stack) (Lit 1 : xs)
assign (#state % #returndata) hash
copyBytesToMemory hash (Lit outSize) (Lit 0) (Lit outOffset)
next
-- RIPEMD-160
0x3 ->
-- TODO: support symbolic variant
forceConcreteBuf input "RIPEMD160" $ \input' -> do
let
padding = BS.pack $ replicate 12 0
hash' = BA.convert (Crypto.hash input' :: Digest RIPEMD160)
hash = ConcreteBuf $ padding <> hash'
assign (#state % #stack) (Lit 1 : xs)
assign (#state % #returndata) hash
copyBytesToMemory hash (Lit outSize) (Lit 0) (Lit outOffset)
next
-- IDENTITY
0x4 -> do
assign (#state % #stack) (Lit 1 : xs)
assign (#state % #returndata) input
copyCallBytesToMemory input (Lit outSize) (Lit 0) (Lit outOffset)
next
-- MODEXP