-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmain.py
805 lines (618 loc) · 32.4 KB
/
main.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
import sys
import os
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(SCRIPT_DIR))
from fetchPackage.fetchTrace import *
from parserPackage.locator import *
from parserPackage.parserGlobal import *
from parserPackage.parser import *
from crawlPackage.crawl import Crawler
from constraintPackage.accessControlInfer import *
from constraintPackage.dataFlowInfer import *
from constraintPackage.gasControlInfer import *
from constraintPackage.moneyFlowInfer import *
from constraintPackage.oracleControl import *
from constraintPackage.reentrancyInfer import *
from constraintPackage.specialStorage import *
from constraintPackage.timeLockInfer import *
from TxSpectorTranslator.translator import TxSpectorTranslator
def collectTransactionHistory(contractAddress, endBlock: int = -1):
crawler = Crawler()
txHashes = None
if endBlock == -1:
txHashes = crawler.Contract2TxHistory(contractAddress)
else:
txHashes = crawler.Contract2TxHistory(contractAddress, endBlock)
return txHashes
def storeATrace(txHash: str):
fe = fetcher()
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
if not os.path.exists(SCRIPT_DIR + "/cache"):
os.makedirs(SCRIPT_DIR + "/cache")
path = SCRIPT_DIR + "/cache/" + txHash + ".json.gz"
# check if the file exists
if os.path.exists(path):
return
result_dict = fe.getTrace(txHash, FullTrace = False)
writeCompressedJson(path, result_dict)
def readATrace(txHash: str):
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
path = SCRIPT_DIR + "/cache/" + txHash + ".json.gz"
if not os.path.exists(path):
return None
readCompressed = readCompressedJson(path)
return readCompressed
def parseATrace(txHash: str):
# pa = VmtraceParserGlobal()
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
path = SCRIPT_DIR + "/cache/" + txHash + ".json.gz"
temp = analyzeOneTxGlobal(txHash, path)
return temp
def analyzeOneTxHelper(contract, tx, path, depositLocator, investLocator, withdrawLocator):
try:
dataSourceMapList, accessList, splitedTraceTree = analyzeOneTx(contract, tx, path, depositLocator, investLocator, withdrawLocator)
writeDataSource(contract, tx, dataSourceMapList)
writeAccessList(contract, tx, accessList)
writeSplitedTraceTree(contract, tx, splitedTraceTree)
return
except Exception as e:
print(e, file=sys.stderr)
print("Some error happened when analyzing tx: {} path: {}".format(tx, path), file=sys.stderr)
sys.exit("Some error happened when analyzing tx: {} path: {}".format(tx, path))
def writeDataSource(contract, tx, dataSourceMapList):
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
path = SCRIPT_DIR + "/cache/" + contract + "/{}.pickle".format(tx)
# print("write", path)
# print(dataSourceMapList)
with open(path, 'wb') as f:
pickle.dump(dataSourceMapList, f)
def readDataSource(contract, tx):
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
path = SCRIPT_DIR + "/cache/" + contract + "/{}.pickle".format(tx)
objects = []
# check if file exists
if not os.path.exists(path):
return objects
with (open(path, "rb")) as openfile:
while True:
try:
objects.append(pickle.load(openfile))
except EOFError:
break
return objects
def writeAccessList(contract, tx, accessList):
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
path = SCRIPT_DIR + "/cache/" + contract + "_Access/{}.pickle".format(tx)
# print("write", path)
# print(dataSourceMapList)
with open(path, 'wb') as f:
pickle.dump(accessList, f)
def readAccessList(contract, tx):
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
path = SCRIPT_DIR + "/cache/" + contract + "_Access/{}.pickle".format(tx)
objects = []
# check if file exists
if not os.path.exists(path):
return objects
with (open(path, "rb")) as openfile:
while True:
try:
objects.append(pickle.load(openfile))
except EOFError:
break
return objects
def writeSplitedTraceTree(contract, tx, splitedTraceTree):
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
path = SCRIPT_DIR + "/cache/" + contract + "_SplitedTraceTree/{}.pickle".format(tx)
# print("write", path)
# print(dataSourceMapList)
with open(path, 'wb') as f:
pickle.dump(splitedTraceTree, f)
def readSplitedTraceTree(contract, tx):
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
path = SCRIPT_DIR + "/cache/" + contract + "_SplitedTraceTree/{}.pickle".format(tx)
objects = []
# check if file exists
if not os.path.exists(path):
return objects
with (open(path, "rb")) as openfile:
while True:
try:
objects.append(pickle.load(openfile))
except EOFError:
break
return objects
def reformatExecutionTable(executionTable: list):
# refactor improper formatted entry
newExecutionTable = []
for contract, executionList in executionTable:
counter = 0
new_executionList = []
for ii in range(len(executionList)):
execution = executionList[ii]
if isinstance(execution[1], list):
if len(execution[1]) == 1:
executionList[ii] = (execution[0], execution[1][0].to_dict())
new_executionList.append( (execution[0], execution[1][0].to_dict() ) )
else: # means one execution contains multiple target locations
executionList[ii] = [execution[0], []]
gasUsed = []
for jj in range(len(execution[1])):
gas = execution[1][jj].metaData['gas']
if gas not in gasUsed: # there is a possibility of duplicate counting
executionList[ii][1].append( execution[1][jj].to_dict() )
if len( executionList[ii][1]) == 1:
executionList[ii][1] = executionList[ii][1][0].to_dict()
else:
if counter == 0:
print("{} has one function call with several transfers".format(contract))
counter = 1
for jj in range(len(executionList[ii][1])):
new_executionList.append( (executionList[ii][0], executionList[ii][1][jj] ) )
else:
sys.exit("not isinstance(execution[1], list)")
newExecutionTable.append( (contract, new_executionList) )
return newExecutionTable
def mainTestTime():
# Punk_1
# hackTx = "0x597d11c05563611cb4ad4ed4c57ca53bbe3b7d3fefc37d1ef0724ad58904742b"
contract = "0x3BC6aA2D25313ad794b2D67f83f21D341cc3f5fb"
endBlock = 12995895
start = time.time()
# Step 1: Collect transactions
# Step 1.1: Collect transaction history using TrueBlocks
txHashes = collectTransactionHistory(contract, endBlock)
end = time.time()
print("Time elapsed for collecting transaction history: ", end - start, "s")
# Step 1.2: Download history transaction traces from QuickNode
start = time.time()
for tx in txHashes:
storeATrace(tx)
pathList = []
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
for tx in txHashes:
path = SCRIPT_DIR + "/cache/" + tx + ".json.gz"
pathList.append(path)
end = time.time()
print("Time elapsed for downloading transaction traces: ", end - start, "s")
changeLoggingUpperBound(1000)
time.sleep(1)
# Step 1: Fetch a transaction trace
start = time.time()
for txHash in txHashes:
temp = readATrace(txHash)
# Step 2: Parse the transaction trace
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
path = SCRIPT_DIR + "/cache/" + txHash + ".json.gz"
metaTraceTree = analyzeOneTxGlobal(txHash, path)
metaTraceTree.hideUnnecessaryInfo()
end = time.time()
print("Time elapsed for parsing transaction traces: ", end - start, "s")
# Step 2: Parse the transactions and Collect Invariant Related Data
start = time.time()
# Suppose target contract is A
# LoggingUpperBound set to x means
# starting from A's depth a, all functions calls of depth a+x will be logged
changeLoggingUpperBound(8)
# The followings are a list of locators for locating the external call functions inside the target contract that are related to deposit, invest, and withdraw
# This is used for dataFlow invariant inference of Trace2Inv
# a locator is used to define where a transfer happens
# l1: deposit locator - when a user deposits their funds into the contract
# l2: invest locator - when the contract invests the funds to another DeFi protocol
# l3: withdraw locator - when a user withdraws their funds from the contract
l1 = []
l2 = []
l3 = [
locator("withdrawTo", FUNCTION, fromAddr = "0x3bc6aa2d25313ad794b2d67f83f21d341cc3f5fb", funcAddress = "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", \
name="transfer", position=1),
locator("withdrawToForge", FUNCTION, fromAddr = "0x3bc6aa2d25313ad794b2d67f83f21d341cc3f5fb", funcAddress = "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", \
name="transfer", position=1),
]
# The following code extracts invariant-related data from the transactions
for ii in range(len(txHashes)):
# if readAccessList(contract, txHashes[ii]) != []:
# continue
start = time.time()
dataSourceMapList, accessList, splitedTraceTree = analyzeOneTx(contract, txHashes[ii], pathList[ii], l1, l2, l3)
writeDataSource(contract, txHashes[ii], dataSourceMapList)
writeAccessList(contract, txHashes[ii], accessList)
writeSplitedTraceTree(contract, txHashes[ii], splitedTraceTree)
end = time.time() - start
print("Time elapsed for analyzing tx: ", txHashes[ii], " ", end, "s")
accesslistTable = []
accesslistList = []
executionListTable = []
executionListList = []
# Here we use 70% of the data as training data, same as in Trace2Inv Paper
trainingSetSize = int(0.7 * len(txHashes))
# read the data source map list
for ii in range( len(txHashes) ):
accessList = readAccessList(contract, txHashes[ii])
if len(accessList) > 0:
accesslistList.append( (txHashes[ii], accessList) )
if len(accessList) == 1 and len(accessList[0]) == 0:
print("no access for tx: ", txHashes[ii])
accesslistTable.append( (contract, accesslistList) )
# read the data source map list
for ii in range( trainingSetSize ):
executionList = readDataSource(contract, txHashes[ii])
if len(executionList) > 0 and len(executionList[0]) > 0:
for execution in executionList[0]:
executionListList.append( (txHashes[ii], execution) )
executionListTable.append( (contract, executionListList) )
end = time.time() - start
print("Time elapsed for extracting invariant-related data: ", end, "s")
start = time.time()
# Invariant Category 1: Access Control
print("=====================================================")
print("=============== Access Control ======================")
print("=====================================================")
inferAccessControl(accesslistTable)
# Invariant Category 2: Time Locks
print("=====================================================")
print("=================== Time Locks ======================")
print("=====================================================")
# enterFuncs represent the functions that a user can deposit their funds into
enterFuncs = []
# exitFuncs represent the functions that a user can withdraw their funds from
exitFuncs = ['withdrawAllToForge', 'withdrawTo', 'withdrawToForge']
inferTimeLocks(accesslistTable, enterFuncs, exitFuncs)
# Invariant Category 3: Gas Control
print("=====================================================")
print("=================== Gas Control =====================")
print("=====================================================")
inferGasControl(accesslistTable)
# Invariant Category 4: Re-entrancy
print("=====================================================")
print("=================== Re-entrancy =====================")
print("=====================================================")
enterFuncs = []
exitFuncs = ['withdrawAllToForge', 'withdrawTo', 'withdrawToForge']
inferReentrancy(accesslistTable, enterFuncs, exitFuncs)
# Invariant Category 5: Special Storage
print("=====================================================")
print("================ Special Storage ====================")
print("=====================================================")
inferSpecialStorage(accesslistTable)
# Invariant Category 6: Oracle Control
# Only the following benchmarks use an oracle
# Punk_1 does not use an oracle, but the code is still here for reference
# # benchmarks = ["bZx2", "Warp_interface", "CheeseBank_1", "CheeseBank_2", "CheeseBank_3", "InverseFi", \
# # "CreamFi2_1", "CreamFi2_2", "CreamFi2_3", "CreamFi2_4", "Harvest1_fUSDT", "Harvest2_fUSDC", \
# # "ValueDeFi"]
# inferOracleRange(benchmarks)
executionListTable = reformatExecutionTable(executionListTable)
# Invariant Category 7: DataFlow
print("=====================================================")
print("=================== DataFlow ========================")
print("=====================================================")
enterFuncs = []
exitFuncs = ['withdrawAllToForge', 'withdrawTo', 'withdrawToForge']
inferDataFlows(executionListTable, enterFuncs, exitFuncs)
# Invariant Category 8: MoneyFlow
print("=====================================================")
print("=================== MoneyFlow =======================")
print("=====================================================")
# transferToken is the token that is being transferred, which we try to restrict
transferToken = "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"
inferMoneyFlows(executionListTable, contract, transferToken)
end = time.time() - start
print("Time elapsed for inferring invariants: ", end, "s")
start = time.time()
for txHash in txHashes:
# step 2: read the trace and translate it to TxSpector desired format
trace = readATrace(txHash)
translated = TxSpectorTranslator().parseLogs(trace)
end = time.time() - start
print("Time elapsed for translating logs: ", end, "s")
def main():
# Feature 0: Given a transaction hash, fetch and parse the transaction trace
feature0()
# Feature 1: Given a target contract, collect all transactions related to the contract.
# Collect all snippets of the transactions related to the target contract, collect invariant-related data, generate invariants
# feature1()
## feature3()
##collectTraceAndInvariants(contract="0xe952bda8c06481506e4731c4f54ced2d4ab81659", endBlock=14465357, l1=[], l2=[], l3=[])
def feature0():
# ==========================================================================
# Feature 0: Given a transaction hash, fetch and parse the transaction trace
# ==========================================================================
changeLoggingUpperBound(1000)
# time.sleep(1)
# Step 1: Fetch a transaction trace
txHash = "0xed2e82bb59e2ea39bfdc7d08ae2f7fcad7200e00163f6e3440b9a5d72fc3ef5d"
storeATrace(txHash)
temp = readATrace(txHash)
# print(temp)
for ii in range(0, 10):
print(temp['structLogs'][ii])
# 0x464c71f6c2f760dda6093dcb91c24c39e5d6e18c
# contracts = ["0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2", "0x8164Cc65827dcFe994AB23944CBC90e0aa80bFcb", "0x2f39d218133AFaB8F2B819B1066c7E434Ad94E9e", "0x54586bE62E3c3580375aE3723C145253060Ca0C2"]
# strstr = str(temp).lower()
# for contract in contracts:
# if contract.lower() in strstr:
# print("Contract Found: ", contract)
# else:
# print("not found")
# Step 2: Parse the transaction trace
print("=================== Trace Tree =====================")
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
path = SCRIPT_DIR + "/cache/" + txHash + ".json.gz"
metaTraceTree = analyzeOneTxGlobal(txHash, path)
print(metaTraceTree.visualizeASE())
# Step 3: Decode function ABI and Storage Accesses (dynamically track SHA3)
print("=================== Decoded Trace Tree =====================")
metaTraceTree.decodeABIStorage(temp['structLogs'])
print(metaTraceTree.visualizeASE_decoded())
def feature1():
# ==========================================================================
# Feature 1: Given a target contract, collect all transactions related to the contract.
# Collect all snippets of the transactions related to the target contract and collect invariant-related data.
# ==========================================================================
# Punk_1
# hackTx = "0x597d11c05563611cb4ad4ed4c57ca53bbe3b7d3fefc37d1ef0724ad58904742b"
contract = "0x3BC6aA2D25313ad794b2D67f83f21D341cc3f5fb"
endBlock = 12995895
# Step 1: Collect transactions
# Step 1.1: Collect transaction history using TrueBlocks
txHashes = collectTransactionHistory(contract, endBlock)
print("total transactions: ", len(txHashes))
# Step 1.2: Download history transaction traces from QuickNode
for tx in txHashes:
storeATrace(tx)
pathList = []
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
for tx in txHashes:
path = SCRIPT_DIR + "/cache/" + tx + ".json.gz"
pathList.append(path)
# Step 2: Parse the transactions and Collect Invariant Related Data
# Suppose target contract is A
# LoggingUpperBound set to x means
# starting from A's depth a, all functions calls of depth a+x will be logged
changeLoggingUpperBound(8)
# The followings are a list of locators for locating the external call functions inside the target contract that are related to deposit, invest, and withdraw
# This is used for dataFlow invariant inference of Trace2Inv
# a locator is used to define where a transfer happens
# l1: deposit locator - when a user deposits their funds into the contract
# l2: invest locator - when the contract invests the funds to another DeFi protocol
# l3: withdraw locator - when a user withdraws their funds from the contract
l1 = []
l2 = []
l3 = [
locator("withdrawTo", FUNCTION, fromAddr = "0x3bc6aa2d25313ad794b2d67f83f21d341cc3f5fb", funcAddress = "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", \
name="transfer", position=1),
locator("withdrawToForge", FUNCTION, fromAddr = "0x3bc6aa2d25313ad794b2d67f83f21d341cc3f5fb", funcAddress = "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", \
name="transfer", position=1),
]
# create folders for storing cached invariant-related data
path1 = SCRIPT_DIR + "/cache/" + contract
path2 = SCRIPT_DIR + "/cache/" + contract + "_Access"
path3 = SCRIPT_DIR + "/cache/" + contract + "_SplitedTraceTree"
for path in [path1, path2, path3]:
if not os.path.exists(path):
os.makedirs(path)
# The following code extracts invariant-related data from the transactions
for ii in range(len(txHashes)):
# if readAccessList(contract, txHashes[ii]) != []:
# continue
dataSourceMapList, accessList, splitedTraceTree = analyzeOneTx(contract, txHashes[ii], pathList[ii], l1, l2, l3)
writeDataSource(contract, txHashes[ii], dataSourceMapList)
writeAccessList(contract, txHashes[ii], accessList)
writeSplitedTraceTree(contract, txHashes[ii], splitedTraceTree)
accesslistTable = []
accesslistList = []
executionListTable = []
executionListList = []
# Here we use 70% of the data as training data, same as in Trace2Inv Paper
trainingSetSize = int(0.7 * len(txHashes))
# read the data source map list
for ii in range( len(txHashes) ):
accessList = readAccessList(contract, txHashes[ii])
if len(accessList) > 0:
accesslistList.append( (txHashes[ii], accessList) )
if len(accessList) == 1 and len(accessList[0]) == 0:
print("no access for tx: ", txHashes[ii])
accesslistTable.append( (contract, accesslistList) )
# read the data source map list
for ii in range( trainingSetSize ):
executionList = readDataSource(contract, txHashes[ii])
if len(executionList) > 0 and len(executionList[0]) > 0:
for execution in executionList[0]:
executionListList.append( (txHashes[ii], execution) )
executionListTable.append( (contract, executionListList) )
# Invariant Category 1: Access Control
print("=====================================================")
print("=============== Access Control ======================")
print("=====================================================")
inferAccessControl(accesslistTable)
# Invariant Category 2: Time Locks
print("=====================================================")
print("=================== Time Locks ======================")
print("=====================================================")
# enterFuncs represent the functions that a user can deposit their funds into
enterFuncs = []
# exitFuncs represent the functions that a user can withdraw their funds from
exitFuncs = ['withdrawAllToForge', 'withdrawTo', 'withdrawToForge']
inferTimeLocks(accesslistTable, enterFuncs, exitFuncs)
# Invariant Category 3: Gas Control
print("=====================================================")
print("=================== Gas Control =====================")
print("=====================================================")
inferGasControl(accesslistTable)
# Invariant Category 4: Re-entrancy
print("=====================================================")
print("=================== Re-entrancy =====================")
print("=====================================================")
enterFuncs = []
exitFuncs = ['withdrawAllToForge', 'withdrawTo', 'withdrawToForge']
inferReentrancy(accesslistTable, enterFuncs, exitFuncs)
# Invariant Category 5: Special Storage
print("=====================================================")
print("================ Special Storage ====================")
print("=====================================================")
inferSpecialStorage(accesslistTable)
# Invariant Category 6: Oracle Control
# Only the following benchmarks use an oracle
# Punk_1 does not use an oracle, but the code is still here for reference
# # benchmarks = ["bZx2", "Warp_interface", "CheeseBank_1", "CheeseBank_2", "CheeseBank_3", "InverseFi", \
# # "CreamFi2_1", "CreamFi2_2", "CreamFi2_3", "CreamFi2_4", "Harvest1_fUSDT", "Harvest2_fUSDC", \
# # "ValueDeFi"]
# inferOracleRange(benchmarks)
executionListTable = reformatExecutionTable(executionListTable)
# Invariant Category 7: DataFlow
print("=====================================================")
print("=================== DataFlow ========================")
print("=====================================================")
enterFuncs = []
exitFuncs = ['withdrawAllToForge', 'withdrawTo', 'withdrawToForge']
inferDataFlows(executionListTable, enterFuncs, exitFuncs)
# Invariant Category 8: MoneyFlow
print("=====================================================")
print("=================== MoneyFlow =======================")
print("=====================================================")
# transferToken is the token that is being transferred, which we try to restrict
transferToken = "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"
inferMoneyFlows(executionListTable, contract, transferToken)
def collectTraceAndInvariants(contract, endBlock, l1 ,l2, l3):
changeLoggingUpperBound(8)
# ==========================================================================
# Feature 1: Given a target contract, collect all transactions related to the contract.
# Collect all snippets of the transactions related to the target contract and collect invariant-related data.
# ==========================================================================
# Punk_1
# Step 1: Collect transactions
# Step 1.1: Collect transaction history using TrueBlocks
txHashes = collectTransactionHistory(contract, endBlock)
print("total transactions: ", len(txHashes))
# Step 1.2: Download history transaction traces from QuickNode
for tx in txHashes:
storeATrace(tx)
pathList = []
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
for tx in txHashes:
path = SCRIPT_DIR + "/cache/" + tx + ".json.gz"
pathList.append(path)
# Step 2: Parse the transactions and Collect Invariant Related Data
# Suppose target contract is A
# LoggingUpperBound set to x means
# starting from A's depth a, all functions calls of depth a+x will be logged
changeLoggingUpperBound(8)
# The followings are a list of locators for locating the external call functions inside the target contract that are related to deposit, invest, and withdraw
# This is used for dataFlow invariant inference of Trace2Inv
# a locator is used to define where a transfer happens
# l1: deposit locator - when a user deposits their funds into the contract
# l2: invest locator - when the contract invests the funds to another DeFi protocol
# l3: withdraw locator - when a user withdraws their funds from the contract
# create folders for storing cached invariant-related data
setUpDirectories(script_dir=SCRIPT_DIR, contract=contract)
# The following code extracts invariant-related data from the transactions
for ii in range(len(txHashes)):
print(txHashes[ii])
# if readAccessList(contract, txHashes[ii]) != []:
# continue
dataSourceMapList, accessList, splitedTraceTree = analyzeOneTx(contract, txHashes[ii], pathList[ii], l1, l2, l3)
writeDataSource(contract, txHashes[ii], dataSourceMapList)
writeAccessList(contract, txHashes[ii], accessList)
writeSplitedTraceTree(contract, txHashes[ii], splitedTraceTree)
accesslistTable = []
accesslistList = []
executionListTable = []
executionListList = []
# Here we use 70% of the data as training data, same as in Trace2Inv Paper
trainingSetSize = int(0.7 * len(txHashes))
# read the data source map list
for ii in range( len(txHashes) ):
accessList = readAccessList(contract, txHashes[ii])
if len(accessList) > 0:
accesslistList.append( (txHashes[ii], accessList) )
if len(accessList) == 1 and len(accessList[0]) == 0:
print("no access for tx: ", txHashes[ii])
accesslistTable.append( (contract, accesslistList) )
# read the data source map list
for ii in range( trainingSetSize ):
executionList = readDataSource(contract, txHashes[ii])
if len(executionList) > 0 and len(executionList[0]) > 0:
for execution in executionList[0]:
executionListList.append( (txHashes[ii], execution) )
executionListTable.append( (contract, executionListList) )
# Invariant Category 1: Access Control
print("=====================================================")
print("=============== Access Control ======================")
print("=====================================================")
inferAccessControl(accesslistTable)
# Invariant Category 2: Time Locks
print("=====================================================")
print("=================== Time Locks ======================")
print("=====================================================")
# enterFuncs represent the functions that a user can deposit their funds into
enterFuncs = []
# exitFuncs represent the functions that a user can withdraw their funds from
exitFuncs = ['withdrawAllToForge', 'withdrawTo', 'withdrawToForge']
inferTimeLocks(accesslistTable, enterFuncs, exitFuncs)
# Invariant Category 3: Gas Control
print("=====================================================")
print("=================== Gas Control =====================")
print("=====================================================")
inferGasControl(accesslistTable)
# Invariant Category 4: Re-entrancy
print("=====================================================")
print("=================== Re-entrancy =====================")
print("=====================================================")
enterFuncs = []
exitFuncs = ['withdrawAllToForge', 'withdrawTo', 'withdrawToForge']
inferReentrancy(accesslistTable, enterFuncs, exitFuncs)
# Invariant Category 5: Special Storage
print("=====================================================")
print("================ Special Storage ====================")
print("=====================================================")
inferSpecialStorage(accesslistTable)
# Invariant Category 6: Oracle Control
# Only the following benchmarks use an oracle
# Punk_1 does not use an oracle, but the code is still here for reference
# # benchmarks = ["bZx2", "Warp_interface", "CheeseBank_1", "CheeseBank_2", "CheeseBank_3", "InverseFi", \
# # "CreamFi2_1", "CreamFi2_2", "CreamFi2_3", "CreamFi2_4", "Harvest1_fUSDT", "Harvest2_fUSDC", \
# # "ValueDeFi"]
# inferOracleRange(benchmarks)
executionListTable = reformatExecutionTable(executionListTable)
# Invariant Category 7: DataFlow
print("=====================================================")
print("=================== DataFlow ========================")
print("=====================================================")
enterFuncs = []
exitFuncs = ['withdrawAllToForge', 'withdrawTo', 'withdrawToForge']
inferDataFlows(executionListTable, enterFuncs, exitFuncs)
# # Invariant Category 8: MoneyFlow
# print("=====================================================")
# print("=================== MoneyFlow =======================")
# print("=====================================================")
# # transferToken is the token that is being transferred, which we try to restrict
# transferToken = "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"
# inferMoneyFlows(executionListTable, contract, transferToken)
if __name__ == '__main__':
main()
# mainTestTime()
def feature2():
# ==========================================================================
# Feature 2: Given a transaction, collect logs from debug_traceTransaction RPC call,
# translate the logs into other logs required by other tools.
# aims to replace the modified Geth part in other tools
# ==========================================================================
# this is the example transaction used as a demo in TxSpector repository https://github.com/OSUSecLab/TxSpector
txHash = "0x37085f336b5d3e588e37674544678f8cb0fc092a6de5d83bd647e20e5232897b"
# step 1: fetch the trace
storeATrace(txHash)
# step 2: read the trace and translate it to TxSpector desired format
trace = readATrace(txHash)
translated = TxSpectorTranslator().parseLogs(trace)
with open ("TxSpectorTranslator/Trace2InvTranslated.txt", "w") as f:
f.write(translated)
# step 3: compare translated result with ground truth, which is the demo input of TxSpector
# placed in TxSpectorTranslator/0x37085f336b5d3e588e37674544678f8cb0fc092a6de5d83bd647e20e5232897b.txt
# original file at https://github.com/OSUSecLab/TxSpector/blob/master/example/0x37085f336b5d3e588e37674544678f8cb0fc092a6de5d83bd647e20e5232897b.txt
groundTruth = None
with open ("TxSpectorTranslator/0x37085f336b5d3e588e37674544678f8cb0fc092a6de5d83bd647e20e5232897b.txt", "r") as f:
groundTruth = f.read()
if translated == groundTruth + "\n":
print("The translated result of Trace2Inv is the same as the input required by TxSpector")
else:
print("The translated result of Trace2Inv is different from the input required by TxSpector")