-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgui_app_blockchain.py
More file actions
1557 lines (1277 loc) · 67.7 KB
/
Copy pathgui_app_blockchain.py
File metadata and controls
1557 lines (1277 loc) · 67.7 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
"""
Encryptum Clone - GUI Application with Working Blockchain Integration
Uses private key wallet for blockchain pinning (no MetaMask needed)
"""
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, simpledialog
import threading
import os
import logging
import json
import webbrowser
from datetime import datetime
from typing import Optional, Dict, Any, List
from pathlib import Path
from web3 import Web3
from eth_account import Account
from eth_utils import to_checksum_address
import time
from decimal import Decimal
from encryption import EncryptumCrypto
from ipfs_handler import EncryptumIPFS
from config import config, validate_file_size, is_supported_file_type
# Simplified Contract ABI for pinning
PINNING_CONTRACT_ABI = [
{
"inputs": [
{"name": "fileCID", "type": "string"},
{"name": "metadataCID", "type": "string"},
{"name": "fileSize", "type": "uint256"},
{"name": "duration", "type": "uint256"},
{"name": "encryptedName", "type": "string"}
],
"name": "pinFile",
"outputs": [{"name": "pinId", "type": "uint256"}],
"stateMutability": "payable",
"type": "function"
},
{
"inputs": [
{"name": "fileSize", "type": "uint256"},
{"name": "duration", "type": "uint256"}
],
"name": "calculatePinCost",
"outputs": [{"name": "cost", "type": "uint256"}],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "pricePerGBPerDay",
"outputs": [{"name": "", "type": "uint256"}],
"stateMutability": "view",
"type": "function"
}
]
class BlockchainPanel(tk.Frame):
"""Blockchain integration panel with private key wallet"""
def __init__(self, parent, file_registry_callback=None):
super().__init__(parent)
self.file_registry_callback = file_registry_callback
self.w3 = None
self.contract = None
self.account = None
self.private_key = None
self.manual_gas_price = None # For manual gas price override
self.colors = {
'bg': '#1a1a1a',
'panel': '#2d2d2d',
'accent': '#00d4aa',
'text': '#ffffff',
'text_secondary': '#888888',
'blockchain': '#6366f1',
'error': '#ff4444',
'warning': '#ffa500'
}
self.configure(bg=self.colors['bg'])
self.setup_ui()
self.logger = logging.getLogger(__name__)
def setup_ui(self):
"""Setup blockchain panel UI"""
# Title
title_frame = tk.Frame(self, bg=self.colors['bg'])
title_frame.pack(fill='x', pady=20)
title = tk.Label(title_frame, text="⛓️ Blockchain File Pinning",
font=('Arial', 24, 'bold'),
fg=self.colors['blockchain'], bg=self.colors['bg'])
title.pack()
# Connection Section
conn_frame = tk.LabelFrame(self, text="Blockchain Connection",
font=('Arial', 12, 'bold'),
fg=self.colors['accent'],
bg=self.colors['panel'],
relief='groove', bd=2)
conn_frame.pack(fill='x', padx=20, pady=10)
# Network selection with warning for mainnet
net_frame = tk.Frame(conn_frame, bg=self.colors['panel'])
net_frame.pack(fill='x', padx=20, pady=10)
tk.Label(net_frame, text="Network:",
font=('Arial', 11), fg=self.colors['text'],
bg=self.colors['panel']).grid(row=0, column=0, sticky='w', padx=(0, 10))
self.network_var = tk.StringVar(value='sepolia')
network_menu = ttk.Combobox(net_frame, textvariable=self.network_var,
values=['sepolia', 'polygon', 'arbitrum', 'mainnet'],
state='readonly', width=15)
network_menu.grid(row=0, column=1, sticky='w')
network_menu.bind('<<ComboboxSelected>>', self.on_network_change)
# Network warning label
self.network_warning = tk.Label(net_frame, text="",
font=('Arial', 10, 'bold'),
fg=self.colors['warning'],
bg=self.colors['panel'])
self.network_warning.grid(row=0, column=2, padx=(10, 0))
# RPC URL with dropdown
tk.Label(net_frame, text="RPC URL:",
font=('Arial', 11), fg=self.colors['text'],
bg=self.colors['panel']).grid(row=1, column=0, sticky='w', padx=(0, 10), pady=(10, 0))
rpc_frame = tk.Frame(net_frame, bg=self.colors['panel'])
rpc_frame.grid(row=1, column=1, sticky='w', pady=(10, 0))
self.rpc_entry = tk.Entry(rpc_frame, width=40)
self.rpc_entry.pack(side='left', padx=(0, 5))
# Use a reliable public RPC by default
self.rpc_entry.insert(0, "https://ethereum-sepolia-rpc.publicnode.com")
# RPC dropdown button
tk.Button(rpc_frame, text="📋 Public RPCs",
command=self.show_rpc_menu,
bg='#4a4a4a', fg='white', padx=10).pack(side='left')
tk.Button(rpc_frame, text="🧪 Test",
command=self.test_rpc_connection,
bg='#666', fg='white', padx=10).pack(side='left', padx=(5, 0))
# Help text
help_text = tk.Label(net_frame,
text="Free public RPC included! Click 'Public RPCs' for 20+ options",
font=('Arial', 9), fg=self.colors['text_secondary'],
bg=self.colors['panel'])
help_text.grid(row=2, column=1, sticky='w', pady=(5, 0))
# Gas settings frame (NEW)
gas_frame = tk.Frame(net_frame, bg=self.colors['panel'])
gas_frame.grid(row=3, column=0, columnspan=3, sticky='w', pady=(10, 0))
tk.Label(gas_frame, text="Gas Price (Gwei):",
font=('Arial', 11), fg=self.colors['text'],
bg=self.colors['panel']).pack(side='left', padx=(0, 10))
self.gas_price_var = tk.StringVar(value="Auto")
self.gas_price_entry = tk.Entry(gas_frame, textvariable=self.gas_price_var, width=10)
self.gas_price_entry.pack(side='left', padx=(0, 5))
tk.Label(gas_frame, text="(Enter number or 'Auto' for automatic)",
font=('Arial', 9), fg=self.colors['text_secondary'],
bg=self.colors['panel']).pack(side='left')
# Connection status
self.conn_status = tk.Label(conn_frame,
text="⚪ Not Connected",
font=('Arial', 12),
fg=self.colors['text_secondary'],
bg=self.colors['panel'])
self.conn_status.pack(pady=10)
# Connect button
self.connect_btn = tk.Button(conn_frame,
text="🔌 Connect to Blockchain",
command=self.connect_blockchain,
bg=self.colors['blockchain'],
fg='white',
font=('Arial', 12, 'bold'),
padx=30, pady=10)
self.connect_btn.pack(pady=10)
# Wallet Section
wallet_frame = tk.LabelFrame(self, text="Wallet",
font=('Arial', 12, 'bold'),
fg=self.colors['accent'],
bg=self.colors['panel'],
relief='groove', bd=2)
wallet_frame.pack(fill='x', padx=20, pady=10)
# Wallet status
self.wallet_status = tk.Label(wallet_frame,
text="No wallet loaded",
font=('Arial', 10),
fg=self.colors['text_secondary'],
bg=self.colors['panel'])
self.wallet_status.pack(pady=10)
self.account_label = tk.Label(wallet_frame,
text="Account: Not connected",
font=('Arial', 10),
fg=self.colors['text_secondary'],
bg=self.colors['panel'])
self.account_label.pack()
self.balance_label = tk.Label(wallet_frame,
text="Balance: --",
font=('Arial', 10),
fg=self.colors['text_secondary'],
bg=self.colors['panel'])
self.balance_label.pack(pady=(0, 10))
# Wallet buttons
wallet_btn_frame = tk.Frame(wallet_frame, bg=self.colors['panel'])
wallet_btn_frame.pack(pady=10)
tk.Button(wallet_btn_frame, text="🔑 Import Private Key",
command=self.import_private_key,
bg='#4a4a4a', fg='white', padx=20).pack(side='left', padx=5)
tk.Button(wallet_btn_frame, text="💰 Generate New Wallet",
command=self.generate_wallet,
bg='#0066cc', fg='white', padx=20).pack(side='left', padx=5)
# Contract Section
contract_frame = tk.LabelFrame(self, text="Smart Contract",
font=('Arial', 12, 'bold'),
fg=self.colors['accent'],
bg=self.colors['panel'],
relief='groove', bd=2)
contract_frame.pack(fill='x', padx=20, pady=10)
# Contract address
addr_frame = tk.Frame(contract_frame, bg=self.colors['panel'])
addr_frame.pack(fill='x', padx=20, pady=10)
tk.Label(addr_frame, text="Contract Address:",
font=('Arial', 11), fg=self.colors['text'],
bg=self.colors['panel']).pack(side='left', padx=(0, 10))
self.contract_entry = tk.Entry(addr_frame, width=50)
self.contract_entry.pack(side='left', padx=(0, 10))
tk.Button(addr_frame, text="Load Contract",
command=self.load_contract,
bg=self.colors['accent'], fg='black',
padx=20).pack(side='left')
# Contract status
self.contract_status = tk.Label(contract_frame,
text="Contract not loaded",
font=('Arial', 10),
fg=self.colors['text_secondary'],
bg=self.colors['panel'])
self.contract_status.pack(pady=(0, 10))
# Pinning Section
pin_frame = tk.LabelFrame(self, text="File Pinning",
font=('Arial', 12, 'bold'),
fg=self.colors['accent'],
bg=self.colors['panel'],
relief='groove', bd=2)
pin_frame.pack(fill='both', expand=True, padx=20, pady=10)
# Duration selection
dur_frame = tk.Frame(pin_frame, bg=self.colors['panel'])
dur_frame.pack(pady=10)
tk.Label(dur_frame, text="Pin Duration:",
font=('Arial', 11), fg=self.colors['text'],
bg=self.colors['panel']).pack(side='left', padx=(0, 20))
self.duration_var = tk.IntVar(value=30)
for text, days in [('30 days', 30), ('90 days', 90), ('1 year', 365)]:
tk.Radiobutton(dur_frame, text=text, variable=self.duration_var,
value=days, bg=self.colors['panel'],
fg=self.colors['text'],
selectcolor=self.colors['panel']).pack(side='left', padx=10)
# Selected files info
self.selected_label = tk.Label(pin_frame,
text="No files selected",
font=('Arial', 10),
fg=self.colors['text_secondary'],
bg=self.colors['panel'])
self.selected_label.pack(pady=10)
# Cost estimate
self.cost_label = tk.Label(pin_frame,
text="Cost: Select files to estimate",
font=('Arial', 11, 'bold'),
fg=self.colors['accent'],
bg=self.colors['panel'])
self.cost_label.pack(pady=10)
# Gas estimate (NEW)
self.gas_estimate_label = tk.Label(pin_frame,
text="",
font=('Arial', 10),
fg=self.colors['warning'],
bg=self.colors['panel'])
self.gas_estimate_label.pack(pady=5)
# Pin button
self.pin_btn = tk.Button(pin_frame,
text="📌 Pin Selected Files on Blockchain",
command=self.pin_files,
bg=self.colors['accent'],
fg='black',
font=('Arial', 12, 'bold'),
padx=30, pady=10,
state='disabled')
self.pin_btn.pack(pady=10)
# Transaction log
log_label = tk.Label(pin_frame, text="Transaction Log:",
font=('Arial', 10), fg=self.colors['text'],
bg=self.colors['panel'])
log_label.pack(anchor='w', padx=20)
# Log text widget
log_frame = tk.Frame(pin_frame, bg=self.colors['panel'])
log_frame.pack(fill='both', expand=True, padx=20, pady=(5, 20))
self.log_text = tk.Text(log_frame, height=6, width=80,
bg='#0a0a0a', fg=self.colors['text'],
font=('Consolas', 9))
self.log_text.pack(side='left', fill='both', expand=True)
scrollbar = tk.Scrollbar(log_frame, command=self.log_text.yview)
scrollbar.pack(side='right', fill='y')
self.log_text.config(yscrollcommand=scrollbar.set)
def show_rpc_menu(self):
"""Show menu of public RPC endpoints"""
# Define public RPCs - updated with all the endpoints
public_rpcs = {
'sepolia': [
("PublicNode (Recommended)", "https://ethereum-sepolia-rpc.publicnode.com"),
("Blast API", "https://eth-sepolia.public.blastapi.io"),
("DRPC", "https://sepolia.drpc.org"),
("1RPC", "https://1rpc.io/sepolia"),
("Alchemy Demo", "https://eth-sepolia.g.alchemy.com/v2/demo"),
("Tenderly", "https://gateway.tenderly.co/public/sepolia"),
("Ethpandaops", "https://rpc.sepolia.ethpandaops.io"),
("ZAN API", "https://api.zan.top/eth-sepolia"),
("OmniaNode", "https://endpoints.omniatech.io/v1/eth/sepolia/public"),
("Unifra", "https://eth-sepolia-public.unifra.io"),
("TheRPC", "https://rpc.therpc.io/ethereum-sepolia"),
("Owlracle", "https://rpc.owlracle.info/sepolia/70d38ce1826c4a60bb2a8e05a6c8b20f"),
("4everland", "https://eth-testnet.4everland.org/v1/37fa9972c1b1cd5fab542c7bdd4cde2f"),
("StackUp", "https://public.stackup.sh/api/v1/node/ethereum-sepolia"),
],
'mainnet': [
("PublicNode (Fast)", "https://ethereum-rpc.publicnode.com"),
("Cloudflare", "https://cloudflare-eth.com"),
("LlamaRPC", "https://eth.llamarpc.com"),
("1RPC Privacy", "https://1rpc.io/eth"),
("Blast API", "https://eth-mainnet.public.blastapi.io"),
("DRPC", "https://eth.drpc.org"),
("Tenderly", "https://gateway.tenderly.co/public/mainnet"),
("Alchemy Demo", "https://eth-mainnet.g.alchemy.com/v2/demo"),
("BlockPi", "https://ethereum.blockpi.network/v1/rpc/public"),
("OmniaNode", "https://endpoints.omniatech.io/v1/eth/mainnet/public"),
("TheRPC", "https://rpc.therpc.io/ethereum"),
("Gashawk", "https://core.gashawk.io/rpc"),
("ZAN API", "https://api.zan.top/eth-mainnet"),
("Owlracle", "https://rpc.owlracle.info/eth/70d38ce1826c4a60bb2a8e05a6c8b20f"),
("0xRPC", "https://0xrpc.io/eth"),
],
'polygon': [
("Polygon RPC", "https://polygon-rpc.com"),
("Matic Vigil", "https://rpc-mainnet.maticvigil.com"),
("1RPC", "https://1rpc.io/matic"),
("DRPC", "https://polygon.drpc.org"),
],
'arbitrum': [
("Arbitrum Official", "https://arb1.arbitrum.io/rpc"),
("1RPC", "https://1rpc.io/arb"),
("DRPC", "https://arbitrum.drpc.org"),
]
}
# Create popup menu
menu = tk.Menu(self, tearoff=0)
# Get current network
network = self.network_var.get()
if network in public_rpcs:
# Add header
menu.add_command(label=f"=== {network.upper()} Public RPCs ===", state='disabled')
menu.add_separator()
for name, url in public_rpcs[network]:
menu.add_command(
label=name,
command=lambda u=url: self.set_rpc_url(u)
)
else:
menu.add_command(label="No public RPCs for this network", state='disabled')
# Add info at bottom
menu.add_separator()
menu.add_command(label="💡 Click to select RPC", state='disabled')
# Show menu at button location
menu.post(self.winfo_pointerx(), self.winfo_pointery())
def set_rpc_url(self, url: str):
"""Set RPC URL from menu selection"""
self.rpc_entry.delete(0, tk.END)
self.rpc_entry.insert(0, url)
self.log(f"RPC URL set to: {url}", 'info')
def log(self, message: str, level: str = 'info'):
"""Add message to transaction log"""
timestamp = datetime.now().strftime('%H:%M:%S')
# Color based on level
if level == 'error':
tag = 'error'
elif level == 'success':
tag = 'success'
elif level == 'warning':
tag = 'warning'
else:
tag = 'info'
self.log_text.insert('end', f"[{timestamp}] {message}\n", tag)
self.log_text.see('end')
# Configure tags
self.log_text.tag_config('error', foreground='#ff4444')
self.log_text.tag_config('success', foreground='#00d4aa')
self.log_text.tag_config('warning', foreground='#ffa500')
self.log_text.tag_config('info', foreground='#888888')
def on_network_change(self, event=None):
"""Handle network selection change"""
network = self.network_var.get()
# Update RPC URL to default for the selected network
default_rpcs = {
'sepolia': 'https://ethereum-sepolia-rpc.publicnode.com',
'polygon': 'https://polygon-rpc.com',
'arbitrum': 'https://arb1.arbitrum.io/rpc',
'mainnet': 'https://ethereum-rpc.publicnode.com' # Updated to PublicNode
}
if network in default_rpcs:
self.rpc_entry.delete(0, tk.END)
self.rpc_entry.insert(0, default_rpcs[network])
self.log(f"Network changed to {network}, RPC updated", 'info')
# Update warning for mainnet
if network == 'mainnet':
self.network_warning.config(text="⚠️ REAL ETH!", fg='#ff0000')
self.log("⚠️ WARNING: Mainnet uses real ETH! Be careful with transactions.", 'warning')
messagebox.showwarning("Mainnet Warning",
"⚠️ You're switching to Ethereum Mainnet!\n\n"
"This network uses REAL ETH.\n"
"Transactions cost real money.\n\n"
"For testing, use Sepolia instead.")
else:
self.network_warning.config(text="")
if network == 'sepolia':
self.log("Using Sepolia testnet - safe for testing", 'info')
def test_rpc_connection(self):
"""Test RPC connection without fully connecting"""
rpc_url = self.rpc_entry.get().strip()
if not rpc_url:
messagebox.showwarning("No URL", "Please enter an RPC URL")
return
self.log(f"Testing RPC connection to: {rpc_url}", 'info')
try:
# Quick connection test
test_w3 = Web3(Web3.HTTPProvider(rpc_url, request_kwargs={'timeout': 5}))
if test_w3.is_connected():
chain_id = test_w3.eth.chain_id
block_num = test_w3.eth.block_number
# Get current gas price for info
gas_price_wei = test_w3.eth.gas_price
gas_price_gwei = float(test_w3.from_wei(gas_price_wei, 'gwei'))
self.log(f"✅ RPC test successful! Chain ID: {chain_id}, Latest block: {block_num}", 'success')
self.log(f"Current gas price: {gas_price_gwei:.2f} Gwei", 'info')
messagebox.showinfo("Test Successful",
f"RPC connection successful!\n\n"
f"Chain ID: {chain_id}\n"
f"Latest block: {block_num}\n"
f"Current gas price: {gas_price_gwei:.2f} Gwei")
else:
self.log(f"❌ RPC test failed - not connected", 'error')
messagebox.showerror("Test Failed", "Could not connect to RPC endpoint")
except Exception as e:
self.log(f"❌ RPC test failed: {str(e)}", 'error')
messagebox.showerror("Test Failed", f"RPC connection failed:\n{str(e)}")
def connect_blockchain(self):
"""Connect to blockchain"""
try:
self.connect_btn.config(state='disabled', text="Connecting...")
self.conn_status.config(text="⟳ Connecting...", fg=self.colors['accent'])
# Get RPC URL
rpc_url = self.rpc_entry.get().strip()
if not rpc_url:
raise ValueError("Please enter RPC URL")
# Connect to Web3
self.w3 = Web3(Web3.HTTPProvider(rpc_url))
if not self.w3.is_connected():
raise ConnectionError("Failed to connect to blockchain")
# Get chain ID
chain_id = self.w3.eth.chain_id
# Get current gas price
gas_price_wei = self.w3.eth.gas_price
gas_price_gwei = float(self.w3.from_wei(gas_price_wei, 'gwei'))
# Update UI
self.conn_status.config(text=f"🟢 Connected (Chain ID: {chain_id})",
fg=self.colors['accent'])
self.connect_btn.config(text="✓ Connected", bg=self.colors['accent'])
self.log(f"Connected to blockchain (Chain ID: {chain_id})", 'success')
self.log(f"Current gas price: {gas_price_gwei:.2f} Gwei", 'info')
# Enable features
self.check_enable_features()
except Exception as e:
self.conn_status.config(text="🔴 Connection Failed", fg=self.colors['error'])
self.connect_btn.config(state='normal', text="🔌 Connect to Blockchain")
self.log(f"Connection failed: {str(e)}", 'error')
messagebox.showerror("Connection Error", f"Failed to connect:\n{str(e)}")
def import_private_key(self):
"""Import private key"""
if not self.w3:
messagebox.showwarning("Not Connected", "Please connect to blockchain first")
return
# Get private key
private_key = simpledialog.askstring("Import Private Key",
"Enter your private key (will be hidden):",
show='*')
if not private_key:
return
try:
# Clean private key - remove 0x prefix if present
if private_key.startswith('0x'):
private_key = private_key[2:]
# Ensure private key is properly formatted
if len(private_key) != 64:
raise ValueError(f"Invalid private key length: {len(private_key)} (should be 64)")
# Create account from private key
account = Account.from_key(private_key)
self.account = account.address
self.private_key = '0x' + private_key # Store with 0x prefix
# Get balance
balance_wei = self.w3.eth.get_balance(self.account)
balance_eth = self.w3.from_wei(balance_wei, 'ether')
# Update UI
self.wallet_status.config(text="Wallet loaded", fg=self.colors['accent'])
self.account_label.config(text=f"Account: {self.account[:6]}...{self.account[-4:]}")
self.balance_label.config(text=f"Balance: {balance_eth:.4f} ETH")
self.log(f"Wallet imported: {self.account[:6]}...{self.account[-4:]}", 'success')
# Enable features
self.check_enable_features()
except Exception as e:
self.log(f"Failed to import wallet: {str(e)}", 'error')
messagebox.showerror("Import Error", f"Failed to import private key:\n{str(e)}")
def generate_wallet(self):
"""Generate new wallet"""
try:
# Generate new account
account = Account.create()
# Show private key to user
result = messagebox.askyesno("New Wallet Generated",
f"New wallet generated!\n\n"
f"Address: {account.address}\n\n"
f"IMPORTANT: Save your private key securely!\n"
f"You will only see it once.\n\n"
f"Click 'Yes' to view private key")
if result:
# Show private key
pk_window = tk.Toplevel(self)
pk_window.title("Private Key")
pk_window.geometry("600x200")
pk_window.configure(bg=self.colors['bg'])
tk.Label(pk_window, text="Your Private Key (KEEP IT SECRET!):",
font=('Arial', 12, 'bold'),
fg=self.colors['error'],
bg=self.colors['bg']).pack(pady=20)
pk_text = tk.Text(pk_window, height=2, width=70,
font=('Consolas', 10))
pk_text.pack(padx=20)
pk_text.insert('1.0', account.key.hex())
pk_text.config(state='disabled')
tk.Button(pk_window, text="Copy & Close",
command=lambda: self.copy_and_close(account.key.hex(), pk_window),
bg=self.colors['accent'], fg='black',
padx=20, pady=10).pack(pady=20)
# Use this wallet
self.account = account.address
self.private_key = account.key.hex() # This already includes 0x prefix
# Update UI if connected
if self.w3:
balance_wei = self.w3.eth.get_balance(self.account)
balance_eth = self.w3.from_wei(balance_wei, 'ether')
self.wallet_status.config(text="New wallet generated", fg=self.colors['accent'])
self.account_label.config(text=f"Account: {self.account[:6]}...{self.account[-4:]}")
self.balance_label.config(text=f"Balance: {balance_eth:.4f} ETH")
self.log(f"New wallet generated: {self.account[:6]}...{self.account[-4:]}", 'success')
self.log("⚠️ Make sure to fund this wallet before pinning files", 'warning')
self.check_enable_features()
except Exception as e:
self.log(f"Failed to generate wallet: {str(e)}", 'error')
messagebox.showerror("Generation Error", f"Failed to generate wallet:\n{str(e)}")
def copy_and_close(self, text: str, window):
"""Copy text to clipboard and close window"""
self.clipboard_clear()
self.clipboard_append(text)
window.destroy()
messagebox.showinfo("Copied", "Private key copied to clipboard!\nStore it securely.")
def load_contract(self):
"""Load smart contract"""
try:
if not self.w3:
messagebox.showwarning("Not Connected", "Please connect to blockchain first")
return
address = self.contract_entry.get().strip()
if not address:
raise ValueError("Please enter contract address")
# Validate address
if not self.w3.is_address(address):
raise ValueError("Invalid contract address")
# Load contract
self.contract = self.w3.eth.contract(
address=Web3.to_checksum_address(address),
abi=PINNING_CONTRACT_ABI
)
# Test contract by calling view function
price_wei = self.contract.functions.pricePerGBPerDay().call()
price_eth = self.w3.from_wei(price_wei, 'ether')
self.contract_status.config(
text=f"✓ Contract loaded - Price: {price_eth:.6f} ETH/GB/day",
fg=self.colors['accent']
)
self.log(f"Contract loaded at: {address[:10]}...{address[-8:]}", 'success')
self.log(f"Price per GB per day: {price_eth:.6f} ETH", 'info')
# Save contract address
config.pinning_contract_address = address
config.save_to_file()
self.check_enable_features()
except Exception as e:
self.contract_status.config(
text=f"Failed: {str(e)[:50]}...",
fg=self.colors['error']
)
self.log(f"Failed to load contract: {str(e)}", 'error')
messagebox.showerror("Contract Error", f"Failed to load contract:\n{str(e)}")
def check_enable_features(self):
"""Check if features should be enabled"""
if self.w3 and self.account and self.contract:
self.pin_btn.config(state='normal')
self.log("✅ All components ready - you can now pin files", 'success')
else:
self.pin_btn.config(state='disabled')
def get_manual_gas_price(self):
"""Get gas price - either manual or automatic"""
gas_price_str = self.gas_price_var.get().strip()
if gas_price_str.lower() == 'auto' or not gas_price_str:
# Get automatic gas price
gas_price_wei = self.w3.eth.gas_price
# Apply buffer
gas_price_wei = int(gas_price_wei * config.gas_price_buffer)
# Ensure minimum gas price
min_gas_wei = self.w3.to_wei(config.min_gas_price_gwei, 'gwei')
if gas_price_wei < min_gas_wei:
gas_price_wei = min_gas_wei
return gas_price_wei
else:
try:
# Use manual gas price
gas_price_gwei = float(gas_price_str)
if gas_price_gwei < config.min_gas_price_gwei:
self.log(f"⚠️ Gas price too low, using minimum: {config.min_gas_price_gwei} Gwei", 'warning')
gas_price_gwei = config.min_gas_price_gwei
return self.w3.to_wei(gas_price_gwei, 'gwei')
except ValueError:
# Fall back to automatic
self.log("Invalid gas price, using automatic", 'warning')
return self.get_manual_gas_price() # Recursive call with 'auto'
def update_selected_files(self, files: List[Dict[str, Any]]):
"""Update selected files info and estimate cost"""
self.selected_files = files
if not files:
self.selected_label.config(text="No files selected")
self.cost_label.config(text="Cost: Select files to estimate")
self.gas_estimate_label.config(text="")
return
total_size = sum(f.get('original_size', 0) for f in files)
size_mb = total_size / (1024 * 1024)
self.selected_label.config(
text=f"Selected: {len(files)} files, {size_mb:.2f} MB total"
)
# Estimate cost if contract loaded
if self.contract:
try:
duration_seconds = self.duration_var.get() * 86400
cost_wei = self.contract.functions.calculatePinCost(
total_size, duration_seconds
).call()
# Convert to int to handle Decimal type
cost_wei = int(cost_wei)
cost_eth = self.w3.from_wei(cost_wei, 'ether')
# Get current gas price
gas_price_wei = self.get_manual_gas_price()
gas_price_gwei = self.w3.from_wei(gas_price_wei, 'gwei')
# Estimate gas for all files
estimated_gas_per_file = 350000 # Conservative estimate
total_gas = estimated_gas_per_file * len(files)
gas_cost_wei = int(total_gas * gas_price_wei)
gas_cost_eth = self.w3.from_wei(gas_cost_wei, 'ether')
# Convert to float for arithmetic
total_cost = float(cost_eth) + float(gas_cost_eth)
self.cost_label.config(
text=f"Estimated Total Cost: {total_cost:.6f} ETH "
f"(Pin: {float(cost_eth):.6f} + Gas: {float(gas_cost_eth):.6f})",
fg=self.colors['accent']
)
self.gas_estimate_label.config(
text=f"Gas: ~{total_gas:,} units @ {float(gas_price_gwei):.2f} Gwei",
fg=self.colors['warning']
)
except Exception as e:
self.cost_label.config(text="Cost estimation failed", fg=self.colors['error'])
self.log(f"Cost estimation error: {str(e)}", 'error')
def pin_files(self):
"""Pin selected files on blockchain"""
if not hasattr(self, 'selected_files') or not self.selected_files:
messagebox.showwarning("No Files", "Please select files from the Files tab first")
return
# Check balance
balance_wei = self.w3.eth.get_balance(self.account)
balance_eth = float(self.w3.from_wei(balance_wei, 'ether'))
# Estimate total cost
total_size = sum(f.get('original_size', 0) for f in self.selected_files)
duration_seconds = self.duration_var.get() * 86400
try:
cost_wei = self.contract.functions.calculatePinCost(
total_size, duration_seconds
).call()
# Convert to int to handle Decimal type
cost_wei = int(cost_wei)
cost_eth = float(self.w3.from_wei(cost_wei, 'ether'))
# Get gas price
gas_price_wei = self.get_manual_gas_price()
gas_price_gwei = float(self.w3.from_wei(gas_price_wei, 'gwei'))
# Estimate gas
estimated_gas_per_file = 350000
total_gas = estimated_gas_per_file * len(self.selected_files)
gas_cost_eth = float(self.w3.from_wei(total_gas * gas_price_wei, 'ether'))
total_cost = cost_eth + gas_cost_eth
if balance_eth < total_cost * 1.1: # 10% safety margin
messagebox.showerror("Insufficient Balance",
f"Insufficient balance!\n\n"
f"Required: ~{total_cost * 1.1:.6f} ETH (with safety margin)\n"
f"Balance: {balance_eth:.6f} ETH\n\n"
f"Please fund your wallet.")
return
# Confirm
if not messagebox.askyesno("Confirm Pinning",
f"Pin {len(self.selected_files)} files for {self.duration_var.get()} days?\n\n"
f"Estimated cost: {total_cost:.6f} ETH\n"
f"Gas price: {gas_price_gwei:.2f} Gwei\n"
f"Your balance: {balance_eth:.6f} ETH\n\n"
f"Proceed with transaction?"):
return
# Execute pinning
self.execute_pinning()
except Exception as e:
messagebox.showerror("Error", f"Failed to estimate cost:\n{str(e)}")
def execute_pinning(self):
"""Execute the pinning transactions"""
self.pin_btn.config(state='disabled', text="Pinning...")
def pin_thread():
try:
successful = 0
failed = 0
# Import Account at the function level to ensure it's available
from eth_account import Account as EthAccount
for i, file in enumerate(self.selected_files):
try:
self.log(f"Pinning file {i+1}/{len(self.selected_files)}: {file['original_name']}", 'info')
# Calculate cost for this file
duration_seconds = self.duration_var.get() * 86400
cost_wei = self.contract.functions.calculatePinCost(
file['original_size'], duration_seconds
).call()
# Convert to int to handle Decimal type
cost_wei = int(cost_wei)
# Get current nonce
nonce = self.w3.eth.get_transaction_count(self.account)
# Get gas price
gas_price_wei = self.get_manual_gas_price()
gas_price_gwei = float(self.w3.from_wei(gas_price_wei, 'gwei'))
self.log(f"Using gas price: {gas_price_gwei:.2f} Gwei", 'info')
# First estimate gas for the transaction
try:
estimated_gas = self.contract.functions.pinFile(
file['file_cid'],
file['metadata_cid'],
file['original_size'],
duration_seconds,
file.get('original_name', 'File')
).estimate_gas({
'from': self.account,
'value': cost_wei
})
# Add buffer to estimated gas
gas_limit = int(estimated_gas * config.gas_limit_buffer)
# Cap at maximum gas limit
if gas_limit > config.max_gas_limit:
gas_limit = config.max_gas_limit
self.log(f"Estimated gas: {estimated_gas:,}, Using limit: {gas_limit:,}", 'info')
except Exception as gas_error:
self.log(f"Gas estimation failed: {str(gas_error)}, using default", 'warning')
gas_limit = config.default_gas_limit
# Build transaction with proper parameters
tx_params = {
'from': self.account,
'value': int(cost_wei),
'gas': gas_limit,
'gasPrice': int(gas_price_wei),
'nonce': nonce,
'chainId': self.w3.eth.chain_id
}
transaction = self.contract.functions.pinFile(
file['file_cid'],
file['metadata_cid'],
file['original_size'],
duration_seconds,
file.get('original_name', 'File')
).build_transaction(tx_params)
# Calculate total transaction cost
tx_cost_eth = float(self.w3.from_wei(cost_wei + (gas_limit * gas_price_wei), 'ether'))
self.log(f"Transaction cost: {tx_cost_eth:.6f} ETH", 'info')
# Sign transaction
try:
# Ensure private key has 0x prefix
pk = self.private_key
if not pk.startswith('0x'):
pk = '0x' + pk
# Sign the transaction
signed = EthAccount.sign_transaction(transaction, pk)
# Get raw transaction
if hasattr(signed, 'rawTransaction'):
raw_tx = signed.rawTransaction
elif hasattr(signed, 'raw_transaction'):
raw_tx = signed.raw_transaction
elif hasattr(signed, 'raw'):
raw_tx = signed.raw
else:
raise AttributeError("Cannot find raw transaction in signed object")
# Send transaction
tx_hash = self.w3.eth.send_raw_transaction(raw_tx)
self.log(f"Transaction sent: 0x{tx_hash.hex()}", 'info')
except Exception as signing_error:
self.log(f"Signing error: {str(signing_error)}", 'error')
raise signing_error
# Wait for receipt
self.log(f"Waiting for transaction confirmation...", 'info')
receipt = self.w3.eth.wait_for_transaction_receipt(tx_hash, timeout=120)
if receipt['status'] == 1:
actual_gas_used = receipt['gasUsed']
actual_gas_cost = float(self.w3.from_wei(actual_gas_used * gas_price_wei, 'ether'))
self.log(f"✓ File pinned successfully! Gas used: {actual_gas_used:,} ({actual_gas_cost:.6f} ETH)", 'success')
successful += 1
# Update file registry
if self.file_registry_callback:
self.file_registry_callback(file['file_id'], {
'blockchain_pinned': True,
'pin_tx': tx_hash.hex(),
'pin_date': datetime.now().isoformat(),
'pin_duration_days': self.duration_var.get(),
'pin_network': self.network_var.get(),
'pin_gas_used': actual_gas_used,
'pin_gas_price_gwei': float(gas_price_gwei)
})
else: