-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathEVM.hs
2763 lines (2449 loc) · 99.3 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 DataKinds #-}
{-# Language GADTs #-}
{-# Language TemplateHaskell #-}
module EVM where
import Prelude hiding (log, exponent, GT, LT)
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 hiding (IllegalOverflow, Error)
import EVM.Sign qualified
import Control.Lens hiding (op, (:<), (|>), (.>))
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 (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.Vector qualified as RegularVector
import Data.Vector qualified as V
import Data.Vector.Storable (Vector)
import Data.Vector.Storable qualified as Vector
import Data.Vector.Storable.Mutable qualified as Vector
import Data.Word (Word8, Word32, Word64)
import Options.Generic as Options
import Crypto.Hash (Digest, SHA256, RIPEMD160)
import Crypto.Hash qualified as Crypto
import Crypto.Number.ModArithmetic (expFast)
import Crypto.PubKey.ECC.ECDSA (signDigestWith, PrivateKey(..), Signature(..))
-- * Data types
-- | EVM failure modes
data Error
= BalanceTooLow W256 W256
| UnrecognizedOpcode Word8
| SelfDestruction
| StackUnderrun
| BadJumpDestination
| Revert (Expr Buf)
| OutOfGas Word64 Word64
| BadCheatCode (Maybe Word32)
| StackLimitExceeded
| IllegalOverflow
| Query Query
| Choose Choose
| StateChangeWhileStatic
| InvalidMemoryAccess
| CallDepthLimitReached
| MaxCodeSizeExceeded W256 W256
| InvalidFormat
| PrecompileFailure
| forall a . UnexpectedSymbolicArg Int String [Expr a]
| DeadPath
| NotUnique (Expr EWord)
| SMTTimeout
| FFI [AbiValue]
| ReturnDataOutOfBounds
| NonceOverflow
deriving instance Show Error
-- | The possible result states of a VM
data VMResult
= VMFailure Error -- ^ An operation failed
| VMSuccess (Expr Buf) -- ^ Reached STOP, RETURN, or end-of-code
deriving instance Show VMResult
-- | The state of a stepwise EVM execution
data VM = VM
{ _result :: Maybe VMResult
, _state :: FrameState
, _frames :: [Frame]
, _env :: Env
, _block :: Block
, _tx :: TxState
, _logs :: [Expr Log]
, _traces :: Zipper.TreePos Zipper.Empty Trace
, _cache :: Cache
, _burned :: {-# UNPACK #-} !Word64
, _iterations :: Map CodeLocation Int
, _constraints :: [Prop]
, _keccakEqs :: [Prop]
, _allowFFI :: Bool
, _overrideCaller :: Maybe (Expr EWord)
}
deriving (Show)
data Trace = Trace
{ _traceOpIx :: Int
, _traceContract :: Contract
, _traceData :: TraceData
}
deriving (Show)
data TraceData
= EventTrace (Expr EWord) (Expr Buf) [Expr EWord]
| FrameTrace FrameContext
| QueryTrace Query
| ErrorTrace Error
| EntryTrace Text
| ReturnTrace (Expr Buf) FrameContext
deriving (Show)
-- | Queries halt execution until resolved through RPC calls or SMT queries
data Query where
PleaseFetchContract :: Addr -> (Contract -> EVM ()) -> Query
--PleaseMakeUnique :: SBV a -> [SBool] -> (IsUnique a -> EVM ()) -> Query
PleaseFetchSlot :: Addr -> W256 -> (W256 -> EVM ()) -> Query
PleaseAskSMT :: Expr EWord -> [Prop] -> (BranchCondition -> EVM ()) -> Query
PleaseDoFFI :: [String] -> (ByteString -> EVM ()) -> Query
data Choose where
PleaseChoosePath :: Expr EWord -> (Bool -> EVM ()) -> Choose
instance Show Query where
showsPrec _ = \case
PleaseFetchContract addr _ ->
(("<EVM.Query: fetch contract " ++ show addr ++ ">") ++)
PleaseFetchSlot addr slot _ ->
(("<EVM.Query: fetch slot "
++ show slot ++ " for "
++ show addr ++ ">") ++)
PleaseAskSMT condition constraints _ ->
(("<EVM.Query: ask SMT about "
++ show condition ++ " in context "
++ show constraints ++ ">") ++)
-- PleaseMakeUnique val constraints _ ->
-- (("<EVM.Query: make value "
-- ++ show val ++ " unique in context "
-- ++ show constraints ++ ">") ++)
PleaseDoFFI cmd _ ->
(("<EVM.Query: do ffi: " ++ (show cmd)) ++)
instance Show Choose where
showsPrec _ = \case
PleaseChoosePath _ _ ->
(("<EVM.Choice: waiting for user to select path (0,1)") ++)
-- | Alias for the type of e.g. @exec1@.
type EVM a = State VM a
type CodeLocation = (Addr, Int)
-- | The possible return values of a SMT query
data BranchCondition = Case Bool | Unknown | Inconsistent
deriving Show
-- | The possible return values of a `is unique` SMT query
data IsUnique a = Unique a | Multiple | InconsistentU | TimeoutU
deriving Show
-- | The cache is data that can be persisted for efficiency:
-- any expensive query that is constant at least within a block.
data Cache = Cache
{ _fetchedContracts :: Map Addr Contract,
_fetchedStorage :: Map W256 (Map W256 W256),
_path :: Map (CodeLocation, Int) Bool
} deriving Show
data StorageBase = Concrete | Symbolic
deriving (Show, Eq)
-- | A way to specify an initial VM state
data VMOpts = VMOpts
{ vmoptContract :: Contract
, vmoptCalldata :: (Expr Buf, [Prop])
, vmoptStorageBase :: StorageBase
, vmoptValue :: Expr EWord
, vmoptPriorityFee :: W256
, vmoptAddress :: Addr
, vmoptCaller :: Expr EWord
, vmoptOrigin :: Addr
, vmoptGas :: Word64
, vmoptGaslimit :: Word64
, vmoptNumber :: W256
, vmoptTimestamp :: Expr EWord
, vmoptCoinbase :: Addr
, vmoptPrevRandao :: W256
, vmoptMaxCodeSize :: W256
, vmoptBlockGaslimit :: Word64
, vmoptGasprice :: W256
, vmoptBaseFee :: W256
, vmoptSchedule :: FeeSchedule Word64
, vmoptChainId :: W256
, vmoptCreate :: Bool
, vmoptTxAccessList :: Map Addr [W256]
, vmoptAllowFFI :: Bool
} deriving Show
-- | An entry in the VM's "call/create stack"
data Frame = Frame
{ _frameContext :: FrameContext
, _frameState :: FrameState
}
deriving (Show)
-- | Call/create info
data FrameContext
= CreationContext
{ creationContextAddress :: Addr
, creationContextCodehash :: Expr EWord
, creationContextReversion :: Map Addr Contract
, creationContextSubstate :: SubState
}
| CallContext
{ callContextTarget :: Addr
, callContextContext :: Addr
, callContextOffset :: W256
, callContextSize :: W256
, callContextCodehash :: Expr EWord
, callContextAbi :: Maybe W256
, callContextData :: Expr Buf
, callContextReversion :: (Map Addr Contract, Expr Storage)
, callContextSubState :: SubState
}
deriving (Show)
-- | The "registers" of the VM along with memory and data stack
data FrameState = FrameState
{ _contract :: Addr
, _codeContract :: Addr
, _code :: ContractCode
, _pc :: {-# UNPACK #-} !Int
, _stack :: [Expr EWord]
, _memory :: Expr Buf
, _memorySize :: Word64
, _calldata :: Expr Buf
, _callvalue :: Expr EWord
, _caller :: Expr EWord
, _gas :: {-# UNPACK #-} !Word64
, _returndata :: Expr Buf
, _static :: Bool
}
deriving (Show)
-- | The state that spans a whole transaction
data TxState = TxState
{ _gasprice :: W256
, _txgaslimit :: Word64
, _txPriorityFee :: W256
, _origin :: Addr
, _toAddr :: Addr
, _value :: Expr EWord
, _substate :: SubState
, _isCreate :: Bool
, _txReversion :: Map Addr Contract
}
deriving (Show)
-- | The "accrued substate" across a transaction
data SubState = SubState
{ _selfdestructs :: [Addr]
, _touchedAccounts :: [Addr]
, _accessedAddresses :: Set Addr
, _accessedStorageKeys :: Set (Addr, W256)
, _refunds :: [(Addr, Word64)]
-- in principle we should include logs here, but do not for now
}
deriving (Show)
{- |
A contract is either in creation (running its "constructor") or
post-creation, and code in these two modes is treated differently
by instructions like @EXTCODEHASH@, so we distinguish these two
code types.
The definition follows the structure of code output by solc. We need to use
some heuristics here to deal with symbolic data regions that may be present
in the bytecode since the fully abstract case is impractical:
- initcode has concrete code, followed by an abstract data "section"
- runtimecode has a fixed length, but may contain fixed size symbolic regions (due to immutable)
hopefully we do not have to deal with dynamic immutable before we get a real data section...
-}
data ContractCode
= InitCode ByteString (Expr Buf) -- ^ "Constructor" code, during contract creation
| RuntimeCode RuntimeCode -- ^ "Instance" code, after contract creation
deriving (Show)
-- | We have two variants here to optimize the fully concrete case.
-- ConcreteRuntimeCode just wraps a ByteString
-- SymbolicRuntimeCode is a fixed length vector of potentially symbolic bytes, which lets us handle symbolic pushdata (e.g. from immutable variables in solidity).
data RuntimeCode
= ConcreteRuntimeCode ByteString
| SymbolicRuntimeCode (V.Vector (Expr Byte))
deriving (Show, Eq, Ord)
-- runtime err when used for symbolic code
instance Eq ContractCode where
(InitCode a b) == (InitCode c d) = a == c && b == d
(RuntimeCode x) == (RuntimeCode y) = x == y
_ == _ = False
deriving instance Ord ContractCode
-- | A contract can either have concrete or symbolic storage
-- depending on what type of execution we are doing
-- data Storage
-- = Concrete (Map Word Expr EWord)
-- | Symbolic [(Expr EWord, Expr EWord)] (SArray (WordN 256) (WordN 256))
-- deriving (Show)
-- to allow for Eq Contract (which useful for debugging vmtests)
-- we mock an instance of Eq for symbolic storage.
-- It should not (cannot) be used though.
-- instance Eq Storage where
-- (==) (Concrete a) (Concrete b) = fmap forceLit a == fmap forceLit b
-- (==) (Symbolic _ _) (Concrete _) = False
-- (==) (Concrete _) (Symbolic _ _) = False
-- (==) _ _ = error "do not compare two symbolic arrays like this!"
-- | The state of a contract
data Contract = Contract
{ _contractcode :: ContractCode
, _balance :: W256
, _nonce :: W256
, _codehash :: Expr EWord
, _opIxMap :: Vector Int
, _codeOps :: RegularVector.Vector (Int, Op)
, _external :: Bool
}
deriving instance Show Contract
-- | When doing symbolic execution, we have three different
-- ways to model the storage of contracts. This determines
-- not only the initial contract storage model but also how
-- RPC or state fetched contracts will be modeled.
data StorageModel
= ConcreteS -- ^ Uses `Concrete` Storage. Reading / Writing from abstract
-- locations causes a runtime failure. Can be nicely combined with RPC.
| SymbolicS -- ^ Uses `Symbolic` Storage. Reading / Writing never reaches RPC,
-- but always done using an SMT array with no default value.
| InitialS -- ^ Uses `Symbolic` Storage. Reading / Writing never reaches RPC,
-- but always done using an SMT array with 0 as the default value.
deriving (Read, Show)
instance ParseField StorageModel
-- | Various environmental data
data Env = Env
{ _contracts :: Map Addr Contract
, _chainId :: W256
, _storage :: Expr Storage
, _origStorage :: Map W256 (Map W256 W256)
, _sha3Crack :: Map W256 ByteString
--, _keccakUsed :: [([SWord 8], SWord 256)]
}
deriving (Show)
-- | Data about the block
data Block = Block
{ _coinbase :: Addr
, _timestamp :: Expr EWord
, _number :: W256
, _prevRandao :: W256
, _gaslimit :: Word64
, _baseFee :: W256
, _maxCodeSize :: W256
, _schedule :: FeeSchedule Word64
} deriving (Show, Generic)
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
}
makeLenses ''FrameState
makeLenses ''Frame
makeLenses ''Block
makeLenses ''TxState
makeLenses ''SubState
makeLenses ''Contract
makeLenses ''Env
makeLenses ''Cache
makeLenses ''Trace
makeLenses ''VM
-- | 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
instance Semigroup Cache where
a <> b = Cache
{ _fetchedContracts = Map.unionWith unifyCachedContract a._fetchedContracts b._fetchedContracts
, _fetchedStorage = Map.unionWith unifyCachedStorage a._fetchedStorage b._fetchedStorage
, _path = mappend a._path b._path
}
unifyCachedStorage :: Map W256 W256 -> Map W256 W256 -> Map W256 W256
unifyCachedStorage _ _ = undefined
-- only intended for use in Cache merges, where we expect
-- everything to be Concrete
unifyCachedContract :: Contract -> Contract -> Contract
unifyCachedContract _ _ = undefined
{-
unifyCachedContract a b = a & set storage merged
where merged = case (view storage a, view storage b) of
(ConcreteStore sa, ConcreteStore sb) ->
ConcreteStore (mappend sa sb)
_ ->
view storage a
-}
instance Monoid Cache where
mempty = Cache { _fetchedContracts = mempty,
_fetchedStorage = mempty,
_path = mempty
}
-- * 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.vmoptTxAccessList
txorigin = o.vmoptOrigin
txtoAddr = o.vmoptAddress
initialAccessedAddrs = fromList $ [txorigin, txtoAddr] ++ [1..9] ++ (Map.keys txaccessList)
initialAccessedStorageKeys = fromList $ foldMap (uncurry (map . (,))) (Map.toList txaccessList)
touched = if o.vmoptCreate then [txorigin] else [txorigin, txtoAddr]
in
VM
{ _result = Nothing
, _frames = mempty
, _tx = TxState
{ _gasprice = o.vmoptGasprice
, _txgaslimit = o.vmoptGaslimit
, _txPriorityFee = o.vmoptPriorityFee
, _origin = txorigin
, _toAddr = txtoAddr
, _value = o.vmoptValue
, _substate = SubState mempty touched initialAccessedAddrs initialAccessedStorageKeys mempty
--, _accessList = txaccessList
, _isCreate = o.vmoptCreate
, _txReversion = Map.fromList
[(o.vmoptAddress , o.vmoptContract )]
}
, _logs = []
, _traces = Zipper.fromForest []
, _block = Block
{ _coinbase = o.vmoptCoinbase
, _timestamp = o.vmoptTimestamp
, _number = o.vmoptNumber
, _prevRandao = o.vmoptPrevRandao
, _maxCodeSize = o.vmoptMaxCodeSize
, _gaslimit = o.vmoptBlockGaslimit
, _baseFee = o.vmoptBaseFee
, _schedule = o.vmoptSchedule
}
, _state = FrameState
{ _pc = 0
, _stack = mempty
, _memory = mempty
, _memorySize = 0
, _code = o.vmoptContract._contractcode
, _contract = o.vmoptAddress
, _codeContract = o.vmoptAddress
, _calldata = fst o.vmoptCalldata
, _callvalue = o.vmoptValue
, _caller = o.vmoptCaller
, _gas = o.vmoptGas
, _returndata = mempty
, _static = False
}
, _env = Env
{ _sha3Crack = mempty
, _chainId = o.vmoptChainId
, _storage = if o.vmoptStorageBase == Concrete then EmptyStore else AbstractStore
, _origStorage = mempty
, _contracts = Map.fromList
[(o.vmoptAddress, o.vmoptContract )]
--, _keccakUsed = mempty
--, _storageModel = vmoptStorageModel o
}
, _cache = Cache mempty mempty mempty
, _burned = 0
, _constraints = snd o.vmoptCalldata
, _keccakEqs = mempty
, _iterations = mempty
, _allowFFI = o.vmoptAllowFFI
, _overrideCaller = Nothing
}
-- | Initialize empty contract with given code
initialContract :: ContractCode -> Contract
initialContract theContractCode = Contract
{ _contractcode = theContractCode
, _codehash = hashcode theContractCode
, _balance = 0
, _nonce = if creation then 1 else 0
, _opIxMap = mkOpIxMap theContractCode
, _codeOps = mkCodeOps theContractCode
, _external = False
} where
creation = case theContractCode 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 (num -> x' :: Integer) -> case x' of
0 -> do
fetchAccount self $ \_ -> do
touchAccount self
vmError PrecompileFailure
_ -> fetchAccount self $ \_ -> do
touchAccount self
out <- use (state . returndata)
finishFrame (FrameReturned out)
e -> vmError $
UnexpectedSymbolicArg vmx._state._pc "precompile returned a symbolic value" [e]
_ ->
underrun
e -> vmError $ UnexpectedSymbolicArg vm._state._pc "cannot call precompiles with symbolic data" [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") $
unlitByte $ ops V.! vm._state._pc
case getOp(?op) of
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)
(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 EVM.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
let 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 new' == 0
then refund (g_sreset + g_access_list_storage_key)