-
Notifications
You must be signed in to change notification settings - Fork 473
/
test_general.py
1808 lines (1515 loc) · 73.4 KB
/
test_general.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
import binascii
import unittest
from contextlib import contextmanager
from pathlib import Path
import os
import pyevmasm as EVMAsm
import re
import shutil
import struct
import tempfile
from manticore.core.plugin import Plugin
from manticore.core.smtlib import ConstraintSet, operators
from manticore.core.smtlib import Z3Solver
from manticore.core.smtlib.expression import BitVec
from manticore.core.smtlib.visitors import to_constant
from manticore.core.state import TerminateState
from manticore.ethereum import (
ManticoreEVM,
State,
DetectExternalCallAndLeak,
DetectIntegerOverflow,
Detector,
NoAliveStates,
ABI,
EthereumError,
EVMContract,
)
from manticore.ethereum.plugins import FilterFunctions
from manticore.ethereum.solidity import SolidityMetadata
from manticore.platforms import evm
from manticore.platforms.evm import EVMWorld, ConcretizeArgument, concretized_args, Return, Stop
from manticore.utils.deprecated import ManticoreDeprecationWarning
solver = Z3Solver.instance()
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
@contextmanager
def disposable_mevm(*args, **kwargs):
mevm = ManticoreEVM(*args, **kwargs)
try:
yield mevm
finally:
shutil.rmtree(mevm.workspace)
class EthDetectorsIntegrationTest(unittest.TestCase):
def test_int_ovf(self):
mevm = ManticoreEVM()
mevm.register_detector(DetectIntegerOverflow())
filename = os.path.join(THIS_DIR, "contracts/int_overflow.sol")
mevm.multi_tx_analysis(filename, tx_limit=1)
self.assertEqual(len(mevm.global_findings), 3)
all_findings = "".join([x[2] for x in mevm.global_findings])
self.assertIn("Unsigned integer overflow at SUB instruction", all_findings)
self.assertIn("Unsigned integer overflow at ADD instruction", all_findings)
self.assertIn("Unsigned integer overflow at MUL instruction", all_findings)
class EthAbiTests(unittest.TestCase):
_multiprocess_can_split = True
@staticmethod
def _pack_int_to_32(x):
return b"\x00" * 28 + struct.pack(">I", x)
def test_str_for_string_bytesM_arg(self):
self.assertEqual(
ABI.serialize("(string,bytes32)", "hi", "qq"),
bytearray(
b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00@qq\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02hi\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
),
)
self.assertEqual(
ABI.serialize("string", "hi"),
bytearray(
b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02hi\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
),
)
def test_parse_tx(self):
m = ManticoreEVM()
source_code = """
contract C{
mapping(address => uint) balances;
function test1(address to, uint val){
balances[to] = val;
}
}
"""
user_account = m.create_account(balance=1000, name="user_account")
contract_account = m.solidity_create_contract(
source_code, owner=user_account, name="contract_account"
)
calldata = binascii.unhexlify(
b"9de4886f9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d9d"
)
returndata = b""
md = m.get_metadata(contract_account)
self.assertEqual(
md.parse_tx(calldata, returndata),
"test1(899826498278242188854817720535123270925417291165, 71291600040229971300002528024956868756719167029433602173313100742126907268509)",
)
def test_dyn_address(self):
d = [
b"AAAA", # function hash
self._pack_int_to_32(32), # offset to data start
self._pack_int_to_32(2), # data start; # of elements
self._pack_int_to_32(42), # element 1
self._pack_int_to_32(43), # element 2
]
d = b"".join(d)
func_id, dynargs = ABI.deserialize(type_spec="func(address[])", data=d)
self.assertEqual(func_id, b"AAAA")
self.assertEqual(dynargs, ([42, 43],))
def test_dyn_bytes(self):
d = [
b"AAAA", # function hash
self._pack_int_to_32(32), # offset to data start
self._pack_int_to_32(30), # data start; # of elements
b"Z" * 30,
b"\x00" * 2,
]
d = b"".join(d)
funcname, dynargs = ABI.deserialize(type_spec="func(bytes)", data=d)
self.assertEqual(funcname, b"AAAA")
self.assertEqual(dynargs, (b"Z" * 30,))
def test_simple_types0(self):
d = [b"AAAA", self._pack_int_to_32(32), b"\xff" * 32] # function hash
d = b"".join(d)
funcname, dynargs = ABI.deserialize(type_spec="func(uint256,uint256)", data=d)
# self.assertEqual(funcname, 'AAAA')
self.assertEqual(dynargs, (32, 2 ** 256 - 1))
def test_simple_types1(self):
d = [
b"AAAA", # function hash
self._pack_int_to_32(32),
b"\xff" * 32,
b"\xff".rjust(32, b"\0"),
self._pack_int_to_32(0x424242),
]
d = b"".join(d)
funcname, dynargs = ABI.deserialize(type_spec="func(uint256,uint256,bool,address)", data=d)
# self.assertEqual(funcname, 'AAAA')
self.assertEqual(dynargs, (32, 2 ** 256 - 1, 0xFF, 0x424242))
def test_simple_types_ints(self):
d = [
b"AAAA", # function hash
b"\x7f" + b"\xff" * 31, # int256 max
b"\x80".ljust(32, b"\0"), # int256 min
]
d = b"".join(d)
func_id, dynargs = ABI.deserialize(type_spec="func(int256,int256)", data=d)
self.assertEqual(func_id, b"AAAA")
self.assertEqual(dynargs, (2 ** 255 - 1, -(2 ** 255)))
def test_simple_types_ints_symbolic(self):
cs = ConstraintSet()
x = cs.new_bitvec(256, name="x")
y = cs.new_bitvec(256, name="y")
# Something is terribly wrong x,y = 10,20
my_ser = ABI.serialize("(uint,uint)", x, y)
x_, y_ = ABI.deserialize("(uint,uint)", my_ser)
self.assertTrue(solver.must_be_true(cs, x == x_))
self.assertTrue(solver.must_be_true(cs, y == y_))
def test_simple_types_ints_symbolic1(self):
cs = ConstraintSet()
x = cs.new_bitvec(256, name="x")
# Something is terribly wrong x,y = 10,20
my_ser = ABI.serialize("uint", x)
self.assertTrue(solver.must_be_true(cs, my_ser[0] == operators.EXTRACT(x, 256 - 8, 8)))
def test_address0(self):
data = f"{chr(0) * 11}\x01\x55{chr(0) * 19}"
parsed = ABI.deserialize("address", data)
self.assertEqual(parsed, 0x55 << (8 * 19))
def test_mult_dyn_types(self):
d = [
b"AAAA", # function hash
self._pack_int_to_32(0x40), # offset to data 1 start
self._pack_int_to_32(0x80), # offset to data 2 start
self._pack_int_to_32(10), # data 1 size
b"helloworld".ljust(32, b"\x00"), # data 1
self._pack_int_to_32(3), # data 2 size
self._pack_int_to_32(3), # data 2
self._pack_int_to_32(4),
self._pack_int_to_32(5),
]
d = b"".join(d)
func_id, dynargs = ABI.deserialize(type_spec="func(bytes,address[])", data=d)
self.assertEqual(func_id, b"AAAA")
self.assertEqual(dynargs, (b"helloworld", [3, 4, 5]))
def test_self_make_and_parse_multi_dyn(self):
d = ABI.function_call("func(bytes,address[])", b"h" * 50, [1, 1, 2, 2, 3, 3])
funcid, dynargs = ABI.deserialize(type_spec="func(bytes,address[])", data=d)
self.assertEqual(funcid, b"\x83}9\xe8")
self.assertEqual(dynargs, (b"h" * 50, [1, 1, 2, 2, 3, 3]))
def test_serialize_tuple(self):
self.assertEqual(ABI.serialize("(int256)", 0x10), b"\0" * 31 + b"\x10")
self.assertEqual(
ABI.serialize("(int256,int256)", 0x10, 0x20),
b"\0" * 31 + b"\x10" + b"\0" * 31 + b"\x20",
)
self.assertEqual(
ABI.serialize("(int256,(int256,int256))", 0x10, (0x20, 0x30)),
b"\0" * 31 + b"\x10" + b"\0" * 31 + b"\x20" + b"\0" * 31 + b"\x30",
)
def test_serialize_basic_types_int(self):
self.assertEqual(ABI.serialize("int256", 0x10), b"\0" * 31 + b"\x10")
self.assertEqual(ABI.deserialize("int256", b"\0" * 31 + b"\x10"), 0x10)
self.assertEqual(ABI.serialize("int256", -0x10), b"\xff" * 31 + b"\xf0")
self.assertEqual(ABI.deserialize("int256", b"\xff" * 31 + b"\xf0"), -0x10)
def test_serialize_basic_types_int8(self):
self.assertEqual(ABI.serialize("int8", 0x10), b"\0" * 31 + b"\x10")
self.assertEqual(ABI.deserialize("int8", b"\0" * 31 + b"\x10"), 0x10)
self.assertEqual(ABI.serialize("int8", -0x10), b"\x00" * 31 + b"\xf0")
self.assertEqual(ABI.deserialize("int8", b"\x00" * 31 + b"\xf0"), -0x10)
def test_serialize_basic_types_int16(self):
self.assertEqual(ABI.serialize("int16", 0x100), b"\0" * 30 + b"\x01\x00")
self.assertEqual(ABI.deserialize("int16", b"\0" * 30 + b"\x01\x00"), 0x100)
self.assertEqual(ABI.serialize("int16", -0x10), b"\x00" * 30 + b"\xff\xf0")
self.assertEqual(ABI.deserialize("int16", b"\x00" * 30 + b"\xff\xf0"), -0x10)
def test_serialize_basic_types_uint(self):
self.assertEqual(ABI.serialize("uint256", 0x10), b"\0" * 31 + b"\x10")
self.assertEqual(ABI.deserialize("uint256", b"\0" * 31 + b"\x10"), 0x10)
self.assertEqual(ABI.serialize("uint256", -0x10), b"\xff" * 31 + b"\xf0")
self.assertEqual(
ABI.deserialize("uint256", b"\xff" * 31 + b"\xf0"),
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0,
)
self.assertEqual(
ABI.deserialize("uint256", b"\xff" * 31 + b"\xf0"),
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0,
)
self.assertNotEqual(ABI.deserialize("uint256", b"\xff" * 31 + b"\xf0"), -0x10)
def test_parse_invalid_int(self):
with self.assertRaises(EthereumError):
ABI.deserialize("intXXX", "\xFF")
ABI.deserialize("uintXXX", "\xFF")
def test_parse_invalid_int_too_big(self):
with self.assertRaises(EthereumError):
ABI.deserialize("int3000", "\xFF")
ABI.deserialize("uint3000", "\xFF")
def test_parse_invalid_int_negative(self):
with self.assertRaises(EthereumError):
ABI.deserialize("int-8", "\xFF")
ABI.deserialize("uint-8", "\xFF")
def test_parse_invalid_int_not_pow_of_two(self):
with self.assertRaises(EthereumError):
ABI.deserialize("int31", "\xFF")
ABI.deserialize("uint31", "\xFF")
def test_parse_valid_int0(self):
ret = ABI.deserialize("int8", "\x10" * 32)
self.assertEqual(ret, 0x10)
def test_parse_valid_int1(self):
ret = ABI.deserialize("int", "\x10".ljust(32, "\0"))
self.assertEqual(ret, 1 << 252)
def test_parse_valid_int2(self):
ret = ABI.deserialize("int40", "\x40\x00\x00\x00\x00".rjust(32, "\0"))
self.assertEqual(ret, 1 << 38)
def test_valid_uint(self):
data = b"\xFF" * 32
parsed = ABI.deserialize("uint", data)
self.assertEqual(parsed, 2 ** 256 - 1)
for i in range(8, 257, 8):
parsed = ABI.deserialize(f"uint{i}", data)
self.assertEqual(parsed, 2 ** i - 1)
def test_empty_types(self):
name, args = ABI.deserialize("func()", "\0" * 32)
self.assertEqual(name, b"\x00\x00\x00\x00")
self.assertEqual(args, tuple())
def test_function_type(self):
# setup ABI for function with one function param
spec = "func(function)"
func_id = ABI.function_selector(spec)
# build bytes24 data for function value (address+selector)
# calls member id lookup on 'Ethereum Foundation Tip Box' (see https://www.ethereum.org/donate)
address = ABI._serialize_uint(0xFB6916095CA1DF60BB79CE92CE3EA74C37C5D359, 20, padding=0)
selector = ABI.function_selector("memberId(address)")
function_ref_data = address + selector + b"\0" * 8
# build tx call data
call_data = func_id + function_ref_data
parsed_func_id, args = ABI.deserialize(spec, call_data)
self.assertEqual(parsed_func_id, func_id)
self.assertEqual(((0xFB6916095CA1DF60BB79CE92CE3EA74C37C5D359, selector),), args)
def test_serialize_fixed_bytes32(self):
ret = ABI.serialize("bytes32", b"hi")
self.assertEqual(ret, b"hi".ljust(32, b"\x00"))
def test_serialize_fixed_bytes2(self):
ret = ABI.serialize("bytes2", b"aa")
self.assertEqual(ret, b"aa".ljust(32, b"\x00"))
def test_serialize_fixed_bytes_less_data(self):
ret = ABI.serialize("bytes4", b"aa")
self.assertEqual(ret, b"aa".ljust(32, b"\x00"))
def test_serialize_fixed_bytes_too_big(self):
with self.assertRaises(EthereumError):
ABI.serialize("bytes2", b"hii")
# test serializing symbolic buffer with bytesM
def test_serialize_bytesM_symbolic(self):
cs = ConstraintSet()
buf = cs.new_array(index_max=17)
ret = ABI.serialize("bytes32", buf)
self.assertEqual(solver.minmax(cs, ret[0]), (0, 255))
self.assertEqual(solver.minmax(cs, ret[17]), (0, 0))
# test serializing symbolic buffer with bytes
def test_serialize_bytes_symbolic(self):
cs = ConstraintSet()
buf = cs.new_array(index_max=17)
ret = ABI.serialize("bytes", buf)
# does the offset field look right?
self.assertTrue(solver.must_be_true(cs, ret[0:32] == bytearray(b"\x00" * 31 + b"\x20")))
# does the size field look right?
self.assertTrue(solver.must_be_true(cs, ret[32:64] == bytearray(b"\x00" * 31 + b"\x11")))
# does the data field look right?
self.assertTrue(solver.must_be_true(cs, ret[64 : 64 + 32] == buf + bytearray(b"\x00" * 15)))
class EthInstructionTests(unittest.TestCase):
def _make(self):
# Make the constraint store
constraints = ConstraintSet()
# make the ethereum world state
world = evm.EVMWorld(constraints)
address = 0x222222222222222222222222222222222222200
caller = origin = 0x111111111111111111111111111111111111100
price = 0
value = 10000
bytecode = b"\x05"
data = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
gas = 1000000
new_vm = evm.EVM(constraints, address, data, caller, value, bytecode, gas=gas, world=world)
return constraints, world, new_vm
def test_str(self):
constraints, world, vm = self._make()
vm_str = """0x222222222222222222222222222222222222200: ---------------------------------------------------------------------------------------------------------------------------------------------------\n0x222222222222222222222222222222222222200: 0x0000: SDIV Signed integer division operation (truncated).\n0x222222222222222222222222222222222222200: Stack Memory\n0x222222222222222222222222222222222222200: 0000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................\n0x222222222222222222222222222222222222200: 0010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................\n0x222222222222222222222222222222222222200: 0020 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................\n0x222222222222222222222222222222222222200: 0030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................\n0x222222222222222222222222222222222222200: 0040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................\n0x222222222222222222222222222222222222200: 0050 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................\n0x222222222222222222222222222222222222200: 0060 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................\n0x222222222222222222222222222222222222200: 0070 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................\n0x222222222222222222222222222222222222200: Gas: 1000000"""
self.assertEqual(str(vm), vm_str)
def test_SDIV(self):
constraints, world, vm = self._make()
result = vm.SDIV(
115792089237316182568066630936765703517573245936339743861833633745570447228928,
200867255532373784442745261542645325315275374222849104412672,
)
self.assertEqual(-64, result)
def test_SDIVS1(self):
constraints, world, vm = self._make()
xx = constraints.new_bitvec(256, name="x")
yy = constraints.new_bitvec(256, name="y")
constraints.add(xx == 0x20)
constraints.add(yy == 1)
result = vm.SDIV(xx, yy)
self.assertListEqual(solver.get_all_values(constraints, result), [0x20])
def test_SDIVS2(self):
constraints, world, vm = self._make()
xx = constraints.new_bitvec(256, name="x")
yy = constraints.new_bitvec(256, name="y")
constraints.add(xx == 0x20)
constraints.add(yy == 2)
result = vm.SDIV(xx, yy)
self.assertListEqual(solver.get_all_values(constraints, result), [0x10])
def test_SDIVS3(self):
constraints, world, vm = self._make()
xx = constraints.new_bitvec(256, name="x")
yy = constraints.new_bitvec(256, name="y")
constraints.add(xx == 0x20)
constraints.add(yy == -1)
result = vm.SDIV(xx, yy)
self.assertListEqual(
list(map(evm.to_signed, solver.get_all_values(constraints, result))), [-0x20]
)
def test_SDIVSx(self):
x, y = 0x20000000000000000000000000000000000000000000000000, -0x40
constraints, world, vm = self._make()
xx = constraints.new_bitvec(256, name="x")
yy = constraints.new_bitvec(256, name="y")
constraints.add(xx == x)
constraints.add(yy == y)
result = vm.SDIV(xx, yy)
self.assertListEqual(
list(map(evm.to_signed, solver.get_all_values(constraints, result))), [vm.SDIV(x, y)]
)
class EthTests(unittest.TestCase):
def setUp(self):
self.mevm = ManticoreEVM()
def tearDown(self):
workspace = self.mevm.workspace
del self.mevm
shutil.rmtree(workspace)
def test_solidity_create_contract_no_args(self):
source_code = "contract A { constructor() {} }"
owner = self.mevm.create_account()
# The default `args=()` makes it pass no arguments
contract1 = self.mevm.solidity_create_contract(source_code, owner=owner)
contract2 = self.mevm.solidity_create_contract(source_code, owner=owner)
self.assertNotEqual(contract1, contract2)
def test_solidity_create_contract_with_not_payable_constructor_and_balance(self):
source_code = "contract A { constructor() {} }"
owner = self.mevm.create_account()
with self.assertRaises(EthereumError) as e:
self.mevm.solidity_create_contract(source_code, owner=owner, balance=1)
expected_exception = (
"Can't create solidity contract with balance (1) different "
"than 0 because the contract's constructor is not payable."
)
self.assertEqual(str(e.exception), expected_exception)
def test_solidity_create_contract_with_payable_constructor_and_balance_owner_insufficient_founds(
self
):
source_code = "contract A { constructor() public payable {} }"
owner = self.mevm.create_account(balance=1)
with self.assertRaises(EthereumError) as e:
self.mevm.solidity_create_contract(source_code, owner=owner, balance=2)
expected_exception = (
f"Can't create solidity contract with balance (2) because "
f"the owner account ({owner}) has insufficient balance (1)."
)
self.assertEqual(str(e.exception), expected_exception)
def test_solidity_create_contract_with_payable_constructor(self):
source_code = "contract A { constructor() public payable {} }"
owner = self.mevm.create_account(balance=1000)
contract = self.mevm.solidity_create_contract(source_code, owner=owner, balance=100)
self.assertIsInstance(contract, EVMContract)
def test_solidity_create_contract_with_missing_args(self):
source_code = "contract A { constructor(uint arg) {} }"
owner = self.mevm.create_account()
# TODO / FIXME: Probably change ValueError to another one and inform that bad arguments have been passed?
with self.assertRaises(ValueError) as e:
self.mevm.solidity_create_contract(source_code, owner=owner)
self.assertEqual(
str(e.exception), "The number of values to serialize is less than the number of types"
)
def test_create_contract_with_too_much_args(self):
source_code = "contract A { constructor(uint arg) {} }"
owner = self.mevm.create_account()
with self.assertRaises(ValueError) as e:
self.mevm.solidity_create_contract(source_code, owner=owner, args="(uint32,uint32)")
self.assertEqual(
str(e.exception),
"The number of values to serialize is greater than the number of types",
)
def test_create_contract_with_string_args(self):
source_code = (
"contract DontWork1{ string s; constructor(string memory s_) public{ s = s_;} }"
)
owner = self.mevm.create_account()
sym_args = self.mevm.make_symbolic_arguments("(string)")
contract = self.mevm.solidity_create_contract(source_code, owner=owner, args=sym_args)
self.assertIsNotNone(contract)
self.assertEqual(self.mevm.count_states(), 1)
def test_create_contract_two_instances(self):
source_code = "contract A { constructor(uint32 arg) {} }"
owner = self.mevm.create_account()
contracts = [
# When we pass no `args`, the default is `()` so it ends up with `b''` as constructor data
self.mevm.solidity_create_contract(source_code, owner=owner, args=[1234]),
self.mevm.solidity_create_contract(source_code, owner=owner, args=[1234]),
# When we pass args=None, the arguments end up being symbolic
# NOTE: This is what CLI does
self.mevm.solidity_create_contract(source_code, owner=owner, args=None),
self.mevm.solidity_create_contract(source_code, owner=owner, args=None),
]
# They must have unique address and name
self.assertEqual(len(contracts), len(set(c.address for c in contracts)))
self.assertEqual(len(contracts), len(set(c.name_ for c in contracts)))
def test_contract_create_and_call_underscore_function(self):
source_code = "contract A { function _f(uint x) returns (uint) { return x + 0x1234; } }"
owner = self.mevm.create_account()
contract = self.mevm.solidity_create_contract(source_code, owner=owner, args=[])
contract._f(123)
def test_contract_create_and_access_non_existing_function(self):
source_code = "contract A {}"
owner = self.mevm.create_account()
contract = self.mevm.solidity_create_contract(source_code, owner=owner, args=[])
with self.assertRaises(AttributeError) as e:
_ = contract.xyz
self.assertEqual(str(e.exception), "The contract contract0 doesn't have xyz function.")
def test_invalid_function_signature(self):
source_code = """
contract Test{
function ret(uint256) returns(uint256){
return 1;
}
}
"""
user_account = self.mevm.create_account(balance=1000)
contract_account = self.mevm.solidity_create_contract(source_code, owner=user_account)
with self.assertRaises(EthereumError) as ctx:
contract_account.ret(self.mevm.make_symbolic_value(), signature="(uint8)")
self.assertTrue(str(ctx.exception))
def test_selfdestruct_decoupled_account_delete(self):
source_code = """
contract C{
function d( ){
selfdestruct(0);
}
function g() returns(uint) {
return 42 ;
}
}
contract D{
C c;
constructor () {
c = new C();
}
function t () returns(uint){
c.d();
return c.g();
}
}
"""
user_account = self.mevm.create_account(balance=1000)
contract_account = self.mevm.solidity_create_contract(
source_code, owner=user_account, contract_name="D", gas=9000000
)
contract_account.t(
gas=9000000
) # this does not return nothing as it may create several states
# nothing reverted and we end up with a single state
self.assertEqual(self.mevm.count_states(), 1)
# Check that calling t() returned a 42
# That is that calling a selfdestructed contract works as the account
# is actually deleted at the end of the human tx
self.assertEqual(
ABI.deserialize("uint", to_constant(self.mevm.world.transactions[-1].return_data)), 42
)
def test_create_bytecode_contract(self):
account = self.mevm.create_account(code="0x00AAFF")
self.assertIsNotNone(account)
account = self.mevm.create_account(code=bytes("0x00AAFF", "utf-8"))
self.assertIsNotNone(account)
with self.assertRaises(EthereumError) as ctx:
self.mevm.create_account(code=bytearray("0x00AAFF", "utf-8"))
def test_states_querying_1325(self):
"""
Tests issue 1325.
"""
owner = self.mevm.create_account(balance=1000)
A = self.mevm.solidity_create_contract(
"contract A { function foo() { revert(); } }", owner=owner
)
self.assertEqual(self.mevm.count_ready_states(), 1)
self.assertEqual(self.mevm.count_terminated_states(), 0)
self.assertEqual(self.mevm.count_states(), 1)
A.foo()
def assert_all():
self.assertEqual(self.mevm.count_ready_states(), 0)
self.assertEqual(self.mevm.count_terminated_states(), 1)
self.assertEqual(self.mevm.count_states(), 1)
list(self.mevm.ready_states)
assert_all()
list(self.mevm.terminated_states)
assert_all()
list(self.mevm.all_states)
assert_all()
def test_function_name_collision(self):
source_code = """
contract Test{
function ret(uint) returns(uint){
return 1;
}
function ret(uint,uint) returns(uint){
return 2;
}
}
"""
user_account = self.mevm.create_account(balance=1000)
contract_account = self.mevm.solidity_create_contract(source_code, owner=user_account)
with self.assertRaises(EthereumError):
contract_account.ret(self.mevm.make_symbolic_value())
def test_check_jumpdest_symbolic_pc(self):
"""
In Manticore 0.2.4 (up to 6804661) when run with DetectIntegerOverflow,
the EVM.pc is tainted and so it becomes a Constant and so a check in EVM._check_jumpdest:
self.pc in self._valid_jumpdests
failed (because we checked if the object is in a list of integers...).
This test checks the fix for this issue.
"""
self.mevm.register_detector(DetectIntegerOverflow())
c = self.mevm.solidity_create_contract(
"""
contract C {
function mul(int256 a, int256 b) {
int256 c = a * b;
require(c / a == b);
}
}
""",
owner=self.mevm.create_account(balance=1000),
)
c.mul(1, 2)
self.assertEqual(self.mevm.count_ready_states(), 1)
self.assertEqual(self.mevm.count_terminated_states(), 0)
def test_gen_testcase_only_if(self):
source_code = """
contract Test {
function f(uint x) returns(uint) {
return x-2;
}
}
"""
user_account = self.mevm.create_account(balance=1000)
contract_account = self.mevm.solidity_create_contract(source_code, owner=user_account)
input_sym = self.mevm.make_symbolic_value()
contract_account.f(input_sym)
self.assertEqual(self.mevm.count_ready_states(), 1)
state = next(self.mevm.ready_states)
retval_array = state.platform.human_transactions[-1].return_data
retval = operators.CONCAT(256, *retval_array)
# Test 1: Generate a testcase (since the condition/constrain can be met/solved)
did_gen = self.mevm.generate_testcase(state, "return can be 0", only_if=retval == 0)
self.assertTrue(did_gen)
with state as tmp:
tmp.constrain(retval == 0)
inp = tmp.solve_one(input_sym)
self.assertEqual(inp, 2)
expected_files = {
"user_00000000." + ext
for ext in ("summary", "constraints", "pkl", "tx.json", "tx", "trace", "logs")
}
expected_files.add("state_00000001.pkl")
actual_files = set((fn for fn in os.listdir(self.mevm.workspace) if not fn.startswith(".")))
self.assertEqual(actual_files, expected_files)
summary_path = os.path.join(self.mevm.workspace, "user_00000000.summary")
with open(summary_path) as summary:
self.assertIn("return can be 0", summary.read())
# Test 2: Don't generate a testcase (since the condition/constrain can't be met/solved)
did_gen = self.mevm.generate_testcase(
state, "return can be 0 again?", only_if=operators.AND(retval != 0, retval == 0)
)
self.assertFalse(did_gen)
# Just a sanity check: a generate testcase with not met condition shouldn't add any more files
self.assertEqual(actual_files, expected_files)
# Since the condition was not met there should be no testcase in the summary
with open(summary_path) as summary:
self.assertNotIn("return can be 0 again?", summary.read())
def test_function_name_with_signature(self):
source_code = """
contract Test {
function ret(uint) returns(uint) {
return 1;
}
function ret(uint,uint) returns(uint) {
return 2;
}
}
"""
user_account = self.mevm.create_account(balance=1000)
contract_account = self.mevm.solidity_create_contract(source_code, owner=user_account)
contract_account.ret(
self.mevm.make_symbolic_value(),
self.mevm.make_symbolic_value(),
signature="(uint256,uint256)",
)
for st in self.mevm.all_states:
z = st.solve_one(st.platform.transactions[1].return_data)
break
self.assertEqual(ABI.deserialize("(uint256)", z)[0], 2)
def test_migrate_integration(self):
m = self.mevm
contract_src = """
contract Overflow {
uint public sellerBalance=0;
function add(uint value)public returns (bool){
sellerBalance += value;
}
}
"""
owner_account = m.create_account(balance=1000)
attacker_account = m.create_account(balance=1000)
contract_account = m.solidity_create_contract(contract_src, owner=owner_account, balance=0)
# Some global expression `sym_add1`
sym_add1 = m.make_symbolic_value(name="sym_add1")
# Let's constrain it on the global fake constraintset
m.constrain(sym_add1 > 0)
m.constrain(sym_add1 < 10)
# Symb tx 1
contract_account.add(sym_add1, caller=attacker_account)
# A new!? global expression
sym_add2 = m.make_symbolic_value(name="sym_add2")
# constraints involve old expression. Some states may get invalidated by this. Should this be accepted?
m.constrain(sym_add1 > sym_add2)
# Symb tx 2
contract_account.add(sym_add2, caller=attacker_account)
# random concrete tx
contract_account.sellerBalance(caller=attacker_account)
# another constraining on the global constraintset. Yet more running states could get unfeasible by this.
m.constrain(sym_add1 > 8)
for state_num, state in enumerate(m.all_states):
if state.is_feasible():
self.assertTrue(state.can_be_true(sym_add1 == 9))
self.assertTrue(state.can_be_true(sym_add2 == 8))
def test_account_names(self):
m = self.mevm
user_account = m.create_account(name="user_account")
self.assertEqual(m.accounts["user_account"], user_account)
self.assertEqual(len(m.accounts), 1)
user_account1 = m.create_account(name="user_account1")
self.assertEqual(m.accounts["user_account1"], user_account1)
self.assertEqual(len(m.accounts), 2)
user_accounts = []
for i in range(10):
user_accounts.append(m.create_account())
self.assertEqual(len(m.accounts), 12)
for i in range(10):
self.assertEqual(m.accounts[f"normal{i}"], user_accounts[i])
def test_regression_internal_tx(self):
m = self.mevm
owner_account = m.create_account(balance=1000)
c = """
contract C1 {
function g() returns (uint) {
return 1;
}
}
contract C2 {
address c;
function C2(address x) {
c = x;
}
function f() returns (uint) {
return C1(c).g();
}
}
"""
c1 = m.solidity_create_contract(c, owner=owner_account, contract_name="C1")
self.assertEqual(m.count_states(), 1)
c2 = m.solidity_create_contract(
c, owner=owner_account, contract_name="C2", args=[c1.address]
)
self.assertEqual(m.count_states(), 1)
c2.f()
self.assertEqual(m.count_states(), 1)
c2.f()
self.assertEqual(m.count_states(), 1)
for state in m.all_states:
world = state.platform
self.assertEqual(len(world.transactions), 6)
self.assertEqual(len(world.all_transactions), 6)
self.assertEqual(len(world.human_transactions), 4)
self.assertListEqual(
["CREATE", "CREATE", "CALL", "CALL", "CALL", "CALL"],
[x.sort for x in world.all_transactions],
)
for tx in world.all_transactions[-4:]:
self.assertEqual(tx.result, "RETURN")
self.assertEqual(
state.solve_one(tx.return_data),
b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01",
)
def test_emit_did_execute_end_instructions(self):
"""
Tests whether the did_evm_execute_instruction event is fired for instructions that internally trigger
an exception
"""
class TestDetector(Detector):
def did_evm_execute_instruction_callback(self, state, instruction, arguments, result):
if instruction.is_endtx:
with self.locked_context("endtx_instructions", set) as d:
d.add(instruction.name)
mevm = self.mevm
p = TestDetector()
mevm.register_detector(p)
filename = os.path.join(THIS_DIR, "contracts/simple_int_overflow.sol")
mevm.multi_tx_analysis(filename, tx_limit=2, tx_preconstrain=True)
self.assertIn("endtx_instructions", p.context)
self.assertSetEqual(p.context["endtx_instructions"], {"INVALID", "RETURN", "STOP"})
def test_call_with_concretized_args(self):
"""Test a CALL with symbolic arguments that will to be concretized.
https://github.com/trailofbits/manticore/issues/1237
"""
m = self.mevm
contract_src = """
contract C {
function transferHalfTo(address receiver) public payable {
receiver.transfer(this.balance/2);
}
}
"""
owner = m.create_account(balance=10 ** 10)
contract = m.solidity_create_contract(contract_src, owner=owner)
receiver = m.create_account(0)
symbolic_address = m.make_symbolic_address()
m.constrain(symbolic_address == receiver.address)
self.assertTrue(m.count_ready_states() > 0)
contract.transferHalfTo(symbolic_address, caller=owner, value=m.make_symbolic_value())
self.assertTrue(m.count_ready_states() > 0)
self.assertTrue(
any(
state.can_be_true(state.platform.get_balance(receiver.address) > 0)
for state in m.ready_states
)
)
def test_make_symbolic_address(self):
for init_state in self.mevm.ready_states:
symbolic_address1 = self.mevm.make_symbolic_address()
self.assertEqual(symbolic_address1.name, "TXADDR")
# TEST 1: the 1st symbolic address should be constrained only to 0 (as there are no other accounts yet!)
possible_addresses1 = init_state.solve_n(symbolic_address1, 10)
self.assertEqual(possible_addresses1, [0])
owner = self.mevm.create_account(balance=1)
for state in self.mevm.ready_states:
# TEST 2: the 2nd symbolic address should be constrained to OR(owner_address, 0)
symbolic_address2 = self.mevm.make_symbolic_address()
self.assertEqual(symbolic_address2.name, "TXADDR_1")
self.assertCountEqual(state.solve_n(symbolic_address2, 10), [0, int(owner)])
contract = self.mevm.solidity_create_contract("contract C {}", owner=owner)
# TEST 3: the 3rd symbolic address should be constrained to OR(contract_address, 0, owner_address)
symbolic_address3 = self.mevm.make_symbolic_address()
self.assertEqual(symbolic_address3.name, "TXADDR_2")
for state in self.mevm.ready_states:
self.assertCountEqual(
state.solve_n(symbolic_address3, 10), [int(contract), 0, int(owner)]
)
# NOTE: The 1st and 2nd symbolic addresses are still constrained to 0 and OR(owner_address, 0)
# as the constrains are not reevaluated. They are created/assigned only once: when we create symbolic address.
self.assertCountEqual(state.solve_n(symbolic_address1, 10), [0])
self.assertCountEqual(state.solve_n(symbolic_address2, 10), [int(owner), 0])
def test_end_instruction_trace(self):
"""
Make sure that the trace files are correct, and include the end instructions.
Also, make sure we produce a valid function call in trace.
"""
class TestPlugin(Plugin):
"""
Record the pcs of all end instructions encountered. Source of truth.
"""
def did_evm_execute_instruction_callback(self, state, instruction, arguments, result):
try:
world = state.platform
if world.current_transaction.sort == "CREATE":
name = "init"
else:
name = "rt"
# collect all end instructions based on whether they are in init or rt
if instruction.is_endtx: