-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgui.py
More file actions
1215 lines (1094 loc) · 48.9 KB
/
Copy pathgui.py
File metadata and controls
1215 lines (1094 loc) · 48.9 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 queue
import threading
import tkinter as tk
from datetime import datetime
from tkinter import ttk, messagebox
import networkx as nx
import ttkbootstrap as tb
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib.patches as mpatches
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from api_clients import (
detect_chain,
get_btc_usd_price,
get_wallet_transactions,
)
from alerts import evaluate_transaction_alert
from exporter import export_png, export_report
from monitoring import WatchlistStore, poll_watchlist
from ransomware_db import (
check_wallet,
get_graph_reputation,
get_wallet_reputation,
summarize_graph_risk,
)
from simulated_data import SIMULATED_TRAIL
from tracker import BlockchainTracker
from utils import justify_simulation
# ---------------------------------------------------------------------------
# Premium dark theme palette
# ---------------------------------------------------------------------------
THEME = {
"bg": "#0a0e17",
"bg_panel": "#111827",
"bg_panel_2": "#0d1420",
"glass": "#151d2e",
"glass_border": "#243247",
"fg": "#e8edf4",
"fg_dim": "#8b98ab",
"accent_red": "#ff2d55",
"accent_amber": "#ffb547",
"accent_green": "#36d399",
"accent_cyan": "#22d3ee",
"neon_red": "#ff3b5c",
"neon_amber": "#ffb545",
"success": "#10b981",
"warning": "#f59e0b",
"danger": "#ef4444",
"node_victim": "#36d399",
"node_mixer": "#ff3b5c",
"node_trail": "#ffb547",
"node_noise": "#566274",
"node_label": "#ff7043",
"edge_regular": "#2c3d52",
"edge_path": "#ffb547",
"font_family": "Segoe UI",
}
RISK_COLORS = {"low": "#10b981", "medium": "#f59e0b", "high": "#ef4444"}
def truncate_address(address, head=8, tail=6):
"""Shorten a long address for display, e.g. 1A1zP1eP...vDivfNa."""
if len(address) <= head + tail + 3:
return address
return f"{address[:head]}...{address[-tail:]}"
class App:
"""
BlockTrace — Blockchain OSINT Ransomware Tracing Workbench.
A 3-pane premium dark dashboard:
- Left: OSINT threat feeds / risk intelligence
- Center: glowing fund-flow network graph with animated arrows
- Right: chronological transaction timeline with USD values
"""
def __init__(self, root):
self.root = root
self.tool_name = "BlockTrace"
self.root.title(f"{self.tool_name} — Blockchain OSINT Workbench")
self.root.geometry("1560x920")
self.root.minsize(1200, 760)
self.root.configure(bg=THEME["bg"])
# Async worker queue (background thread -> UI thread)
self._worker_queue = queue.Queue()
# State
self.previous_tx_count = 0
self.previous_wallet = None
self.watchlist_store = WatchlistStore()
self.current_report = None
self._worker = None
self._btc_usd_price = None
self._anim = None
self._loading = False
self._graph_metadata = None
self._build_styles()
self._build_ui()
self._poll_queue()
self._load_btc_price_async()
# ------------------------------------------------------------------
# Styling
# ------------------------------------------------------------------
def _build_styles(self):
style = tb.Style()
style.configure("TFrame", background=THEME["bg"])
style.configure(
"Panel.TFrame",
background=THEME["bg_panel_2"],
bordercolor=THEME["glass_border"],
)
style.configure(
"Glass.TFrame",
background=THEME["glass"],
bordercolor=THEME["glass_border"],
borderwidth=1,
)
style.configure(
"TLabel", background=THEME["bg"], foreground=THEME["fg"], font=(THEME["font_family"], 10)
)
style.configure(
"Panel.TLabel", background=THEME["bg_panel_2"], foreground=THEME["fg"]
)
style.configure(
"Header.TLabel", background=THEME["bg_panel_2"], foreground=THEME["fg"],
font=(THEME["font_family"], 14, "bold"),
)
style.configure(
"Title.TLabel", background=THEME["bg"], foreground=THEME["fg"],
font=(THEME["font_family"], 24, "bold"),
)
style.configure(
"Dim.TLabel", background=THEME["bg_panel_2"], foreground=THEME["fg_dim"],
font=(THEME["font_family"], 9),
)
style.configure(
"Amber.TLabel", background=THEME["glass"], foreground=THEME["neon_amber"],
font=(THEME["font_family"], 10, "bold"),
)
style.configure(
"Red.TLabel", background=THEME["glass"], foreground=THEME["neon_red"],
font=(THEME["font_family"], 10, "bold"),
)
style.configure(
"Green.TLabel", background=THEME["glass"], foreground=THEME["success"],
font=(THEME["font_family"], 10, "bold"),
)
style.configure(
"Metric.TLabel", background=THEME["bg_panel_2"], foreground=THEME["fg"],
font=(THEME["font_family"], 18, "bold"),
)
style.configure(
"MetricCaption.TLabel", background=THEME["bg_panel_2"],
foreground=THEME["fg_dim"], font=(THEME["font_family"], 8),
)
style.configure(
"TEntry", fieldbackground=THEME["bg_panel"], foreground=THEME["fg"],
bordercolor=THEME["glass_border"],
)
style.configure(
"Accent.TButton", background=THEME["accent_amber"], foreground="#0a0e17",
borderwidth=0, font=(THEME["font_family"], 10, "bold"),
)
style.configure(
"Action.TButton", background=THEME["glass"], foreground=THEME["fg"],
borderwidth=1, bordercolor=THEME["glass_border"],
)
style.configure(
"Danger.TButton", background=THEME["neon_red"], foreground="#ffffff",
borderwidth=0, font=(THEME["font_family"], 10, "bold"),
)
style.configure(
"Horizontal.TProgressbar", background=THEME["neon_amber"],
troughcolor=THEME["bg_panel"], bordercolor=THEME["glass_border"],
)
# ------------------------------------------------------------------
# UI Layout
# ------------------------------------------------------------------
def _build_ui(self):
# Root container
container = ttk.Frame(self.root, style="TFrame", padding=18)
container.pack(fill="both", expand=True)
# ===================== HEADER =====================
header = ttk.Frame(container, style="TFrame")
header.pack(fill="x", side="top", pady=(0, 12))
title_block = ttk.Frame(header, style="TFrame")
title_block.pack(side="left")
# Logo (if assets/logo.png exists)
self.logo_image = None
try:
base = os.path.dirname(__file__)
logo_path = os.path.join(base, "assets", "logo.png")
if os.path.exists(logo_path):
self.logo_image = tk.PhotoImage(file=logo_path)
ttk.Label(title_block, image=self.logo_image, style="TLabel").pack(side="left", padx=(0, 10))
except Exception:
self.logo_image = None
ttk.Label(title_block, text=self.tool_name, style="Title.TLabel").pack(side="left")
ttk.Label(
title_block,
text=" Blockchain Intelligence Workbench",
foreground=THEME["fg_dim"],
background=THEME["bg"],
font=(THEME["font_family"], 10),
).pack(side="left", pady=(8, 0))
# Status / scan-time indicators on the right
status_block = ttk.Frame(header, style="TFrame")
status_block.pack(side="right")
self.scan_label = ttk.Label(
status_block,
text="● READY FOR INVESTIGATION",
foreground=THEME["success"],
background=THEME["bg"],
font=(THEME["font_family"], 9, "bold"),
)
self.scan_label.pack(anchor="e")
self.price_label = ttk.Label(
status_block,
text="BTC/USD: --",
foreground=THEME["fg_dim"],
background=THEME["bg"],
font=(THEME["font_family"], 9),
)
self.price_label.pack(anchor="e", pady=(2, 0))
# ===================== SEARCH BAR =====================
search_bar = ttk.Frame(container, style="Glass.TFrame", padding=12)
search_bar.pack(fill="x", side="top", pady=(0, 12))
ttk.Label(
search_bar,
text="🔎 SEARCH WALLET / TX HASH",
style="Panel.TLabel",
).pack(side="left", padx=(4, 8))
self.entry = ttk.Entry(search_bar, width=58)
self.entry.pack(side="left", fill="x", expand=True, padx=(0, 8))
self.entry.bind("<Return>", lambda event: self.run_analysis())
tb.Button(
search_bar, text="ANALYZE", bootstyle="warning", command=self.run_analysis
).pack(side="left", padx=3)
tb.Button(
search_bar, text="WATCH", bootstyle="info", command=self.watch_wallet
).pack(side="left", padx=3)
tb.Button(
search_bar, text="POLL", bootstyle="secondary", command=self.poll_watchlist
).pack(side="left", padx=3)
actions_menu = tb.Menubutton(search_bar, text="ACTIONS ▼", bootstyle="dark")
menu = tk.Menu(actions_menu, tearoff=False, bg=THEME["glass"], fg=THEME["fg"],
activebackground=THEME["glass_border"], activeforeground=THEME["accent_amber"])
menu.add_command(label="Export Report (JSON / PDF)", command=self.export)
menu.add_command(label="Export Graph (PNG)", command=self.export_png)
menu.add_separator()
menu.add_command(label="Remove Watch", command=self.remove_watch)
menu.add_command(label="Project Info", command=self.project_info_page)
menu.add_separator()
menu.add_command(label="Exit BlockTrace", command=self.quit_app)
actions_menu["menu"] = menu
actions_menu.pack(side="left", padx=3)
# ===================== METRIC CARDS =====================
metrics_row = ttk.Frame(container, style="TFrame")
metrics_row.pack(fill="x", side="top", pady=(0, 12))
self._metric_frames = {}
metrics = [
("transactions", "TRANSACTIONS", "#22d3ee"),
("hops", "TRACE HOPS", "#ffb547"),
("evidence", "EVIDENCE TXNS", "#36d399"),
("risk", "RISK LEVEL", "#ff3b5c"),
]
for i, (key, caption, accent) in enumerate(metrics):
card = self._make_metric_card(metrics_row, caption, accent)
card.pack(side="left", fill="x", expand=True, padx=(0 if i == 0 else 6, 0))
self._metric_frames[key] = card
# ===================== 3-PANE DASHBOARD =====================
# NOTE: previously this row used pack(side="left", expand=False) for the
# threat and timeline panels, which sized them off their Text widget's
# requested character width instead of the window — that's what made the
# third (timeline) panel look cramped. Using grid with explicit weighted
# columns instead makes all three panels scale proportionally with the
# window, and the timeline panel gets noticeably more room than before.
panes = ttk.Frame(container, style="TFrame")
panes.pack(fill="both", expand=True)
panes.rowconfigure(0, weight=1)
panes.columnconfigure(0, weight=2) # threat intelligence
panes.columnconfigure(1, weight=5) # fund-flow graph (largest)
panes.columnconfigure(2, weight=3) # transaction timeline (was too narrow)
# --- LEFT: Threat Intelligence ---
self.threat_panel = self._make_panel(panes, "THREAT INTELLIGENCE", "#ff3b5c")
self.threat_panel.grid(row=0, column=0, sticky="nsew", padx=(0, 6), pady=0)
self.threat_text = self._make_text_widget(self.threat_panel, width=30)
self.threat_text.pack(fill="both", expand=True, padx=10, pady=(4, 10))
self.threat_text.tag_configure("high", foreground=THEME["neon_red"])
self.threat_text.tag_configure("medium", foreground=THEME["neon_amber"])
self.threat_text.tag_configure("low", foreground=THEME["success"])
self.threat_text.tag_configure("dim", foreground=THEME["fg_dim"])
self.threat_text.tag_configure("header", foreground=THEME["fg"], font=(THEME["font_family"], 10, "bold"))
self._set_panel_text(self.threat_text, "")
# --- CENTER: Graph ---
self.graph_panel = self._make_panel(panes, "FUND FLOW NETWORK", "#ffb547")
self.graph_panel.grid(row=0, column=1, sticky="nsew", padx=6, pady=0)
self.fig, self.ax = plt.subplots(figsize=(12, 7), facecolor=THEME["bg_panel_2"])
self.canvas = FigureCanvasTkAgg(self.fig, master=self.graph_panel)
self.canvas.get_tk_widget().pack(fill="both", expand=True, padx=8, pady=(4, 8))
self._draw_empty_state()
# Scan progress bar (hidden by default, shown during analysis)
self.scan_progress = ttk.Progressbar(
self.graph_panel, mode="indeterminate", style="Horizontal.TProgressbar"
)
self.scan_progress.pack(fill="x", padx=8, pady=(0, 8))
self.scan_progress.pack_forget()
# --- RIGHT: Timeline ---
self.timeline_panel = self._make_panel(panes, "TRANSACTION TIMELINE", "#22d3ee")
self.timeline_panel.grid(row=0, column=2, sticky="nsew", padx=(6, 0), pady=0)
self.timeline_text = self._make_text_widget(self.timeline_panel, width=40)
self.timeline_text.pack(fill="both", expand=True, padx=10, pady=(4, 10))
self.timeline_text.tag_configure("header", foreground=THEME["fg"], font=(THEME["font_family"], 10, "bold"))
self.timeline_text.tag_configure("hash", foreground=THEME["accent_cyan"], font=("Consolas", 8))
self.timeline_text.tag_configure("amt", foreground=THEME["neon_amber"], font=(THEME["font_family"], 9, "bold"))
self.timeline_text.tag_configure("usd", foreground=THEME["success"])
self.timeline_text.tag_configure("dim", foreground=THEME["fg_dim"])
self._set_panel_text(self.timeline_text, "")
# --- STATUS / DETAILS BAR ---
self.details_label = ttk.Label(
container,
text="No investigation loaded — enter a wallet address or transaction hash.",
style="Panel.TLabel",
wraplength=1500,
)
self.details_label.pack(fill="x", side="bottom", pady=(10, 0))
def _make_panel(self, parent, title, accent_hex):
panel = ttk.Frame(parent, style="Panel.TFrame", padding=0)
header = ttk.Frame(panel, style="Glass.TFrame", padding=(10, 6))
header.pack(fill="x", side="top", padx=6, pady=(6, 0))
ttk.Label(
header,
text=f"▍ {title}",
foreground=accent_hex,
background=THEME["glass"],
font=(THEME["font_family"], 10, "bold"),
).pack(side="left")
return panel
def _make_text_widget(self, parent, width):
text = tk.Text(
parent,
width=width,
bg=THEME["bg_panel_2"],
fg=THEME["fg"],
insertbackground=THEME["neon_amber"],
relief="flat",
wrap="word",
padx=8,
pady=8,
spacing3=4,
selectbackground=THEME["glass_border"],
font=(THEME["font_family"], 9),
highlightthickness=0,
)
return text
def _make_metric_card(self, parent, caption, accent):
card = ttk.Frame(parent, style="Glass.TFrame", padding=(14, 8))
ttk.Label(card, text=caption, style="MetricCaption.TLabel").pack(anchor="w")
value = tk.Label(
card,
text="--",
bg=THEME["glass"],
fg=accent,
font=(THEME["font_family"], 22, "bold"),
)
value.pack(anchor="w", pady=(2, 0))
return value
# ------------------------------------------------------------------
# Text helpers
# ------------------------------------------------------------------
def _set_panel_text(self, widget, content):
widget.configure(state="normal")
widget.delete("1.0", "end")
widget.insert("1.0", content)
widget.configure(state="disabled")
def _draw_scanning_state(self, wallet):
"""Show an animated 'scanning' message in the graph panel."""
self.ax.clear()
self.fig.patch.set_facecolor(THEME["bg_panel_2"])
self.ax.set_facecolor(THEME["bg_panel_2"])
self.ax.text(
0.5, 0.58, "SCANNING BLOCKCHAIN...",
transform=self.ax.transAxes, ha="center", va="center",
fontsize=24, fontweight="bold", color=THEME["neon_amber"],
)
self.ax.text(
0.5, 0.48,
f"{truncate_address(wallet)}",
transform=self.ax.transAxes, ha="center", va="center",
fontsize=12, color=THEME["fg"],
)
self.ax.text(
0.5, 0.40,
"Fetching transaction history from public explorer...",
transform=self.ax.transAxes, ha="center", va="center",
fontsize=10, color=THEME["fg_dim"],
)
self.ax.set_axis_off()
self.canvas.draw()
def _set_default_panel_text(self, threat_text, timeline_text):
"""Show informative placeholder text in the side panels."""
self._set_panel_text(self.threat_text, threat_text)
self._set_panel_text(self.timeline_text, timeline_text)
def _stop_scan_progress(self):
"""Stop and hide the indeterminate progress bar."""
self.scan_progress.stop()
self.scan_progress.pack_forget()
# ------------------------------------------------------------------
# BTC price (async)
# ------------------------------------------------------------------
def _load_btc_price_async(self):
def fetch():
price = get_btc_usd_price()
self._worker_queue.put(("price", price))
threading.Thread(target=fetch, daemon=True).start()
# ------------------------------------------------------------------
# Queue polling (keeps UI responsive)
# ------------------------------------------------------------------
def _poll_queue(self):
try:
while True:
kind, payload = self._worker_queue.get_nowait()
if kind == "price":
self._apply_price(payload)
elif kind == "analysis":
self._apply_analysis(payload)
elif kind == "poll":
self._apply_poll_results(payload)
elif kind == "poll_error":
self.scan_label.config(
text="● POLL FAILED", foreground=THEME["neon_red"]
)
messagebox.showerror("Watchlist Poll Failed", payload)
except queue.Empty:
pass
self.root.after(80, self._poll_queue)
# ------------------------------------------------------------------
# Analysis (async)
# ------------------------------------------------------------------
def run_analysis(self):
"""Start the analysis in a background thread so the UI stays responsive."""
wallet = self.entry.get().strip()
if not wallet:
messagebox.showwarning("Input Error", "Please enter a wallet address.")
return
if self._loading:
messagebox.showinfo("Already running", "An analysis is already in progress.")
return
self._loading = True
self.scan_label.config(
text="● ANALYZING...", foreground=THEME["neon_amber"]
)
self.details_label.config(
text=f"Scanning {truncate_address(wallet)} — contacting blockchain explorer..."
)
self.scan_progress.pack(after=self.canvas.get_tk_widget(), fill="x", padx=8, pady=(0, 8))
self.scan_progress.start(12)
self._draw_scanning_state(wallet)
self._set_default_panel_text(
"Scanning blockchain...\n\nFetching transaction history\nand building fund-flow graph.\n\nThis may take a few seconds.",
"Analyzing wallet...\n\nContacting public blockchain explorer.\n\nTransaction timeline will appear here\nonce the scan completes.",
)
def worker():
try:
result = self._perform_analysis(wallet)
self._worker_queue.put(("analysis", result))
except Exception as error: # pragma: no cover - defensive
result = {
"wallet": wallet,
"error": str(error),
}
self._worker_queue.put(("analysis", result))
self._worker = threading.Thread(target=worker, daemon=True)
self._worker.start()
def _perform_analysis(self, wallet):
"""Run the full analysis pipeline (blocking; called in a worker thread)."""
reputation_details = get_wallet_reputation(wallet)
reputation = check_wallet(wallet)
data, chain = get_wallet_transactions(wallet)
tx_count = len(data.get("txs", [])) if data else 0
# If the public explorer is unreachable, gracefully fall back to the
# simulated demo trail instead of failing, so the UI always produces output.
if chain in ("BTC", "BTC_TRANSACTION") and data is None:
tracker = BlockchainTracker(
SIMULATED_TRAIL, "Victim_Wallet", "Attacker_Cold_Storage_FINAL"
)
is_simulation = True
chain = "BTC (SIMULATED)"
tx_count = 0
elif chain in ("BTC", "BTC_TRANSACTION"):
trace_wallet = wallet
if chain == "BTC_TRANSACTION":
transaction = data.get("txs", [{}])[0] if data else {}
input_addresses = [
item.get("prev_out", {}).get("addr")
for item in transaction.get("inputs", [])
]
trace_wallet = next(
(address for address in input_addresses if address), ""
)
if not trace_wallet:
return {
"wallet": wallet,
"chain": chain,
"error": "No traceable input address",
"tx_count": tx_count,
}
tracker = BlockchainTracker.from_dynamic_btc_trace(trace_wallet, limit=5)
is_simulation = False
else:
tracker = BlockchainTracker(
SIMULATED_TRAIL, "Victim_Wallet", "Attacker_Cold_Storage_FINAL"
)
is_simulation = True
graph_reputation = get_graph_reputation(tracker.G.nodes())
graph_risk = summarize_graph_risk(tracker.G, graph_reputation)
metrics = tracker.get_metrics()
same_wallet = self.previous_wallet == wallet
baseline_count = self.previous_tx_count if same_wallet else tx_count
alert = evaluate_transaction_alert(baseline_count, tx_count)
return {
"wallet": wallet,
"chain": chain,
"reputation": reputation,
"reputation_details": reputation_details,
"graph_reputation": graph_reputation,
"graph_risk": graph_risk,
"alert": alert,
"metrics": metrics,
"tracker": tracker,
"transactions": tx_count,
"is_simulated": is_simulation,
}
def _apply_analysis(self, result):
"""Apply an analysis result on the UI thread."""
self._loading = False
self._stop_scan_progress()
if result.get("error"):
self.scan_label.config(
text="● SCAN FAILED", foreground=THEME["neon_red"]
)
self.details_label.config(text=result["error"])
messagebox.showerror(
"Blockchain data unavailable",
result["error"] + "\nCheck your connection or try again later.",
)
return
wallet = result["wallet"]
chain = result["chain"]
metrics = result["metrics"]
graph_risk = result["graph_risk"]
alert = result["alert"]
is_simulation = result["is_simulated"]
tx_count = result["transactions"]
# Update summary cards
self._metric_frames["transactions"].config(text=str(tx_count))
self._metric_frames["hops"].config(text=str(metrics["hops"]))
self._metric_frames["evidence"].config(
text=str(len(metrics["path_transaction_ids"]))
)
risk_level = graph_risk["level"]
risk_color = RISK_COLORS.get(risk_level, THEME["fg_dim"])
self._metric_frames["risk"].config(text=risk_level.upper(), fg=risk_color)
# Update side panels
self._render_threat_panel(result)
self._render_timeline_panel(result)
# Render graph
self._draw_graph(
result["tracker"], is_simulation, result["graph_reputation"]
)
# Status / scan indicator
now = datetime.now().strftime("%H:%M:%S")
self.scan_label.config(
text=f"● LAST SCAN {now}", foreground=THEME["success"]
)
self.details_label.config(
text=(
f"Wallet: {truncate_address(wallet)} Chain: {chain} "
f"Reputation: {result['reputation']} "
f"Labeled graph addresses: {graph_risk['labeled_addresses']} "
f"Risk: {graph_risk['level'].upper()} "
f"Hops: {metrics['hops']} "
f"Flow bottleneck: {metrics['path_amount']:.8f} BTC\n"
f"Start: {truncate_address(metrics['start'])} "
f"End (terminal): {truncate_address(metrics['end'])} "
f"Evidence txns: {len(metrics['path_transaction_ids'])}\n"
f"Monitoring: {alert['reason']} "
f"Note: {justify_simulation() if is_simulation else 'Real transaction data fetched dynamically from public explorers.'}"
)
)
if alert["triggered"]:
messagebox.showwarning("Alert", alert["reason"])
self.previous_tx_count = tx_count
self.previous_wallet = wallet
self.current_report = {
"chain": chain,
"reputation": result["reputation"],
"reputation_details": result["reputation_details"],
"graph_reputation": result["graph_reputation"],
"graph_risk": graph_risk,
"alert": alert,
"metrics": metrics,
"transactions": tx_count,
"is_simulated": is_simulation,
}
# ------------------------------------------------------------------
# Threat panel rendering
# ------------------------------------------------------------------
def _render_threat_panel(self, result):
graph_risk = result["graph_risk"]
graph_reputation = result["graph_reputation"]
self._set_panel_text(self.threat_text, "")
self.threat_text.configure(state="normal")
level = graph_risk["level"].upper()
self.threat_text.insert("end", f"OVERALL RISK [ ", )
self.threat_text.tag_add("header", "1.0", "end")
self.threat_text.insert("end", f"{level}", "high" if level == "HIGH" else "medium" if level == "MEDIUM" else "low")
self.threat_text.insert("end", " ]\n")
self.threat_text.insert(
"end",
f"LABELED NODES {graph_risk['labeled_addresses']}\n"
f"CONFIRMED SOURCE local_rw_db\n\n",
"dim",
)
for address, finding in graph_risk["findings"].items():
if finding["indicators"]:
display = truncate_address(address)
level_tag = finding["level"]
self.threat_text.insert("end", f"◉ [{level_tag.upper()}] {display}\n", level_tag)
for indicator in finding["indicators"]:
self.threat_text.insert("end", f" • {indicator}\n", "dim")
self.threat_text.insert(
"end",
"\nHeuristics: fan-in / fan-out are investigation indicators,\n"
"not proof of criminal activity.",
"dim",
)
self.threat_text.configure(state="disabled")
# ------------------------------------------------------------------
# Timeline panel rendering
# ------------------------------------------------------------------
def _render_timeline_panel(self, result):
self._set_panel_text(self.timeline_text, "")
self.timeline_text.configure(state="normal")
price = self._btc_usd_price
metrics = result["metrics"]
entries = []
for edge in metrics["edges"]:
for record in edge["transaction_records"]:
entries.append((record, edge))
# Sort by timestamp descending (most recent first)
entries.sort(key=lambda item: item[0].get("timestamp") or 0, reverse=True)
if not entries:
self.timeline_text.insert(
"end",
"Transaction timestamps and hashes will appear here\n"
"when provided by the explorer.",
"dim",
)
self.timeline_text.configure(state="disabled")
return
for record, edge in entries:
timestamp = record.get("timestamp") or "time unavailable"
tx_hash = record.get("id") or "unknown"
amount = edge.get("amount", 0.0)
source = truncate_address(edge["source"])
target = truncate_address(edge["target"])
if isinstance(timestamp, (int, float)):
formatted_time = datetime.fromtimestamp(timestamp).strftime(
"%Y-%m-%d %H:%M:%S"
)
else:
formatted_time = timestamp
self.timeline_text.insert(
"end", f"▸ {formatted_time}\n", "header"
)
self.timeline_text.insert("end", f"{source} → {target}\n", "dim")
usd_text = ""
if price:
usd_text = f" ≈ ${amount * price:,.2f} USD"
self.timeline_text.insert("end", f"{amount:,.8f} BTC{usd_text}\n", "amt")
self.timeline_text.insert("end", f"{tx_hash}\n\n", "hash")
self.timeline_text.configure(state="disabled")
# ------------------------------------------------------------------
# Graph rendering
# ------------------------------------------------------------------
def _draw_empty_state(self):
self.ax.clear()
self.fig.patch.set_facecolor(THEME["bg_panel_2"])
self.ax.set_facecolor(THEME["bg_panel_2"])
self.ax.text(
0.5, 0.56, "NO INVESTIGATION LOADED",
transform=self.ax.transAxes, ha="center", va="center",
fontsize=22, fontweight="bold", color=THEME["fg"],
)
self.ax.text(
0.5, 0.46,
"Enter a wallet address or Bitcoin transaction hash above to begin tracing",
transform=self.ax.transAxes, ha="center", va="center",
fontsize=11, color=THEME["fg_dim"],
)
self.ax.set_axis_off()
self.canvas.draw()
def _draw_graph(self, tracker, is_simulation=True, graph_reputation=None):
"""Render the glowing fund-flow network graph with animated arrows."""
self.ax.clear()
self.fig.patch.set_facecolor(THEME["bg_panel_2"])
self.ax.set_facecolor(THEME["bg_panel_2"])
G = tracker.G
node_count = G.number_of_nodes()
if is_simulation:
pos = {
"Victim_Wallet": (0, 0),
"Ransom_Address_1A": (2.8, 0),
"Fee_Address_01": (2.8, -2.0),
"Intermediate_Wallet_2B": (5.3, 0),
"Change_Address_2C": (5.3, 2.0),
"Aggregator_Wallet_3C": (8.1, 0),
"Fake_Victim_X": (8.1, -2.0),
"Split_A_4D": (11.0, 1.2),
"Split_B_4E": (11.0, -1.2),
"Mixer_Entry_5F": (13.8, 0),
"Attacker_Cold_Storage_FINAL": (16.0, 0),
}
else:
# A real wallet trace can pull in a large number of raw neighbor
# addresses (every output of every fetched tx, not just the ones
# actually traced further). A fixed k was too tight for graphs that
# size and produced an overlapping hairball, so spacing now grows
# with node count to keep the layout readable.
k = max(2.2, 9.0 / max(node_count, 1) ** 0.5)
pos = nx.spring_layout(G, k=k, seed=42, iterations=80)
for node in G.nodes():
if node not in pos:
pos[node] = (0.0, 0.0)
graph_reputation = graph_reputation or {}
# The subset of nodes worth calling out by name: the traced path,
# the source/target endpoints, and anything matched in the local
# reputation database. Everything else is real data (kept for the
# threat panel and exports) but rendered as an unlabeled dot so large
# traces stay legible instead of drowning in overlapping text.
important_nodes = set(tracker.malicious_path) | {tracker.source, tracker.target}
important_nodes |= {
node for node, rep in graph_reputation.items() if rep.get("matched")
}
declutter = (not is_simulation) and node_count > 25
hidden_label_count = (node_count - len(important_nodes)) if declutter else 0
# Node styling
node_colors = []
node_sizes = []
for node in G.nodes():
if graph_reputation.get(node, {}).get("matched"):
node_colors.append(THEME["node_label"])
elif node == tracker.source:
node_colors.append(THEME["node_victim"])
elif node == tracker.target:
node_colors.append(THEME["node_mixer"])
elif node in tracker.malicious_path:
node_colors.append(THEME["node_trail"])
else:
node_colors.append(THEME["node_noise"])
if node == tracker.source or node == tracker.target:
node_sizes.append(1800)
elif node in tracker.malicious_path:
node_sizes.append(1300)
elif declutter and node not in important_nodes:
node_sizes.append(280)
else:
node_sizes.append(900)
# Path edges
path_edges = list(zip(tracker.malicious_path, tracker.malicious_path[1:]))
path_edge_set = set(path_edges)
if declutter:
# Keep only edges that touch an important node so the raw fan-out
# noise (dozens of thin lines to minor addresses) doesn't drown
# out the actual trail. The full edge set still exists in
# tracker.G for the threat panel, JSON export, and PDF report.
regular_edges = [
edge for edge in G.edges()
if edge not in path_edge_set
and (edge[0] in important_nodes or edge[1] in important_nodes)
]
else:
regular_edges = [edge for edge in G.edges() if edge not in path_edge_set]
# --- Glow effect: draw larger translucent nodes underneath ---
nx.draw_networkx_nodes(
G, pos, ax=self.ax, node_color=node_colors,
node_size=[s * 1.6 for s in node_sizes], alpha=0.18,
)
# --- Regular edges ---
if regular_edges:
nx.draw_networkx_edges(
G, pos, ax=self.ax, edgelist=regular_edges,
arrowstyle="-|>", arrowsize=14,
edge_color=THEME["edge_regular"], width=1.1, alpha=0.65,
connectionstyle="arc3,rad=0.12",
)
# --- Path edges (glowing amber) ---
if path_edges:
# Glow pass
nx.draw_networkx_edges(
G, pos, ax=self.ax, edgelist=path_edges,
arrowstyle="-|>", arrowsize=22,
edge_color=THEME["node_trail"], width=5.0, alpha=0.2,
connectionstyle="arc3,rad=0.12",
)
# Solid pass
nx.draw_networkx_edges(
G, pos, ax=self.ax, edgelist=path_edges,
arrowstyle="-|>", arrowsize=22,
edge_color=THEME["node_trail"], width=2.6, alpha=0.95,
connectionstyle="arc3,rad=0.12",
)
# --- Main nodes ---
nx.draw_networkx_nodes(
G, pos, ax=self.ax, node_color=node_colors, node_size=node_sizes,
edgecolors="#0a0e17", linewidths=1.2,
)
# --- Labels ---
for n, (x, y) in pos.items():
if declutter and n not in important_nodes:
continue
if is_simulation:
label_y = y + (0.42 if abs(y) < 1.2 else 0.28)
else:
label_y = y + 0.12
display = truncate_address(n, head=8, tail=4)
label_color = "#e7edf5"
if graph_reputation.get(n, {}).get("matched"):
label_color = THEME["neon_red"]
self.ax.text(
x, label_y, display,
horizontalalignment="center", fontsize=8,
color=label_color,
bbox=dict(facecolor=THEME["bg_panel"], alpha=0.85,
edgecolor=THEME["glass_border"], boxstyle="round,pad=0.3"),
)
# --- Edge amount labels ---
edge_labels = {(u, v): f"{d.get('amount', 0.0):.4f} BTC" for u, v, d in G.edges(data=True)}
for (u, v), label in edge_labels.items():
if declutter and (u, v) not in path_edge_set and not (
u in important_nodes and v in important_nodes
):
continue
if u in pos and v in pos:
ux, uy = pos[u]
vx, vy = pos[v]
mx, my = (ux + vx) / 2.0, (uy + vy) / 2.0
self.ax.text(
mx, my, label, fontsize=7.5, color=THEME["neon_amber"],
ha="center", va="center",
bbox=dict(facecolor=THEME["bg_panel"], alpha=0.9,
edgecolor="none", boxstyle="round,pad=0.2"),
)
# --- Legend ---
legend_patches = [
mpatches.Patch(color=THEME["node_victim"], label="Victim / Source"),
mpatches.Patch(color=THEME["node_trail"], label="Main Trail"),
mpatches.Patch(color=THEME["node_mixer"], label="Mixer / Terminal"),
mpatches.Patch(color=THEME["node_label"], label="Known Label"),
mpatches.Patch(color=THEME["node_noise"], label="Noise / Change"),
]
self.ax.legend(
handles=legend_patches, loc="upper left", fontsize=8,
facecolor=THEME["bg_panel"], edgecolor=THEME["glass_border"],
labelcolor=THEME["fg"], framealpha=0.9,
)
if hidden_label_count > 0:
self.ax.text(
0.99, 0.02,
f"+{hidden_label_count} minor addresses (labels hidden for clarity — "
f"still included in threat scan & export)",
transform=self.ax.transAxes, ha="right", va="bottom",
fontsize=8, color=THEME["fg_dim"], style="italic",
)
self.ax.set_title(
f"{self.tool_name} / RANSOMWARE TRANSACTION FLOW",
fontsize=14, color=THEME["fg"], pad=18, fontweight="bold",
)
self.ax.set_axis_off()
self.fig.tight_layout()
self.canvas.draw()
# --- Animated particles flowing along path edges ---
self._start_edge_animation(pos, path_edges, tracker)
def _start_edge_animation(self, pos, path_edges, tracker):
"""Animate glowing particles flowing along the main trail edges."""
if self._anim:
try:
self._anim.event_source.stop()
except Exception:
pass
self._anim = None
if not path_edges or len(path_edges) < 1:
return
# Pre-compute edge midpoints and directions for particle motion
particles = []
for edge in path_edges:
if edge[0] not in pos or edge[1] not in pos:
continue
x1, y1 = pos[edge[0]]
x2, y2 = pos[edge[1]]
# Midpoint trajectory