This repository was archived by the owner on May 17, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1706 lines (1398 loc) · 73.4 KB
/
Copy pathmain.py
File metadata and controls
1706 lines (1398 loc) · 73.4 KB
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 os
import sys
import re
import json
import creds
import shutil
import requests
import subprocess
import numpy as np
import pandas as pd
from PyQt5 import QtGui
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from graphviz import Source
from datetime import datetime
from PyQt5.QtWidgets import *
from bs4 import BeautifulSoup
from termcolor import colored
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from pyvis.network import Network
from matplotlib import image as mpimg
from PyQt5.QtWebEngineWidgets import *
from PyQt5.QtWidgets import QFileDialog
from PyQt5.QtNetwork import QHostAddress
from sklearn.impute import SimpleImputer
from sklearn.ensemble import IsolationForest
from PyQt5.QtWebSockets import QWebSocketServer
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Spyder")
self.setGeometry(100, 100, 1350, 800)
icon = QIcon(r"Icons\app.png")
self.setWindowIcon(icon)
toolbar = QToolBar()
self.addToolBar(toolbar)
self.setStyleSheet("""
QMainWindow {
background-color: white;
}
QSplitter::handle {
background-color: white;
}
QScrollBar:vertical {
background-color: #F0F0F0;
width: 12px;
}
QScrollBar::handle:vertical {
background-color: #CCCCCC;
border-radius: 6px;
}
QScrollBar::add-line:vertical,
QScrollBar::sub-line:vertical {
background-color: #F0F0F0;
}
QScrollBar:horizontal {
background-color: #F0F0F0;
height: 12px;
}
QScrollBar::handle:horizontal {
background-color: #CCCCCC;
border-radius: 6px;
}
QScrollBar::add-line:horizontal,
QScrollBar::sub-line:horizontal {
background-color: #F0F0F0;
}
""")
menu_bar = self.menuBar()
file_menu = QMenu("File", self)
menu_bar.addMenu(file_menu)
self.save_action = QAction("&Save Project", self)
self.save_action.triggered.connect(self.SaveProject)
file_menu.addAction(self.save_action)
self.save_action.setEnabled(False)
load_action = QAction("&Load Project", self)
load_action.triggered.connect(self.LoadProject)
file_menu.addAction(load_action)
help_menu = QMenu("About", self)
menu_bar.addMenu(help_menu)
ver_action = QAction("&Version", self)
help_menu.addAction(ver_action)
ver_action.triggered.connect(self.applicationInfo)
button1 = QAction(QIcon(r"Icons\search.png"), "Search Wallet Address", self)
button1.triggered.connect(self.search_address_popup)
self.button2 = QAction(QIcon(r"Icons\timeline.png"), "Timeline Graph", self)
self.button2.triggered.connect(lambda: self.get_transactions(self.current_tab, 'Timeline'))
self.button3 = QAction(QIcon(r"Icons\profile.png"), "Search Profile", self)
self.button3.triggered.connect(self.show_ProfileWindow)
self.button4 = QAction(QIcon(r"Icons\crosshair.png"), "Crosshair", self)
self.button4.triggered.connect(self.flag_suspicious_activity)
self.button5 = QAction(QIcon(r"Icons\Transaction.png"), "Find Transaction", self)
self.button5.triggered.connect(self.show_TransactionWindow)
self.button6 = QAction(QIcon(r"Icons\filter.png"), "Filter Information", self)
self.button6.triggered.connect(self.Filter)
self.SaveButton = QAction(QIcon(r"Icons\save.png"), "Save", self)
self.SaveButton.triggered.connect(self.SaveProject)
self.LoadButton = QAction(QIcon(r"Icons\load.png"), "Load", self)
self.LoadButton.triggered.connect(self.LoadProject)
self.button2.setEnabled(False)
self.button3.setEnabled(True)
self.button4.setEnabled(False)
self.button6.setEnabled(False)
self.SaveButton.setEnabled(False)
toolbar.addAction(button1)
toolbar.addAction(self.SaveButton)
toolbar.addAction(self.LoadButton)
toolbar.addAction(self.button3)
toolbar.addAction(self.button5)
toolbar.addAction(self.button2)
toolbar.addAction(self.button4)
toolbar.addAction(self.button6)
self.search_bar = QLineEdit()
self.search_bar.setPlaceholderText("Search")
self.search_bar.setMaximumWidth(300)
self.search_bar.textChanged.connect(lambda text: self.Search(text, self.tab_widget.currentIndex()))
spacer = QWidget()
spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
toolbar.addWidget(spacer)
toolbar.addWidget(self.search_bar)
static_spacer = QWidget()
static_spacer.setFixedSize(10, 0)
toolbar.addWidget(static_spacer)
splitter = QSplitter(Qt.Horizontal)
self.web_widget = QWebEngineView()
self.web_widget.setMinimumSize(800, 300)
self.web_widget.setStyleSheet("background-color: white;")
self.web_widget.setFocusPolicy(Qt.NoFocus)
self.tab_widget = QTabWidget()
self.tab_widget.setMaximumHeight(800)
self.tab_widget.setTabEnabled(0, False)
self.tab_widget.setTabsClosable(True)
self.tab_widget.tabCloseRequested.connect(lambda index: self.remove_tab(index, self.tab_widget.tabText(index)))
self.tabs = []
self.tab_widget.currentChanged.connect(self.current_tab_name)
self.text_widget = QTextEdit()
self.text_widget.setMaximumHeight(100)
self.text_widget.setMaximumWidth(750)
table_text_widget = QWidget()
table_text_widget.setMaximumWidth(750)
table_text_layout = QVBoxLayout()
table_text_layout.addWidget(self.tab_widget)
table_text_layout.addWidget(self.text_widget)
table_text_widget.setLayout(table_text_layout)
splitter.addWidget(self.web_widget)
splitter.addWidget(table_text_widget)
splitter.setStretchFactor(0, 3)
splitter.setStretchFactor(1, 1)
self.setCentralWidget(splitter)
self.Visited = []
self.filter_values = {}
self.unique_values = {}
self.contracts = []
self.Parents = []
self.createContextMenu()
def remove_tab(self, tab_index, tab):
print(tab)
print(self.Visited)
self.Visited.remove(tab)
if not self.Visited:
self.web_widget.setHtml("")
else:
self.get_transactions(self.Visited[0])
self.tab_widget.removeTab(tab_index)
def Search(self, search_text, tab_index):
filtered_nodes = []
if search_text != '':
for index in range(self.tab_widget.count()):
tab_widget = self.tab_widget.widget(index)
if isinstance(tab_widget, QTableWidget):
table_widget = tab_widget
column_names = [table_widget.horizontalHeaderItem(column).text().lower() for column in range(table_widget.columnCount())]
from_column_index = column_names.index('from')
to_column_index = column_names.index('to')
date_column_index = column_names.index('date')
time_column_index = column_names.index('time')
value_column_index = column_names.index('value (eth)')
for row in range(table_widget.rowCount()):
visible = False
from_item = table_widget.item(row, from_column_index)
to_item = table_widget.item(row, to_column_index)
date_item = table_widget.item(row, date_column_index)
time_item = table_widget.item(row, time_column_index)
value_item = table_widget.item(row, value_column_index)
if from_item is not None and search_text.lower() in from_item.text().lower():
visible = True
filtered_nodes.append(from_item.text())
filtered_nodes.append(to_item.text())
elif to_item is not None and search_text.lower() in to_item.text().lower():
visible = True
filtered_nodes.append(from_item.text())
filtered_nodes.append(to_item.text())
elif date_item is not None and search_text in date_item.text():
visible = True
filtered_nodes.append(from_item.text())
filtered_nodes.append(to_item.text())
elif time_item is not None and search_text in time_item.text():
visible = True
filtered_nodes.append(from_item.text())
filtered_nodes.append(to_item.text())
elif value_item is not None and search_text in value_item.text():
visible = True
filtered_nodes.append(from_item.text())
filtered_nodes.append(to_item.text())
table_widget.setRowHidden(row, not visible)
else:
print("Invalid tab widget type")
self.create_graph(self.transactions, set(filtered_nodes))
else:
for index in range(self.tab_widget.count()):
tab_widget = self.tab_widget.widget(index)
if isinstance(tab_widget, QTableWidget):
table_widget = tab_widget
for row in range(table_widget.rowCount()):
table_widget.setRowHidden(row, False)
self.create_graph(self.transactions, None)
def current_tab_name(self, index):
self.current_tab = self.tab_widget.tabText(index)
def pan_zoom_handler(self, ax):
press = None
x0 = None
y0 = None
def connect():
nonlocal press, x0, y0
cidpress = ax.figure.canvas.mpl_connect('button_press_event', on_press)
cidrelease = ax.figure.canvas.mpl_connect('button_release_event', on_release)
cidmotion = ax.figure.canvas.mpl_connect('motion_notify_event', on_motion)
cidscroll = ax.figure.canvas.mpl_connect('scroll_event', on_scroll)
def on_press(event):
nonlocal press, x0, y0
if event.button == 1:
press = event.x, event.y
x0 = ax.get_xlim()
y0 = ax.get_ylim()
def on_release(event):
nonlocal press
if event.button == 1:
press = None
def on_motion(event):
nonlocal press
if press is None:
return
if event.button != 1:
return
dx = event.x - press[0]
dy = event.y - press[1]
scale_x = (x0[1] - x0[0]) / ax.bbox.width
scale_y = (y0[1] - y0[0]) / ax.bbox.height
ax.set_xlim(x0[0] - dx * scale_x, x0[1] - dx * scale_x)
ax.set_ylim(y0[0] - dy * scale_y, y0[1] - dy * scale_y)
ax.figure.canvas.draw_idle()
def on_scroll(event):
if event.button == 'up':
_zoom(0.9)
elif event.button == 'down':
_zoom(1.1)
def _zoom(zoom_factor):
nonlocal x0, y0
x_center = np.mean(ax.get_xlim())
y_center = np.mean(ax.get_ylim())
ax.set_xlim(x_center - (x_center - ax.get_xlim()[0]) * zoom_factor,
x_center + (ax.get_xlim()[1] - x_center) * zoom_factor)
ax.set_ylim(y_center - (y_center - ax.get_ylim()[0]) * zoom_factor,
y_center + (ax.get_ylim()[1] - y_center) * zoom_factor)
ax.figure.canvas.draw_idle()
connect()
def create_timeline(self, transactions, address):
dates = [datetime.fromtimestamp(int(tx['timeStamp'])) for tx in transactions]
dates_sorted = sorted(dates)
levels = np.tile([-0.6, 0.6, -0.4, 0.4, -0.2, 0.2],
int(np.ceil(len(dates_sorted) / 6)))[:len(dates_sorted)]
fig, ax = plt.subplots(figsize=(14, 6), constrained_layout=True)
ax.vlines(dates_sorted, 0, levels, color="k")
ax.plot(dates_sorted, np.zeros_like(dates_sorted), "-o",
color="k", markerfacecolor="w")
for d, l, tx in zip(dates, levels, transactions):
amount = float(tx['value']) / 10 ** 18
timestamp = int(tx['timeStamp'])
date = datetime.fromtimestamp(timestamp)
formatted_date = date.strftime("%d/%m/%y")
formatted_time = date.strftime("%I:%M %p")
annotation = None
if tx['from'].lower() == address.lower():
annotation = f"(Sent)\nAmount: {amount:.2f} ETH\nDate: {formatted_date}\nTime: {formatted_time}"
else:
annotation = f"(Received)\nAmount: {amount:.2f} ETH\nDate: {formatted_date}\nTime: {formatted_time}"
bbox_props = dict(boxstyle="round", fc="w", ec="gray", lw=0.5)
ax.annotate(annotation, xy=(d, l),
xytext=(-3, np.sign(l) * 2), textcoords="offset points",
fontsize=7,
ha='center',
va='top',
bbox=bbox_props)
ax.xaxis.set_major_locator(mdates.DayLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter("%d %b '%y"))
plt.setp(ax.get_xticklabels(), rotation=90, ha="right", fontsize=8)
ax.yaxis.set_visible(False)
ax.spines[["left", "top", "right"]].set_visible(False)
num_values_to_show = 7
if len(dates_sorted) >= num_values_to_show:
ax.set_xlim(dates_sorted[0], dates_sorted[num_values_to_show - 1])
else:
ax.set_xlim(dates_sorted[0], dates_sorted[-1])
self.pan_zoom_handler(ax)
plt.gcf().canvas.setWindowTitle("Timeline For" + address)
plt.show()
def SaveProject(self):
folder_path = QFileDialog.getExistingDirectory(self, "Select Directory")
if folder_path:
now = datetime.now()
folder_name = now.strftime("%Y-%m-%d_%H-%M-%S")
folder_path = os.path.join(folder_path, folder_name)
os.makedirs(folder_path)
for tab_index in range(self.tab_widget.count()):
table_widget = self.tab_widget.widget(tab_index)
df = pd.DataFrame(columns=[table_widget.horizontalHeaderItem(col).text() for col in range(table_widget.columnCount())])
table_name = self.tab_widget.tabText(tab_index)
for row in range(table_widget.rowCount()):
row_data = []
for col in range(table_widget.columnCount()):
item = table_widget.item(row, col)
if item is not None:
row_data.append(item.text())
else:
row_data.append('')
df.loc[len(df)] = row_data
file_name = f"{table_name}.xlsx"
file_path = os.path.join(folder_path, file_name)
df.to_excel(file_path, index=False)
graph_file_name = "graph.html"
graph_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), graph_file_name)
shutil.copy(graph_file_path, folder_path)
icons_folder_name = "Icons"
icons_folder_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), icons_folder_name)
shutil.copytree(icons_folder_path, os.path.join(folder_path, icons_folder_name))
QMessageBox.information(self, "Save", "Project saved successfully.")
def LoadProject(self):
folder_path = QFileDialog.getExistingDirectory(self, "Select Directory")
if folder_path:
self.tab_widget.clear()
graph_file_name = "graph.html"
graph_file_path = os.path.join(folder_path, graph_file_name)
main_directory = os.path.dirname(os.path.abspath(__file__))
main_graph_file_path = os.path.join(main_directory, graph_file_name)
shutil.copy(graph_file_path, main_graph_file_path)
self.web_widget.load(QUrl.fromLocalFile(main_graph_file_path))
excel_files = [file for file in os.listdir(folder_path) if file.endswith(".xlsx")]
for excel_file in excel_files:
file_path = os.path.join(folder_path, excel_file)
table_name = os.path.splitext(excel_file)[0]
df = pd.read_excel(file_path)
self.get_transactions(table_name, 'Load')
table_widget = QTableWidget()
table_widget.setMinimumSize(500, 500)
table_widget.setMaximumWidth(750)
table_widget.setEditTriggers(QAbstractItemView.NoEditTriggers)
table_widget.cellClicked.connect(self.RowSelection)
table_widget.setSelectionBehavior(QAbstractItemView.SelectRows)
table_widget.setSelectionMode(QAbstractItemView.ExtendedSelection)
table_widget.setColumnCount(df.shape[1])
table_widget.setRowCount(df.shape[0])
table_widget.setHorizontalHeaderLabels(df.columns)
for row in range(df.shape[0]):
for col in range(df.shape[1]):
item = QTableWidgetItem(str(df.iloc[row, col]))
table_widget.setItem(row, col, item)
header = table_widget.horizontalHeaderItem(col).text()
value = item.text()
if header not in self.unique_values:
self.unique_values[header] = set()
self.unique_values[header].add(value)
self.tab_widget.addTab(table_widget, table_name)
self.enable_buttons()
QMessageBox.information(self, "Load", "Project loaded successfully.")
def Filter(self):
dialog = QDialog(self)
layout = QFormLayout()
for key, values in self.unique_values.items():
if key == 'Time':
start_label = QLabel('Start ' + key)
end_label = QLabel('End ' + key)
start_time_layout = QHBoxLayout()
end_time_layout = QHBoxLayout()
start_time = QComboBox()
start_time.addItems(['All'] + [str(i) for i in range(1, 13)])
start_time.setCurrentIndex(self.filter_values.get(key, 0))
start_time_layout.addWidget(start_time)
end_time = QComboBox()
end_time.addItems(['All'] + [str(i) for i in range(1, 13)])
end_time.setCurrentIndex(self.filter_values.get(key + '_end', 0))
end_time_layout.addWidget(end_time)
start_am_pm = QComboBox()
start_am_pm.addItems(['AM', 'PM'])
end_am_pm = QComboBox()
end_am_pm.addItems(['AM', 'PM'])
start_time_layout.addWidget(start_am_pm)
end_time_layout.addWidget(end_am_pm)
layout.addRow(start_label, start_time_layout)
layout.addRow(end_label, end_time_layout)
# start_time.currentIndexChanged.connect(lambda value, key=key: self.filter_values.update({key: value}))
# end_time.currentIndexChanged.connect(lambda value, key=key + '_end': self.filter_values.update({key: value}))
# am_pm.currentIndexChanged.connect(lambda value, key=key + '_am_pm': self.filter_values.update({key: value}))
elif key == 'Date':
date_layout = QHBoxLayout()
label = QLabel(key)
start_date = QComboBox()
start_date.addItems(['All'] + list(values))
start_date.setCurrentIndex(self.filter_values.get(key, 0))
end_date = QComboBox()
end_date.addItems(['All'] + list(values))
end_date.setCurrentIndex(self.filter_values.get(key, 0))
date_layout.addWidget(start_date)
date_layout.addWidget(end_date)
layout.addRow(label, date_layout)
else:
label = QLabel(key)
combo_box = QComboBox()
combo_box.addItems(['All'] + list(values))
combo_box.setCurrentIndex(self.filter_values.get(key, 0))
layout.addRow(label, combo_box)
button_layout = QHBoxLayout()
FilterButton = QPushButton("Filter")
ClearButton = QPushButton("Clear All")
button_layout.addWidget(FilterButton)
button_layout.addWidget(ClearButton)
layout.addRow(button_layout)
dialog.setLayout(layout)
dialog.setWindowTitle("Filter")
dialog.show()
def applicationInfo(self):
dialog = QDialog(self)
dialog.setStyleSheet("background-color: white;")
dialog.setWindowTitle("Spyder")
dialog.setWindowIcon(QIcon(r"Icons\app.png"))
dialog.setFixedSize(500, 200)
layout = QVBoxLayout(dialog)
horizontal_layout = QHBoxLayout()
image_label = QLabel()
pixmap = QPixmap(r"Icons\appVersion.png")
resized_pixmap = pixmap.scaled(280, 300)
image_label.setPixmap(resized_pixmap)
horizontal_layout.addWidget(image_label)
text_label = QLabel("Spyder® 0.1\nBlockChain Forensics & Visualization Tool\nHuthaifa Mohammad")
horizontal_layout.addWidget(text_label)
layout.addLayout(horizontal_layout)
dialog.show()
def createContextMenu(self):
self.tab_widget.setContextMenuPolicy(Qt.CustomContextMenu)
self.tab_widget.customContextMenuRequested.connect(self.showContextMenu)
def showContextMenu(self, pos):
menu = QMenu(self)
analyze_transaction = menu.addAction("Analyze Transaction")
analyze_transaction.triggered.connect(self.AnalyzeTransaction)
remove = menu.addAction("Remove trasaction(s) from scope")
current_tab_index = self.tab_widget.currentIndex()
table_widget = self.tab_widget.widget(current_tab_index)
selection_model = table_widget.selectionModel()
selected_rows = [index.row() for index in selection_model.selectedRows()]
for row in selected_rows:
column = 5
item = table_widget.item(row, column)
if item is not None:
text = item.text()
if text:
self.hash = text
menu.exec_(self.tab_widget.mapToGlobal(pos))
def AnalyzeTransaction(self):
dialog = QDialog(self)
dialog.setWindowTitle("Transaction Analysis Window")
dialog.setWindowIcon(QIcon(r"Icons\app.png"))
dialog.setFixedSize(400, 550)
selected_transaction = None
for transaction in self.transactions:
if transaction['hash'] == self.hash:
selected_transaction = transaction
break
to = None
fromtext = None
if selected_transaction is not None:
layout = QFormLayout()
for key, value in selected_transaction.items():
if key == "from":
label = QLabel(key + ':')
text = QLineEdit()
text.setMaximumWidth(253)
text.setReadOnly(True)
text.setText(value)
button1 = QPushButton()
button1.setIcon(QIcon(r"Icons\analyze.png"))
button1.setMaximumWidth(30)
button1.setEnabled(True)
button1.setToolTip('Generate Profile Report')
fromtext = text.text()
hbox = QHBoxLayout()
hbox.addWidget(label)
hbox.addWidget(text)
hbox.addWidget(button1)
layout.addRow(hbox)
elif key == "to":
label = QLabel(key + ':')
text = QLineEdit()
text.setMaximumWidth(253)
text.setReadOnly(True)
text.setText(value)
button2 = QPushButton()
button2.setIcon(QIcon(r"Icons\analyze.png"))
button2.setMaximumWidth(30)
button2.setEnabled(True)
button2.setToolTip('Generate Profile Report')
to = text.text()
hbox = QHBoxLayout()
hbox.addWidget(label)
hbox.addWidget(text)
hbox.addWidget(button2)
layout.addRow(hbox)
elif key == "transactionIndex":
label = QLabel("Index:")
text = QLineEdit()
text.setMaximumWidth(300)
text.setReadOnly(True)
text.setText(value)
layout.addRow(label, text)
elif key == "cumulativeGasUsed":
label = QLabel("cGasUsed:")
text = QLineEdit()
text.setMaximumWidth(300)
text.setReadOnly(True)
text.setText(value)
layout.addRow(label, text)
else:
label = QLabel(key + ':')
text = QLineEdit()
text.setMaximumWidth(300)
text.setReadOnly(True)
text.setText(value)
layout.addRow(label, text)
dialog.setLayout(layout)
button1.clicked.connect(lambda: self.GenerateReport(fromtext))
button2.clicked.connect(lambda: self.GenerateReport(to))
dialog.show()
def SearchAddress(self, address, action):
Ethplorer_API = creds.Ethplorer_API
if action == 'Website':
url = f'https://api.ethplorer.io/getTokenInfo/{address}?apiKey={Ethplorer_API}'
elif action == 'Account':
url = f'https://api.ethplorer.io/getAddressInfo/{address}?apiKey={Ethplorer_API}&showETHTotals=true&showTxsCount=true'
elif action == 'Type':
Etherscan_API = creds.Etherscan_API
url = f'https://api.etherscan.io/api?module=contract&action=getcontractcreation&contractaddresses={address}&apikey={Etherscan_API}'
elif action == 'Transactions':
Etherscan_API = creds.Etherscan_API
url = f'https://api.etherscan.io/api?module=account&action=txlist&address={address}&apikey={Etherscan_API}'
elif action == 'Contracts':
Etherscan_API = creds.Etherscan_API
url = f'https://api.etherscan.io/api?module=account&action=txlistinternal&address={address}&startblock=0&endblock=99999999&page=1&offset=1000&sort=asc&apikey={Etherscan_API}'
try:
response = requests.get(url)
data = response.json()
return data
except requests.exceptions.RequestException as e:
print(f"Error occurred: {e}")
def GetAccountActivity(self, data):
if 'error' not in data:
AddressActivity = {}
Balances = {}
AddressActivity['Total In'] = "{:f}".format(data['ETH']['totalIn'])
AddressActivity['Total Out'] = "{:f}".format(data['ETH']['totalOut'])
AddressActivity['Transactions'] = data['countTxs']
Balances['ETH'] = {"balance": "{:f}".format(data['ETH']['balance']) + ' ETH'}
if 'tokens' in data:
for token in data['tokens']:
if 'name' in token['tokenInfo']:
token_name = token['tokenInfo']['name']
Balances[token_name] = {"balance": "{:f}".format(token['balance']) + ' ' + token['tokenInfo']['symbol']}
if 'image' in token['tokenInfo']:
Balances[token_name]['image'] = token['tokenInfo']['image']
return AddressActivity, Balances
else:
return None
def CheckType(self, data):
if data['status'] == '1':
wallet_type = 'Contract'
return wallet_type
else:
wallet_type = 'Address'
return wallet_type
def GetName(self, data):
if 'error' not in data:
wallet_tag = data['name']
return wallet_tag
else:
wallet_tag = ''
return wallet_tag
def GetCreator(self, data):
if data['status'] == '1':
result = data['result'][0]
ContractCreator = result['contractCreator']
return ContractCreator
else:
ContractCreator = ''
return ContractCreator
def GetWebsite(self, data):
if 'website' in data:
website = data['website']
return website
else:
website = ''
return website
def analyzeProfile(self, address):
self.GenerateReport(address)
def scrape_wallet_tag(self, address):
url = 'https://etherscan.io/address/' + address
headers = {
'Cookie': 'ASP.NET_SessionId=eosrt10a1bqudqgn1wdwsoqd; amp_fef1e8=a7e3b843-0b2f-4bf2-8d8f-bdc1fd42a17eR...1h37mraqn.1h37mraqr.3.2.5; __cuid=2c82c9af5ffc4323ab5db8acc49db778; __cflb=02DiuFnsSsHWYH8WqVXaqGvd6BSBaXQLTLDHf853rGYoN; __cf_bm=wHTcLBtrA85t2pyAQiUdcuFdCUPq.6nhqVCIpE7wbDQ-1687112319-0-AePicdKEFAxg7XXqMIOSVC0kcg7LxqtHo0Hbg9go/75bCmOp5QMZd3uyZOkx2ulAYw==',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/114.0',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate',
'Referer': 'https://etherscan.io/tx/0xeaf5423392c70d58e0bee7d93c0e972a7118fe17872279fb54306cee5d7ad30d',
'Dnt': '1',
'Upgrade-Insecure-Requests': '1',
'Sec-Fetch-Dest': 'document',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-Site': 'same-origin',
'Sec-Fetch-User': '?1',
'Sec-Gpc': '1',
'Te': 'trailers',
'Connection': 'close'
}
max_retries = 20
retry_count = 0
while retry_count < max_retries:
try:
response = requests.get(url, headers=headers)
content = response.text
soup = BeautifulSoup(response.content, 'html.parser')
title_tag = soup.title
if title_tag:
title = title_tag.string
title_parts = title.split('|')
if len(title_parts) > 2:
alert_type = ['danger', 'dark', 'warning']
for alert in alert_type:
alert_code = "<div class='alert alert-{} alert-dismissible fade show mb-3' role='alert'>".format(alert)
if alert_code in content:
lines = [line for line in content.split('\n') if alert_code in line]
for line in lines:
start_index = line.find(alert_code) + len(alert_code)
end_index = line.find("<button")
self.Tooltip = line[start_index:end_index]
wallet_owner = title_parts[0].strip() + ' (Suspicious)'
return wallet_owner
else:
wallet_owner = title_parts[0].strip()
return wallet_owner
break
except requests.exceptions.RequestException as e:
retry_count += 1
else:
print("Failed to establish a connection.")
def GenerateReport(self, address):
self.Tooltip = None
report = QDialog(self)
report.setWindowTitle(address)
report.setMaximumHeight(900)
report.setMinimumWidth(800)
report.setMaximumWidth(800)
scroll_area = QScrollArea()
scroll_area.setWidgetResizable(True)
widget = QWidget()
layout = QFormLayout(widget)
scroll_area.setWidget(widget)
wallet_tag = self.scrape_wallet_tag(address)
if wallet_tag != '' and wallet_tag is not None:
WalletOwnerLabel = QLabel(wallet_tag)
hbox = QHBoxLayout()
verified = QPushButton()
if 'Suspicious' in wallet_tag:
verified.setIcon(QIcon(r"Icons\caution.png"))
if self.Tooltip is not None:
verified.setToolTip(self.Tooltip)
else:
verified.setToolTip('Suspicious')
else:
verified.setIcon(QIcon(r"Icons\verified.png"))
verified.setToolTip('Verified')
verified.setMaximumWidth(30)
verified.setEnabled(True)
verified.setStyleSheet("color: white; background-color: transparent; border: none;")
hbox.addWidget(WalletOwnerLabel)
hbox.addWidget(verified)
hbox.setSpacing(0)
hbox.addStretch()
layout.addRow(hbox)
Website = self.SearchAddress(address, 'Website')
contract_website = self.GetWebsite(Website)
if contract_website != '' and contract_website is not None:
websiteLabel = QLabel('Website:')
websiteText = QLineEdit(contract_website)
layout.addRow(websiteLabel, websiteText)
self.verified_source_code = False
source_code = self.SourceCode(address)
WalletType = self.SearchAddress(address, 'Type')
wallet_type = self.CheckType(WalletType)
TypeLabel = QLabel('Type:')
TypeText = QLineEdit()
TypeText.setText(str(wallet_type))
if self.verified_source_code == True:
hbox2 = QHBoxLayout()
view_source = QPushButton()
view_source.setIcon(QIcon(r"Icons\source.png"))
view_source.setMaximumWidth(30)
view_source.setEnabled(True)
view_source.setToolTip('View Source Code')
view_source.clicked.connect(lambda: self.SourceCodeWindow(source_code))
TypeText.setMaximumWidth(241)
hbox2.addWidget(TypeLabel)
hbox2.addWidget(TypeText)
hbox2.addWidget(view_source)
layout.addRow(hbox2)
else:
layout.addRow(TypeLabel, TypeText)
WalletAddressLabel = QLabel('Address:')
WalletAddressText = QLineEdit()
WalletAddressText.setText(address)
layout.addRow(WalletAddressLabel, WalletAddressText)
contract_creator = self.GetCreator(WalletType)
if contract_creator != '' and contract_creator is not None:
hbox3 = QHBoxLayout()
AnalyzeProfile = QPushButton()
AnalyzeProfile.setIcon(QIcon(r"Icons\analyze.png"))
AnalyzeProfile.setMaximumWidth(30)
AnalyzeProfile.setEnabled(True)
AnalyzeProfile.setToolTip('Generate Profile Report')
AnalyzeProfile.clicked.connect(lambda: self.analyzeProfile(ContractCreatorText.text()))
ContractCreatorLabel = QLabel('Creator:')
ContractCreatorText = QLineEdit()
ContractCreatorText.setText(contract_creator)
ContractCreatorText.setMaximumWidth(241)
hbox3.addWidget(ContractCreatorLabel)
hbox3.addWidget(ContractCreatorText)
hbox3.addWidget(AnalyzeProfile)
layout.addRow(hbox3)
AccountData = self.SearchAddress(address, 'Account')
AccountActivity, Balances = self.GetAccountActivity(AccountData)
for key, value in AccountActivity.items():
Label = QLabel(key + ':')
Text = QLineEdit(str(value))
layout.addRow(Label, Text)
balances_scroll_area = QScrollArea()
balances_scroll_area.setWidgetResizable(True)
balances_widget = QWidget()
balances_layout = QFormLayout(balances_widget)
balances_scroll_area.setWidget(balances_widget)
for key, value in Balances.items():
Label = QLabel(key + ':')
Label.setMaximumWidth(100)
Text = QLineEdit(str(value['balance']))
balances_layout.addRow(Label, Text)
profile_groupbox = QGroupBox("Profile")
profile_layout = QVBoxLayout()
profile_layout.addWidget(widget)
profile_groupbox.setLayout(profile_layout)
balances_groupbox = QGroupBox("Balances")
balances_groupbox_layout = QVBoxLayout()
balances_groupbox_layout.addWidget(balances_scroll_area)
balances_groupbox.setLayout(balances_groupbox_layout)
main_layout = QHBoxLayout(report)
main_layout.addWidget(profile_groupbox)
main_layout.addWidget(balances_groupbox)
report.setLayout(main_layout)
report.show()
def GenerateGraph(self):
if os.path.isfile('inheritance') is True:
os.remove('inheritance')
os.system("slither contract.sol --print inheritance-graph")
graph_path = os.path.join(os.getcwd(), 'contract.sol.inheritance-graph.dot')
Graph = Source.from_file(graph_path)
Graph.render('Inheritance', format='jpg', view=True)
def SourceCodeWindow(self, code):
self.SourceCodeExplorer = QMainWindow(self)
self.SourceCodeExplorer.setWindowTitle('Source Code Analysis')
self.SourceCodeExplorer.setFixedSize(900, 800)
flags, strings = self.analyze_contract_source_code(code)
layout = QVBoxLayout()
toolbar = QToolBar()
relationship_graph_action = QAction(QIcon(r"Icons\relationship.png"), "Load", self)
relationship_graph_action.triggered.connect(self.GenerateGraph)
toolbar.addAction(relationship_graph_action)
self.SourceCodeExplorer.addToolBar(toolbar)
text_edit = QTextEdit()
text_edit.setStyleSheet("font-family: Cascadia Mono; font-size: 8pt;")
palette = text_edit.palette()
palette.setColor(QPalette.Text, QColor("white"))
palette.setColor(QPalette.Base, QColor("black"))
text_edit.setPalette(palette)
text_edit.setPlainText(code)
text_edit.setReadOnly(True)
layout.addWidget(text_edit)
self.highlight_suspicious_lines(text_edit, strings)
flag_text = QTextEdit()
flag_text.setMaximumHeight(200)
flag_text.setReadOnly(True)
flag_text.setStyleSheet("font-family: Cascadia Mono; font-size: 8pt;")
palette = flag_text.palette()
palette.setColor(QPalette.Text, QColor("red"))
palette.setColor(QPalette.Base, QColor("black"))
flag_text.setPalette(palette)
flags_with_symbol = [f"{flag}\n" for flag in flags]
flag_text.setPlainText("\n".join(flags_with_symbol))
layout.addWidget(flag_text)
central_widget = QWidget(self.SourceCodeExplorer)
central_widget.setLayout(layout)
self.SourceCodeExplorer.setCentralWidget(central_widget)
self.SourceCodeExplorer.show()
def highlight_suspicious_lines(self, text_edit, strings):
format = QTextCharFormat()
format.setBackground(QColor(226, 91, 116))