/
evm.py
2497 lines (2078 loc) · 94.8 KB
/
evm.py
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
''' Symbolic EVM implementation based on the yellow paper: http://gavwood.com/paper.pdf '''
import binascii
import random
import io
import copy
import inspect
from functools import wraps
from typing import List, Set, Tuple, Union
from ..exceptions import EthereumError
from ..utils.helpers import issymbolic, get_taints, taint_with, istainted
from ..platforms.platform import *
from ..core.smtlib import solver, BitVec, Array, ArrayProxy, Operators, Constant, ArrayVariable, ArrayStore, BitVecConstant, translate_to_smtlib, to_constant, simplify
from ..core.state import Concretize, TerminateState
from ..utils.event import Eventful
from ..exceptions import EthereumError
import pyevmasm as EVMAsm
import logging
from collections import namedtuple
import sha3
import rlp
logger = logging.getLogger(__name__)
#fixme make it global using this https://docs.python.org/3/library/configparser.html
#and save it at the workspace so results are reproducible
config = namedtuple("config", "out_of_gas")
config.out_of_gas = None # 0: default not enough gas, 1 default to always enough gas, 2: for on both
# Auxiliary constants and functions
TT256 = 2 ** 256
TT256M1 = 2 ** 256 - 1
MASK160 = 2 ** 160 - 1
TT255 = 2 ** 255
TOOHIGHMEM = 0x1000
DEFAULT_FORK = 'byzantium'
#FIXME. We should just use a Transaction() for this
PendingTransaction = namedtuple("PendingTransaction", ['type', 'address', 'price', 'data', 'caller', 'value', 'gas'])
EVMLog = namedtuple("EVMLog", ['address', 'memlog', 'topics'])
def ceil32(x):
size = 256
if isinstance(x, BitVec):
size = x.size
return Operators.ITEBV(size, Operators.UREM(x, 32) == 0, x, x + 32 - Operators.UREM(x, 32))
def to_signed(i):
return Operators.ITEBV(256, i < TT255, i, i - TT256)
class Transaction:
__slots__ = '_sort', 'address', 'price', 'data', 'caller', 'value', 'depth', '_return_data', '_result', 'gas'
def __init__(self, sort, address, price, data, caller, value, gas=0, depth=None, result=None, return_data=None):
self.sort = sort
self.address = address
self.price = price
self.data = data
self.caller = caller
self.value = value
self.depth = depth
self.gas = gas
self.set_result(result, return_data)
def concretize(self, state):
conc_caller = state.solve_one(self.caller)
conc_address = state.solve_one(self.address)
conc_value = state.solve_one(self.value)
conc_gas = state.solve_one(self.gas)
conc_data = state.solve_one(self.data)
conc_return_data = state.solve_one(self.return_data)
return Transaction(self.sort, conc_address, self.price, conc_data, conc_caller, conc_value, conc_gas,
depth=self.depth, result=self.result, return_data=bytearray(conc_return_data))
def to_dict(self, mevm):
"""
Only meant to be used with concrete Transaction objects! (after calling .concretize())
"""
return dict(type=self.sort,
from_address=self.caller,
from_name=mevm.account_name(self.caller),
to_address=self.address,
to_name=mevm.account_name(self.address),
value=self.value,
gas=self.gas,
data=binascii.hexlify(self.data).decode())
def dump(self, stream, state, mevm, conc_tx=None):
"""
Concretize and write a human readable version of the transaction into the stream. Used during testcase
generation.
:param stream: Output stream to write to. Typically a file.
:param manticore.ethereum.State state: state that the tx exists in
:param manticore.ethereum.ManticoreEVM mevm: manticore instance
:return:
"""
from ..ethereum import ABI # circular imports
from ..ethereum.manticore import flagged
is_something_symbolic = False
if conc_tx is None:
conc_tx = self.concretize(state)
# The result if any RETURN or REVERT
stream.write("Type: %s (%d)\n" % (self.sort, self.depth))
caller_solution = conc_tx.caller
caller_name = mevm.account_name(caller_solution)
stream.write("From: %s(0x%x) %s\n" % (caller_name, caller_solution, flagged(issymbolic(self.caller))))
address_solution = conc_tx.address
address_name = mevm.account_name(address_solution)
stream.write("To: %s(0x%x) %s\n" % (address_name, address_solution, flagged(issymbolic(self.address))))
stream.write("Value: %d %s\n" % (conc_tx.value, flagged(issymbolic(self.value))))
stream.write("Gas used: %d %s\n" % (conc_tx.gas, flagged(issymbolic(self.gas))))
tx_data = conc_tx.data
stream.write("Data: 0x{} {}\n".format(binascii.hexlify(tx_data).decode(), flagged(issymbolic(self.data))))
if self.return_data is not None:
return_data = conc_tx.return_data
stream.write("Return_data: 0x{} {}\n".format(binascii.hexlify(return_data).decode(), flagged(issymbolic(self.return_data))))
metadata = mevm.get_metadata(self.address)
if self.sort == 'CREATE':
if metadata is not None:
conc_args_data = conc_tx.data[len(metadata._init_bytecode):]
arguments = ABI.deserialize(metadata.get_constructor_arguments(), conc_args_data)
# TODO confirm: arguments should all be concrete?
is_argument_symbolic = any(map(issymbolic, arguments)) # is this redundant since arguments are all concrete?
stream.write('Function call:\n')
stream.write("Constructor(")
stream.write(','.join(map(repr, map(state.solve_one, arguments)))) # is this redundant since arguments are all concrete?
stream.write(') -> %s %s\n' % (self.result, flagged(is_argument_symbolic)))
if self.sort == 'CALL':
if metadata is not None:
calldata = conc_tx.data
is_calldata_symbolic = issymbolic(self.data)
function_id = calldata[:4] # hope there is enough data
signature = metadata.get_func_signature(function_id)
function_name = metadata.get_func_name(function_id)
if signature:
_, arguments = ABI.deserialize(signature, calldata)
else:
arguments = (calldata,)
return_data = None
if self.result == 'RETURN':
ret_types = metadata.get_func_return_types(function_id)
return_data = conc_tx.return_data
return_values = ABI.deserialize(ret_types, return_data) # function return
is_return_symbolic = issymbolic(self.return_data)
stream.write('\n')
stream.write("Function call:\n")
stream.write("%s(" % function_name)
stream.write(','.join(map(repr, arguments)))
stream.write(') -> %s %s\n' % (self.result, flagged(is_calldata_symbolic)))
if return_data is not None:
if len(return_values) == 1:
return_values = return_values[0]
stream.write('return: %r %s\n' % (return_values, flagged(is_return_symbolic)))
is_something_symbolic = is_calldata_symbolic or is_return_symbolic
stream.write('\n\n')
return is_something_symbolic
@property
def sort(self):
return self._sort
@sort.setter
def sort(self, sort):
if sort not in {'CREATE', 'CALL', 'DELEGATECALL'}:
raise EVMException('Invalid transaction type')
self._sort = sort
@property
def result(self):
return self._result
def is_human(self):
return self.depth == 0
@property
def return_data(self):
return self._return_data
@property
def return_value(self):
if self.result in {'RETURN', 'STOP', 'SELFDESTRUCT'}:
return 1
else:
assert self.result in {'TXERROR', 'REVERT', 'THROW'}
return 0
def set_result(self, result, return_data=None):
if getattr(self, 'result', None) is not None:
raise EVMException('Transaction result already set')
if result not in {None, 'TXERROR', 'REVERT', 'RETURN', 'THROW', 'STOP', 'SELFDESTRUCT'}:
raise EVMException('Invalid transaction result')
if result in {'RETURN', 'REVERT'}:
if not isinstance(return_data, (bytes, bytearray, Array)):
raise EVMException('Invalid transaction return_data type:', type(return_data).__name__)
elif result in {'STOP', 'THROW', 'SELFDESTRUCT'}:
if return_data is None:
return_data = bytearray()
if not isinstance(return_data, (bytes, bytearray, Array)) or len(return_data) != 0:
raise EVMException(f'Invalid transaction return_data. Too much data ({len(return_data)}) for STOP, THROW or SELFDESTRUCT')
else:
if return_data is not None:
raise EVMException('Invalid transaction return_data')
self._result = result
self._return_data = return_data
def __reduce__(self):
''' Implements serialization/pickle '''
return (self.__class__, (self.sort, self.address, self.price, self.data, self.caller, self.value, self.gas, self.depth, self.result, self.return_data))
def __str__(self):
return 'Transaction({:s}, from=0x{:x}, to=0x{:x}, value={!r}, depth={:d}, data={!r}, result={!r}..)'.format(self.sort, self.caller, self.address, self.value, self.depth, self.data, self.result)
# Exceptions...
class EVMException(Exception):
pass
class ConcretizeStack(EVMException):
'''
Raised when a symbolic memory cell needs to be concretized.
'''
def __init__(self, pos, expression=None, policy='MINMAX'):
self.message = "Concretizing evm stack item {}".format(pos)
self.pos = pos
self.expression = expression
self.policy = policy
class StartTx(EVMException):
''' A new transaction is started '''
pass
class EndTx(EVMException):
''' The current transaction ends'''
def __init__(self, result, data=None):
if result not in {None, 'TXERROR', 'REVERT', 'RETURN', 'THROW', 'STOP', 'SELFDESTRUCT'}:
raise EVMException('Invalid end transaction result')
if result is None and data is not None:
raise EVMException('Invalid end transaction result')
if not isinstance(data, (type(None), Array, bytes)):
raise EVMException('Invalid end transaction data type')
self.result = result
self.data = data
def is_rollback(self):
if self.result in {'STOP', 'RETURN', 'SELFDESTRUCT'}:
return False
else:
assert self.result in {'THROW', 'TXERROR', 'REVERT'}
return True
def __str__(self):
return f'EndTX<{self.result}>'
class InvalidOpcode(EndTx):
''' Trying to execute invalid opcode '''
def __init__(self):
super().__init__('THROW')
class StackOverflow(EndTx):
''' Attempted to push more than 1024 items '''
def __init__(self):
super().__init__('THROW')
class StackUnderflow(EndTx):
''' Attempted to pop from an empty stack '''
def __init__(self):
super().__init__('THROW')
class NotEnoughGas(EndTx):
''' Not enough gas for operation '''
def __init__(self):
super().__init__('THROW')
class Stop(EndTx):
''' Program reached a STOP instruction '''
def __init__(self):
super().__init__('STOP')
class Return(EndTx):
''' Program reached a RETURN instruction '''
def __init__(self, data=bytearray()):
super().__init__('RETURN', data)
class Revert(EndTx):
''' Program reached a REVERT instruction '''
def __init__(self, data):
super().__init__('REVERT', data)
class SelfDestruct(EndTx):
''' Program reached a SELFDESTRUCT instruction '''
def __init__(self):
super().__init__('SELFDESTRUCT')
class TXError(EndTx):
''' A failed Transaction '''
def __init__(self):
super().__init__('TXERROR')
def concretized_args(**policies):
"""
Make sure an EVM instruction has all of its arguments concretized according to
provided policies.
Example decoration:
@concretized_args(size='ONE', address='')
def LOG(self, address, size, *topics):
...
The above will make sure that the |size| parameter to LOG is Concretized when symbolic
according to the 'ONE' policy and concretize |address| with the default policy.
:param policies: A kwargs list of argument names and their respective policies.
Provide None or '' as policy to use default.
:return: A function decorator
"""
def concretizer(func):
@wraps(func)
def wrapper(*args, **kwargs):
spec = inspect.getfullargspec(func)
for arg, policy in policies.items():
assert arg in spec.args, "Concretizer argument not found in wrapped function."
# index is 0-indexed, but ConcretizeStack is 1-indexed. However, this is correct
# since implementation method is always a bound method (self is param 0)
index = spec.args.index(arg)
if not issymbolic(args[index]):
continue
if not policy:
policy = 'MINMAX'
if policy == "ACCOUNTS":
value = args[index]
world = args[0].world
#special handler for EVM only policy
cond = world._constraint_to_accounts(value, ty='both', include_zero=True)
world.constraints.add(cond)
policy = 'ALL'
raise ConcretizeStack(index, policy=policy)
return func(*args, **kwargs)
wrapper.__signature__ = inspect.signature(func)
return wrapper
return concretizer
class EVM(Eventful):
'''Machine State. The machine state is defined as
the tuple (g, pc, m, i, s) which are the gas available, the
program counter pc , the memory contents, the active
number of words in memory (counting continuously
from position 0), and the stack contents. The memory
contents are a series of zeroes of bitsize 256
'''
_published_events = {'evm_execute_instruction',
'evm_read_storage', 'evm_write_storage',
'evm_read_memory',
'evm_write_memory',
'evm_read_code',
'decode_instruction', 'execute_instruction', 'concrete_sha3', 'symbolic_sha3'}
class transact:
"Emulate PyProperty_Type() in Objects/descrobject.c"
def __init__(self, pre=None, pos=None, doc=None):
self._pre = pre
self._pos = pos
if doc is None and pre is not None:
doc = pre.__doc__
self.__doc__ = doc
self.__name__ = pre.__name__
def __get__(self, obj, objtype=None):
if obj is None:
return self
if self._pre is None:
raise AttributeError("unreadable attribute")
from types import MethodType
#return different version depending on obj._pending_transaction
def _pre_func(my_obj, *args, **kwargs):
if my_obj._on_transaction:
result = self._pos(my_obj, *args, **kwargs)
my_obj._on_transaction = False
return result
else:
try:
self._pre(my_obj, *args, **kwargs)
raise AssertionError("The pre-transaction handler must raise a StartTx transaction")
except StartTx:
my_obj._on_transaction = True
raise
return MethodType(_pre_func, obj)
def __set__(self, obj, value):
raise AttributeError("can't set attribute")
def __delete__(self, obj):
raise AttributeError("can't delete attribute")
def pos(self, pos):
return type(self)(self._pre, pos)
def __init__(self, constraints, address, data, caller, value, bytecode, world=None, gas=210000, **kwargs):
'''
Builds a Ethereum Virtual Machine instance
:param memory: the initial memory
:param address: the address of the account which owns the code that is executing.
:param data: the byte array that is the input data to this execution
:param caller: the address of the account which caused the code to be executing. A 160-bit code used for identifying Accounts
:param value: the value, in Wei, passed to this account as part of the same procedure as execution. One Ether is defined as being 10**18 Wei
:param bytecode: the byte array that is the machine code to be executed
:param world: the EVMWorld object where the transaction is being executed
:param gas: gas budget for this transaction
'''
super().__init__(**kwargs)
if data is not None and not issymbolic(data):
data_size = len(data)
data_symbolic = constraints.new_array(index_bits=256, value_bits=8, index_max=data_size, name=f'DATA_{address:x}', avoid_collisions=True, default=0)
data_symbolic[0:data_size] = data
data = data_symbolic
if bytecode is not None and not issymbolic(bytecode):
bytecode_size = len(bytecode)
bytecode_symbolic = constraints.new_array(index_bits=256, value_bits=8, index_max=bytecode_size, name=f'BYTECODE_{address:x}', avoid_collisions=True, default=0)
bytecode_symbolic[0:bytecode_size] = bytecode
bytecode = bytecode_symbolic
#TODO: Handle the case in which bytecode is symbolic (This happens at
# CREATE instructions that has the arguments appended to the bytecode)
# This is a very cornered corner case in which code is actually symbolic
# We should simply not allow to jump to unconstrained(*) symbolic code.
# (*) bytecode that could take more than a single value
self._check_jumpdest = False
self._valid_jumpdests = set()
#Compile the list of valid jumpdests via linear dissassembly
def extend_with_zeroes(b):
try:
for x in b:
x = to_constant(x)
if isinstance(x, int):
yield(x)
else:
yield(0)
for _ in range(32):
yield(0)
except Exception as e:
return
for i in EVMAsm.disassemble_all(extend_with_zeroes(bytecode)):
if i.mnemonic == 'JUMPDEST':
self._valid_jumpdests.add(i.pc)
#A no code VM is used to execute transactions to normal accounts.
#I'll execute a STOP and close the transaction
#if len(bytecode) == 0:
# raise EVMException("Need code")
self._constraints = constraints
# Uninitialized values in memory are 0 by spec
self.memory = constraints.new_array(index_bits=256, value_bits=8, name=f'EMPTY_MEMORY_{address:x}', avoid_collisions=True, default=0)
self.address = address
self.caller = caller # address of the account that is directly responsible for this execution
self.data = data
self.value = value
self._bytecode = bytecode
self.suicides = set()
self.logs = []
#FIXME parse decode and mark invalid instructions
#self.invalid = set()
# Machine state
self.pc = 0
self.stack = []
# We maintain gas as a 512 bits internally to avoid overflows
# it is shortened to 256 bits when it is used by the GAS instruction
self._gas = Operators.ZEXTEND(gas, 512)
self._world = world
self._allocated = 0
self._on_transaction = False # for @transact
self._checkpoint_data = None
self._published_pre_instruction_events = False
# Used calldata size
min_size = 0
max_size = len(self.data)
self._used_calldata_size = 0
self._calldata_size = len(self.data)
self._valid_jmpdests = set()
@property
def bytecode(self):
return self._bytecode
@property
def constraints(self):
return self._constraints
@constraints.setter
def constraints(self, constraints):
self._constraints = constraints
self.memory.constraints = constraints
@property
def gas(self):
return self._gas
def __getstate__(self):
state = super().__getstate__()
state['memory'] = self.memory
state['world'] = self._world
state['constraints'] = self.constraints
state['address'] = self.address
state['caller'] = self.caller
state['data'] = self.data
state['value'] = self.value
state['bytecode'] = self._bytecode
state['pc'] = self.pc
state['stack'] = self.stack
state['gas'] = self._gas
state['allocated'] = self._allocated
state['suicides'] = self.suicides
state['logs'] = self.logs
state['_on_transaction'] = self._on_transaction
state['_checkpoint_data'] = self._checkpoint_data
state['_published_pre_instruction_events'] = self._published_pre_instruction_events
state['_used_calldata_size'] = self._used_calldata_size
state['_calldata_size'] = self._calldata_size
state['_valid_jumpdests'] = self._valid_jumpdests
state['_check_jumpdest'] = self._check_jumpdest
return state
def __setstate__(self, state):
self._checkpoint_data = state['_checkpoint_data']
self._published_pre_instruction_events = state['_published_pre_instruction_events']
self._on_transaction = state['_on_transaction']
self._gas = state['gas']
self.memory = state['memory']
self.logs = state['logs']
self._world = state['world']
self.constraints = state['constraints']
self.address = state['address']
self.caller = state['caller']
self.data = state['data']
self.value = state['value']
self._bytecode = state['bytecode']
self.pc = state['pc']
self.stack = state['stack']
self._allocated = state['allocated']
self.suicides = state['suicides']
self._used_calldata_size = state['_used_calldata_size']
self._calldata_size = state['_calldata_size']
self._valid_jumpdests = state['_valid_jumpdests']
self._check_jumpdest = state['_check_jumpdest']
super().__setstate__(state)
def _get_memfee(self, address, size=1):
address = self.safe_add(address, size)
allocated = self.allocated
GMEMORY = 3
GQUADRATICMEMDENOM = 512 # 1 gas per 512 quadwords
old_size = Operators.ZEXTEND(Operators.UDIV(self.safe_add(allocated, 31), 32), 512)
new_size = Operators.ZEXTEND(Operators.UDIV(self.safe_add(address, 31), 32), 512)
old_totalfee = self.safe_mul(old_size, GMEMORY) + Operators.UDIV(self.safe_mul(old_size, old_size), GQUADRATICMEMDENOM)
new_totalfee = self.safe_mul(new_size, GMEMORY) + Operators.UDIV(self.safe_mul(new_size, new_size), GQUADRATICMEMDENOM)
memfee = new_totalfee - old_totalfee
flag = Operators.AND(size != 0, Operators.UGT(new_totalfee, old_totalfee))
return Operators.ITEBV(512, flag, memfee, 0)
def _allocate(self, address, size=1):
self._consume(self._get_memfee(address, size))
address_c = Operators.UDIV(Operators.ZEXTEND(address, 512) + size + 31, 32) * 32
self._allocated = Operators.ITEBV(512, Operators.UGT(address_c, self._allocated), address_c, self.allocated)
@property
def allocated(self):
return self._allocated
@property
def world(self):
return self._world
@staticmethod
def check256int(value):
assert True
def read_code(self, address, size=1):
'''
Read size byte from bytecode.
If less than size bytes are available result will be pad with \x00
'''
assert address < len(self.bytecode)
value = self.bytecode[address:address + size]
if len(value) < size:
value += '\x00' * (size - len(value)) # pad with null (spec)
return value
def disassemble(self):
return EVMAsm.disassemble(self.bytecode)
@property
def PC(self):
return self.pc
@property
def instruction(self):
'''
Current instruction pointed by self.pc
'''
# FIXME check if pc points to invalid instruction
# if self.pc >= len(self.bytecode):
# return InvalidOpcode('Code out of range')
# if self.pc in self.invalid:
# raise InvalidOpcode('Opcode inside a PUSH immediate')
try:
_decoding_cache = getattr(self, '_decoding_cache')
except:
_decoding_cache = self._decoding_cache = {}
pc = self.pc
if isinstance(pc, Constant):
pc = pc.value
if pc in _decoding_cache:
return _decoding_cache[pc]
def getcode():
bytecode = self.bytecode
for pc_i in range(pc, len(bytecode)):
yield simplify(bytecode[pc_i]).value
while True:
yield 0
instruction = EVMAsm.disassemble_one(getcode(), pc=pc, fork=DEFAULT_FORK)
_decoding_cache[pc] = instruction
return instruction
# auxiliary funcs
# Stack related
def _push(self, value):
'''
ITEM0
ITEM1
ITEM2
sp-> {empty}
'''
assert isinstance(value, int) or isinstance(value, BitVec) and value.size == 256
if len(self.stack) >= 1024:
raise StackOverflow()
if isinstance(value, int):
value = value & TT256M1
value = simplify(value)
if isinstance(value, Constant) and not value.taint:
value = value.value
self.stack.append(value)
def _top(self, n=0):
''' Read a value from the top of the stack without removing it '''
if len(self.stack) - n < 0:
raise StackUnderflow()
return self.stack[n - 1]
def _pop(self):
''' Pop a value from the stack '''
if len(self.stack) == 0:
raise StackUnderflow()
return self.stack.pop()
def _consume(self, fee):
if isinstance(fee, int):
if fee > (1 << 512) - 1:
raise ValueError
elif isinstance(fee, BitVec):
if (fee.size != 512):
raise ValueError("Fees should be 512 bit long")
#FIXME add configurable checks here
config.out_of_gas = 3
# If both are concrete values...
if not issymbolic(self._gas) and not issymbolic(fee):
if self._gas < fee:
logger.debug("Not enough gas for instruction")
raise NotEnoughGas()
else:
if config.out_of_gas is None:
# do nothing. gas could go negative.
# memory could be accessed in great offsets
pass
elif config.out_of_gas == 0:
#explore only when OOG
if solver.can_be_true(self.constraints, Operators.ULT(self.gas, fee)):
self.constraints.add(Operators.UGT(fee, self.gas))
logger.debug("Not enough gas for instruction")
raise NotEnoughGas()
elif config.out_of_gas == 1:
#explore only when there is enough gas if possible
if solver.can_be_true(self.constraints, Operators.UGT(self.gas, fee)):
self.constraints.add(Operators.UGT(self.gas, fee))
else:
logger.debug("Not enough gas for instruction")
raise NotEnoughGas()
else:
#explore both options / fork
enough_gas_solutions = solver.get_all_values(self.constraints, Operators.UGT(self._gas, fee))
if len(enough_gas_solutions) == 2:
raise Concretize("Concretize gas fee",
expression=Operators.UGT(self._gas, fee),
setstate=None,
policy='ALL')
elif enough_gas_solutions[0] == False:
logger.debug("Not enough gas for instruction")
raise NotEnoughGas()
self._gas -= fee
assert issymbolic(self._gas) or self._gas >= 0
def _indemnify(self, fee):
self._gas += fee
def _pop_arguments(self):
#Get arguments (imm, pop)
current = self.instruction
arguments = []
if current.has_operand:
arguments.append(current.operand)
for _ in range(current.pops):
arguments.append(self._pop())
# simplify stack arguments
for i in range(len(arguments)):
if isinstance(arguments[i], Constant) and not arguments[i].taint:
arguments[i] = arguments[i].value
return arguments
def _top_arguments(self):
#Get arguments (imm, top). Stack is not changed
current = self.instruction
arguments = []
if current.has_operand:
arguments.append(current.operand)
if current.pops:
arguments.extend(reversed(self.stack[-current.pops:]))
return arguments
def _push_arguments(self, arguments):
#Immediate operands should not be pushed
start = int(self.instruction.has_operand)
for arg in reversed(arguments[start:]):
self._push(arg)
def _push_results(self, instruction, result):
# Check result (push)
if instruction.pushes > 1:
assert len(result) == instruction.pushes
for value in reversed(result):
self._push(value)
elif instruction.pushes == 1:
self._push(result)
else:
assert instruction.pushes == 0
assert result is None
def _handler(self, *arguments):
current = self.instruction
implementation = getattr(self, current.semantics, None)
if implementation is None:
raise TerminateState("Instruction not implemented %s" % current.semantics, testcase=True)
return implementation(*arguments)
def _checkpoint(self):
#Fixme[felipe] add a with self.disabled_events context mangr to Eventful
if self._checkpoint_data is None:
if not self._published_pre_instruction_events:
self._published_pre_instruction_events = True
self._publish('will_decode_instruction', self.pc)
self._publish('will_execute_instruction', self.pc, self.instruction)
self._publish('will_evm_execute_instruction', self.instruction, self._top_arguments())
pc = self.pc
instruction = self.instruction
old_gas = self._gas
self._consume(instruction.fee)
arguments = self._pop_arguments()
self._checkpoint_data = (pc, old_gas, instruction, arguments)
return self._checkpoint_data
def _rollback(self):
#Revert the stack, gas and pc so it looks like before executing the instruction
last_pc, last_gas, last_instruction, last_arguments = self._checkpoint_data
self._push_arguments(last_arguments)
self._gas = last_gas
self._pc = last_pc
self._checkpoint_data = None
def _set_check_jmpdest(self, flag=True):
self._check_jumpdest = flag
def _check_jmpdest(self):
should_check_jumpdest = self._check_jumpdest
if issymbolic(should_check_jumpdest):
should_check_jumpdest_solutions = solver.get_all_values(self.constraints, should_check_jumpdest)
if len(should_check_jumpdest_solutions) != 1:
raise EthereumError("Conditional not concretized at JMPDEST check")
should_check_jumpdest = should_check_jumpdest_solutions[0]
if should_check_jumpdest:
self._check_jumpdest = False
if self.pc not in self._valid_jumpdests:
raise InvalidOpcode()
def _advance(self, result=None, exception=False):
if self._checkpoint_data is None:
return
last_pc, last_gas, last_instruction, last_arguments = self._checkpoint_data
if not exception:
if not last_instruction.is_branch:
#advance pc pointer
self.pc += last_instruction.size
self._push_results(last_instruction, result)
self._publish('did_evm_execute_instruction', last_instruction, last_arguments, result)
self._publish('did_execute_instruction', last_pc, self.pc, last_instruction)
self._checkpoint_data = None
self._published_pre_instruction_events = False
def change_last_result(self, result):
last_pc, last_gas, last_instruction, last_arguments = self._checkpoint_data
# Check result (push)\
if last_instruction.pushes > 1:
assert len(result) == last_instruction.pushes
for _ in range(last_instruction.pushes):
self._pop()
for value in reversed(result):
self._push(value)
elif last_instruction.pushes == 1:
self._pop()
self._push(result)
else:
assert last_instruction.pushes == 0
assert result is None
#Execute an instruction from current pc
def execute(self):
pc = self.pc
if issymbolic(pc) and not isinstance(pc, Constant):
expression = pc
taints = self.pc.taint
def setstate(state, value):
if taints:
state.platform.current_vm.pc = BitVecConstant(256, value, taint=taints)
else:
state.platform.current_vm.pc = value
raise Concretize("Concretize PC",
expression=expression,
setstate=setstate,
policy='ALL')
try:
self._check_jmpdest()
last_pc, last_gas, instruction, arguments = self._checkpoint()
result = self._handler(*arguments)
self._advance(result)
except ConcretizeStack as ex:
self._rollback()
pos = -ex.pos
def setstate(state, value):
self.stack[pos] = value
raise Concretize("Concretize Stack Variable",
expression=self.stack[pos],
setstate=setstate,
policy=ex.policy)
except StartTx:
raise
except EndTx as ex:
self._advance(exception=True)
raise
def read_buffer(self, offset, size):
if issymbolic(size):
raise EVMException("Symbolic size not supported")
if size == 0:
return b''
self._allocate(offset, size)
return self.memory[offset: offset + size]
def write_buffer(self, offset, data):
self._allocate(offset, len(data))
for i, c in enumerate(data):
self._store(offset + i, Operators.ORD(c))
def _load(self, offset, size=1):
value = self.memory.read_BE(offset, size)
try:
value = simplify(value)
if not value.taint:
value = value.value
except:
pass
for i in range(size):
self._publish('did_evm_read_memory', offset + i, Operators.EXTRACT(value, (size - i - 1) * 8, 8))
return value
def _store(self, offset, value, size=1):
''' Stores value in memory as a big endian '''
self.memory.write_BE(offset, value, size)
for i in range(size):
self._publish('did_evm_write_memory', offset + i, Operators.EXTRACT(value, (size - i - 1) * 8, 8))
def safe_add(self, a, b):
a = Operators.ZEXTEND(a, 512)
b = Operators.ZEXTEND(b, 512)
result = a + b
'''
if solver.can_be_true(self.constraints, Operators.ULT(result, 1 << 256)):
self.constraints.add(Operators.ULT(result, 1 << 256))
else:
raise ValueError("Integer overflow")
'''
return result
def safe_mul(self, a, b):
a = Operators.ZEXTEND(a, 512)
b = Operators.ZEXTEND(b, 512)
result = a * b
'''
if solver.can_be_true(self.constraints, Operators.ULT(result, 1 << 256)):
self.constraints.add(Operators.ULT(result, 1 << 256))
else:
raise ValueError("Integer overflow")
'''
return result
############################################################################
#INSTRUCTIONS
def INVALID(self):
'''Halts execution'''
raise InvalidOpcode()
############################################################################