-
Notifications
You must be signed in to change notification settings - Fork 0
/
rdisc.py
1350 lines (1194 loc) · 59 KB
/
rdisc.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import rdisc_kv
from enclib import hash_a_file, to_base, pass_to_key, enc_from_key, dec_from_pass, dec_from_key
from base64 import b32encode
from datetime import datetime
from hashlib import sha512
from os import path, mkdir, listdir
from random import randint, uniform, choices
from socket import socket
from threading import Thread
from time import perf_counter, sleep
from zlib import error as zl_error
from kivy.app import App as KivyApp
from kivy.clock import Clock
from kivy.config import Config
from kivy.core.window import Window
from kivy.factory import Factory
from kivy.lang import Builder
from kivy.properties import StringProperty, ObjectProperty
from kivy.graphics import Line, Color, RoundedRectangle
from kivy.utils import platform, get_color_from_hex as rgb
from kivy.uix.image import AsyncImage
from kivy.uix.label import Label
from kivy.uix.screenmanager import ScreenManager, Screen
from rsa import newkeys, PublicKey, decrypt
# hashes client file
if path.exists("rdisc.exe"):
app_hash = hash_a_file("rdisc.exe")
elif path.exists("rdisc.py"):
app_hash = hash_a_file("rdisc.py")
else:
app_hash = f"Unknown distro: {platform}"
# updates sha.txt with new app_hash
version = None
if path.exists("sha.txt"):
rdisc_kv.kv()
with open("sha.txt", "r", encoding="utf-8") as f:
latest_sha_, version, tme_, bld_num_, run_num_ = f.readlines()[-1].split("§")
print("prev", version, tme_, bld_num_, run_num_)
release_major, major, build, run = version.replace("V", "").split(".")
if latest_sha_ != app_hash:
run = int(run)+1
with open("sha.txt", "a+", encoding="utf-8") as f:
f.write(f"\n{app_hash}§V{release_major}.{major}.{build}.{run}"
f"§TME-{str(datetime.now())[:-4].replace(' ', '_')}"
f"§BLD_NM-{bld_num_[7:]}§RUN_NM-{int(run_num_[7:])+1}")
print(f"crnt V{release_major}.{major}.{build}.{run} "
f"TME-{str(datetime.now())[:-4].replace(' ', '_')} "
f"BLD_NM-{bld_num_[7:]} RUN_NM-{int(run_num_[7:])+1}")
print(f"Running rdisc V{release_major}.{major}.{build}.{run}")
default_salt = "52gy\"J$&)6%0}fgYfm/%ino}PbJk$w<5~j'|+R .bJcSZ.H&3z'A:gip/jtW$6A=G-;|&&rR81!BTElChN|+\"T"
# server class containing connection algorithm and data transfer functions
class Server:
def __init__(self):
self.s, self.enc_key = socket(), None
if path.exists("app/server_ip"):
with open(f"app/server_ip", "rb") as f:
self.ip = f.read().decode().split(":")
else:
self.ip = None
def connect(self): # connect to server
try:
self.s.connect((self.ip[0], int(self.ip[1])))
print("Connected to server")
l_ip, l_port = str(self.s).split("laddr=")[1].split("raddr=")[0][2:-3].split("', ")
s_ip, s_port = str(self.s).split("raddr=")[1][2:-2].split("', ")
print(f" << Server connected via {l_ip}:{l_port} -> {s_ip}:{s_port}")
pub_key, pri_key = newkeys(512)
try:
self.s.send(PublicKey.save_pkcs1(pub_key))
except ConnectionResetError:
return False
print(" >> Public RSA key sent")
enc_seed = decrypt(self.s.recv(128), pri_key).decode()
self.enc_key = pass_to_key(enc_seed[:18], enc_seed[18:], 100000)
print(" << Client enc_seed and enc_salt received and loaded\n -- RSA Enc bootstrap complete")
return True
except ConnectionRefusedError:
print("Connection refused")
return False
def send_e(self, text): # encrypt and send data to server
try:
self.s.send(enc_from_key(text, self.enc_key))
except ConnectionResetError:
print("CONNECTION_LOST, reconnecting...")
if s.ip and s.connect():
self.s.send(enc_from_key(text, self.enc_key))
else:
print("Failed to reconnect")
def recv_d(self, buf_lim=1024): # receive and decrypt data to server
try:
return dec_from_key(self.s.recv(buf_lim), self.enc_key)
except ConnectionResetError:
print("CONNECTION_LOST, reconnecting...")
if s.ip and s.connect():
return dec_from_key(self.s.recv(buf_lim), self.enc_key)
else:
print("Failed to reconnect")
# creates a popup
def popup(popup_type, reason):
App.popup_text = reason
if popup_type == "error":
App.popup = Factory.ErrorPopup()
if popup_type == "success":
App.popup = Factory.SuccessPopup()
App.popup.open()
# connects to sever with ip and port from file or user input
def connect_system():
if s.ip and s.connect():
print("Loading account keys...")
if path.exists(f'userdata/key'):
with open(f'userdata/key', 'rb') as f:
key_data = f.read()
print(" - Key data loaded")
App.uid, App.ipk = str(key_data[:8])[2:-1], key_data[8:]
App.sm.switch_to(KeyUnlock(), direction="left")
else:
print(" - No keys found")
App.sm.switch_to(LogInOrSignUp(), direction="left")
else: # connection failed, switch to ip input screen
App.sm.switch_to(IpSet(), direction="left")
# screen to run connect_system()
class AttemptConnection(Screen):
def on_enter(self, *args):
Clock.schedule_once(lambda dt: connect_system(), 1) # todo make this retry
# screen to set a new ip and port
class IpSet(Screen):
@staticmethod
def try_connect(ip_address):
if ip_address == "":
popup("error", "IP Blank\n- Type an IP into the IP box")
else:
try:
server_ip, server_port = ip_address.split(":")
server_port = int(server_port)
except ValueError or NameError:
popup("error", "Invalid IP address\n- Please type a valid IP")
else:
if server_port < 1 or server_port > 65535:
popup("error", "IP Port Invalid\n- Port must be between 1 and 65535")
else:
try:
ip_1, ip_2, ip_3, ip_4 = server_ip.split(".")
if all(i.isdigit() and 0 <= int(i) <= 255 for i in [ip_1, ip_2, ip_3, ip_4]):
s.ip = [server_ip, server_port]
App.sm.switch_to(AttemptConnection(), direction="left")
else:
popup("error", "IP Address Invalid\n- Address must have integers between 0 and 255")
except ValueError or NameError:
popup("error", "IP Address Invalid\n- Address must be in the format 'xxx.xxx.xxx.xxx")
# default screen to show after connection if no keys are found
class LogInOrSignUp(Screen):
pass
# screen to unlock ip key
class KeyUnlock(Screen):
passcode_prompt_text = StringProperty()
pwd = ObjectProperty(None)
counter = 0
def on_pre_enter(self, *args):
self.passcode_prompt_text = f"Enter passcode for account {App.uid}"
if path.exists("password.txt"): # this is for testing ONLY
with open("password.txt", "r") as f:
self.pwd.text = f.read()
self.login()
def login(self):
if self.pwd.text == "":
self.counter += 1
if self.counter != 3:
popup("error", "Password Blank\n- Top tip, type something in the password box.")
else:
popup("error", "Password Blank\n- WHY IS THE BOX BLANK?")
else:
try:
user_pass = pass_to_key(self.pwd.text, default_salt, 50000)
ipk = dec_from_pass(App.ipk, user_pass[:40], user_pass[40:])
s.send_e(f"ULK:{App.uid}{ipk}")
ulk_resp = s.recv_d(128)
if ulk_resp == "SESH_T":
popup("error", "This accounts session is taken.")
elif ulk_resp == "N":
popup("error", "Incorrect Password\n- How exactly did you manage to trigger this.")
self.pwd.text = ""
else:
App.uname, App.xp, App.r_coin, App.d_coin = ulk_resp.split("")
if App.r_coin.endswith(".0"):
App.r_coin = App.r_coin[:-2]
if App.d_coin.endswith(".0"):
App.d_coin = App.d_coin[:-2]
App.sm.switch_to(Home(), direction="left")
except zl_error:
popup("error", "Incorrect Password")
self.pwd.text = ""
# screen to create a new account master key
class CreateKey(Screen):
pass_code_text = StringProperty()
pin_code_text = StringProperty()
rand_confirm_text = StringProperty()
rand_confirmation = None
def generate_master_key(self, master_key, salt, depth_time, current_depth=0):
sleep(0.2)
start, time_left, loop_timer = perf_counter(), depth_time, perf_counter()
if not path.exists("userdata"):
mkdir("userdata")
while time_left > 0:
current_depth += 1
master_key = sha512(master_key+salt).digest()
if perf_counter()-loop_timer > 0.25:
try:
time_left -= (perf_counter()-loop_timer)
loop_timer = perf_counter()
real_dps = int(round(current_depth/(perf_counter()-start), 0))
print(f"Runtime: {round(perf_counter()-start, 2)}s "
f"Time Left: {round(time_left, 2)}s "
f"DPS: {round(real_dps/1000000, 3)}M "
f"Depth: {current_depth}/{round(real_dps*time_left, 2)} "
f"Progress: {round((depth_time-time_left)/depth_time*100, 3)}%")
self.pin_code_text = f"Generating Key and Pin ({round(time_left, 2)}s left)"
except ZeroDivisionError:
pass
App.mkey = to_base(96, 16, master_key.hex())
self.rand_confirmation = str(randint(0, 9))
self.pin_code_text = f"Account Pin: {to_base(36, 10, current_depth)}"
self.rand_confirm_text = f"Once you have written down your Account Key " \
f"and Pin enter {self.rand_confirmation} below.\n" \
f"By proceeding with account creation you agree to our Terms and Conditions."
App.pin_code = to_base(36, 10, current_depth)
def on_pre_enter(self, *args):
App.path = "make"
acc_key = "".join(choices("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", k=int(15)))
time_depth = uniform(3, 5)
Thread(target=self.generate_master_key, args=(acc_key[:6].encode(),
acc_key[6:].encode(), time_depth,), daemon=True).start()
self.pin_code_text = f"Generating Key and Pin ({time_depth}s left)"
acc_key_print = f"{acc_key[:5]}-{acc_key[5:10]}-{acc_key[10:15]}"
self.pass_code_text = f"Your Account Key is: {acc_key_print}"
App.acc_key = acc_key
def continue_confirmation(self, confirmation_code):
if self.rand_confirmation:
if confirmation_code == "":
popup("error", "Confirmation Empty")
elif confirmation_code == self.rand_confirmation:
if platform in ["win", "linux"]:
App.sm.switch_to(UsbSetup(), direction="left")
else:
App.sm.switch_to(Captcha(), direction="left")
else:
popup("error", "Incorrect Confirmation Number")
# screen to set up a USB to write the master key to
class UsbSetup(Screen):
usb_text = StringProperty()
skip_text = StringProperty()
def check_usb(self): # todo linux version
dl = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
before_drives = [f"{d}:\\" for d in dl if path.exists(f"{d}:\\")]
while True:
now_drives = [f"{d}:\\" for d in dl if path.exists(f"{d}:\\")]
if before_drives != now_drives:
try:
new_drive = [d for d in now_drives if d not in before_drives][0]
break
except IndexError:
before_drives = [f"{d}:\\" for d in dl if path.exists(f"{d}:\\")]
sleep(0.1)
App.new_drive = new_drive
self.usb_text = f"USB detected at {new_drive}\n" \
f"Do not unplug USB until your account is created and you are on the home screen"
self.skip_text = "Continue"
def on_pre_enter(self, *args):
self.usb_text = "Detecting USB drive....\nPlease connect your USB drive\n" \
"(If it is already connected please disconnect and reconnect it)"
self.skip_text = "Skip USB setup"
Thread(target=self.check_usb, daemon=True).start()
# screen to collect data for regenerate master key
class ReCreateKey(Screen):
load_text = StringProperty()
name_or_uid = ObjectProperty()
pass_code = ObjectProperty()
pin_code = ObjectProperty()
drive = None
def on_pre_enter(self, *args):
self.load_text = "Load from USB"
def load_data(self):
with open(self.drive+"mkey", "r", encoding="utf-8") as f:
self.name_or_uid.text, self.pass_code.text, self.pin_code.text = f.read().split("")
def detect_usb(self):
dl = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
before_drives = [f"{d}:\\" for d in dl if path.exists(f"{d}:\\")]
while True: # check all possible new drives
now_drives = [f"{d}:\\" for d in dl if path.exists(f"{d}:\\")]
if before_drives != now_drives:
try:
new_drive = [d for d in now_drives if d not in before_drives][0]
break
except IndexError:
before_drives = [f"{d}:\\" for d in dl if path.exists(f"{d}:\\")]
sleep(0.1)
self.load_text = "USB loaded"
self.drive = new_drive
Clock.schedule_once(lambda dt: self.load_data())
def load_from_usb(self):
self.load_text = "Detecting USB"
self.ids.load_from_usb_button.disabled = True
Thread(target=self.detect_usb, daemon=True).start()
def toggle_button(self):
if len(self.name_or_uid.text) == 8 and len(self.pass_code.text) == 15 and self.pin_code.text:
self.ids.start_regen_button.disabled = False
elif 8 < len(self.name_or_uid.text) < 29 and "#" in self.name_or_uid.text and \
len(self.pass_code.text) == 15 and self.pin_code.text:
self.ids.start_regen_button.disabled = False
else:
self.ids.start_regen_button.disabled = True
def start_regeneration(self):
if len(self.name_or_uid.text) == 8 and len(self.pass_code.text) == 15 and self.pin_code.text:
App.path, App.uid = "login", self.name_or_uid.text
App.pass_code, App.pin_code = self.pass_code.text, self.pin_code.text
App.sm.switch_to(ReCreateGen(), direction="left")
if 8 < len(self.name_or_uid.text) < 29 and "#" in self.name_or_uid.text and \
len(self.pass_code.text) == 15 and self.pin_code.text:
App.path, App.uname = "login", self.name_or_uid.text
App.pass_code, App.pin_code = self.pass_code.text, self.pin_code.text
App.sm.switch_to(ReCreateGen(), direction="left")
# screen to regenerate master key
class ReCreateGen(Screen):
gen_left_text = StringProperty()
def regenerate_master_key(self, master_key, salt, depth_to, current_depth=0):
start, depth_left, loop_timer = perf_counter(), depth_to-current_depth, perf_counter()
for depth_count in range(1, depth_left+1):
master_key = sha512(master_key+salt).digest()
if perf_counter()-loop_timer > 0.25:
try:
loop_timer = perf_counter()
real_dps = int(round(depth_count/(perf_counter()-start), 0))
print(f"Runtime: {round(perf_counter()-start, 2)}s "
f"Time Left: {round((depth_left-depth_count)/real_dps, 2)}s "
f"DPS: {round(real_dps/1000000, 3)}M "
f"Depth: {current_depth+depth_count}/{depth_to} "
f"Progress: {round((current_depth+depth_count)/depth_to*100, 3)}%")
self.gen_left_text = f"Generating master key " \
f"({round((depth_left-depth_count)/real_dps, 2)}s left)"
except ZeroDivisionError:
pass
App.mkey = to_base(96, 16, master_key.hex())
Clock.schedule_once(lambda dt: App.sm.switch_to(Captcha(), direction="left"))
def on_enter(self, *args):
self.gen_left_text = f"Generating master key"
Thread(target=self.regenerate_master_key, args=(App.pass_code[:6].encode(),
App.pass_code[6:].encode(), int(to_base(10, 36, App.pin_code)),), daemon=True).start()
# screen to verify a captcha
class Captcha(Screen):
captcha_prompt_text = StringProperty()
captcha_inp = ObjectProperty(None)
def on_pre_enter(self, *args):
self.captcha_prompt_text = "Waiting for captcha..."
def on_enter(self, *args):
s.send_e("CAP")
self.get_captcha()
def get_captcha(self):
image = s.recv_d(32768) # todo remove the need for a file
with open('captcha.jpg', 'wb') as f:
f.write(image)
self.captcha_prompt_text = f"Enter the text below"
self.ids.captcha_image.source = 'captcha.jpg'
def try_captcha(self):
if len(self.captcha_inp.text) == 10:
s.send_e(self.captcha_inp.text.replace(" ", "").replace("1", "I").replace("0", "O").upper())
if s.recv_d() != "V":
popup("error", "Captcha Failed")
elif App.path == "make":
App.sm.switch_to(NacPass(), direction="left")
elif App.path == "login":
if App.uname:
s.send_e(f"LOG:{App.mkey}u{App.uname}")
else:
s.send_e(f"LOG:{App.mkey}i{App.uid}")
log_resp = s.recv_d()
if log_resp == "IMK":
popup("error", "Invalid Master Key")
App.sm.switch_to(ReCreateKey(), direction="left")
elif log_resp == "NU":
popup("error", "Username/UID does not exist")
App.sm.switch_to(ReCreateKey(), direction="right")
else:
if App.uname:
App.uid = s.recv_d()
App.sm.switch_to(LogUnlock(), direction="left")
# screen to create a new password
class NacPass(Screen):
nac_password_1 = ObjectProperty(None)
nac_password_2 = ObjectProperty(None)
def set_nac_password(self):
if self.nac_password_1.text == "":
popup("error", "Password 1 Blank")
elif self.nac_password_2.text == "":
popup("error", "Password 2 Blank")
elif len(self.nac_password_1.text) < 9:
popup("error", "Password Invalid\n- Password must be at least 9 characters")
elif self.nac_password_1.text != self.nac_password_2.text:
popup("error", "Password Mismatch\n- Passwords must be the same")
else:
pass_send = pass_to_key(self.nac_password_1.text, default_salt, 50000)
if App.path == "CHANGE_PASS":
s.send_e(pass_send)
App.sm.switch_to(TwoFacLog(), direction="left")
else:
s.send_e(f"NAC:{App.mkey}{pass_send}")
App.sm.switch_to(TwoFacSetup(), direction="left")
# screen to log in to an account
class LogUnlock(Screen):
pwd = ObjectProperty(None)
passcode_prompt_text = StringProperty()
def on_pre_enter(self, *args):
self.passcode_prompt_text = f"Enter passcode for account {App.uid}"
def login(self):
if self.pwd.text == "":
popup("error", "Password Blank\n- The question is, why is it blank?")
else:
try:
user_pass = pass_to_key(self.pwd.text, default_salt, 50000)
s.send_e(user_pass)
ipk = s.recv_d()
if ipk == "N":
popup("error", "Incorrect Password\n- How exactly did you manage to trigger this")
self.pwd.text = ""
else:
App.ipk = ipk
App.sm.switch_to(TwoFacLog(), direction="left")
except zl_error:
popup("error", "Incorrect Password")
self.pwd.text = ""
# screen to set up 2fa
class TwoFacSetup(Screen):
two_fac_wait_text = StringProperty()
two_fac_code = ObjectProperty(None)
def on_pre_enter(self, *args):
self.two_fac_wait_text = "Waiting for 2fa QR code..."
def on_enter(self, *args):
App.uid, secret_code = s.recv_d().split("")
secret_code = b32encode(secret_code.encode()).decode().replace('=', '')
print(secret_code) # todo mention in UI text
self.ids.two_fac_qr.source = "https://chart.googleapis.com/chart?cht=qr&chs=300x300&chl=otpauth%3A%2" \
f"F%2Ftotp%2F{App.uid}%3Fsecret%3D{secret_code}%26issuer%3DRdisc"
self.two_fac_wait_text = "Scan this QR with your authenticator, then enter code to confirm.\n" \
f"Your User ID (UID) is {App.uid}"
def confirm_2fa(self):
if self.two_fac_code.text == "":
popup("error", "2FA Code Blank\n- Please enter a 2FA code")
elif len(self.two_fac_code.text) != 6:
popup("error", "Invalid 2FA Code")
else:
s.send_e(self.two_fac_code.text.replace(" ", ""))
ipk = s.recv_d()
if ipk == "N":
popup("error", "2FA Failed\n- Please Try Again")
else:
with open("userdata/key", "wb") as f:
f.write(App.uid.encode()+ipk)
App.uname, App.xp, App.r_coin, App.d_coin = s.recv_d().split("")
if App.r_coin.endswith(".0"):
App.r_coin = App.r_coin[:-2]
if App.d_coin.endswith(".0"):
App.d_coin = App.d_coin[:-2]
if App.new_drive:
with open(f"{App.new_drive}mkey", "w", encoding="utf-8") as f:
f.write(f"{App.uid}{App.acc_key}{App.pin_code}")
App.sm.switch_to(Home(), direction="left")
# screen to verify 2fa code on login
class TwoFacLog(Screen):
two_fac_code = ObjectProperty(None)
def confirm_2fa(self):
if self.two_fac_code.text == "":
popup("error", "2FA Code Blank\n- Please enter a 2FA code")
elif len(self.two_fac_code.text) != 6:
popup("error", "Invalid 2FA Code")
else:
s.send_e(self.two_fac_code.text.replace(" ", ""))
two_fa_valid = s.recv_d()
if two_fa_valid == "N":
popup("error", "2FA Failed\n- Please Try Again")
elif App.path == "CHANGE_PASS":
with open("userdata/key", "wb") as f:
f.write(App.uid.encode()+two_fa_valid)
App.sm.switch_to(Settings(), direction="left")
popup("success", "Password Changed")
else:
with open("userdata/key", "wb") as f:
f.write(App.uid.encode()+App.ipk)
App.uname, App.xp, App.r_coin, App.d_coin = two_fa_valid.split("")
if App.r_coin.endswith(".0"):
App.r_coin = App.r_coin[:-2]
if App.d_coin.endswith(".0"):
App.d_coin = App.d_coin[:-2]
App.sm.switch_to(Home(), direction="left")
# the home screen
class Home(Screen):
r_coins = StringProperty()
d_coins = StringProperty()
welcome_text = StringProperty()
transfer_uid = ObjectProperty(None)
transfer_amt = ObjectProperty(None)
transfer_cost = StringProperty()
transfer_send = StringProperty()
transfer_fee = StringProperty()
direction_text = StringProperty()
coin_conversion = StringProperty()
code = ObjectProperty(None)
transfer_direction = "R"
level_progress = [0, 100]
transactions_counter = 0
def update_level_bar(self):
self.level_progress = [round(float(App.xp), 2), 100]
self.ids.level_bar_text.text = f"{self.level_progress[0]} XP"
#self.ids.level_bar_text.text = f"{self.level_progress[0]}/{self.level_progress[1]} XP"
#with self.ids.level_bar.canvas:
# Color(*App.col["yellow"])
# RoundedRectangle(pos=self.ids.level_bar.pos,
# size=(self.ids.level_bar.size[0]*self.level_progress[0]/self.level_progress[1],
# self.ids.level_bar.size[1]))
def on_enter(self, *args):
self.r_coins = App.r_coin+" R"
self.d_coins = App.d_coin+" D"
Clock.schedule_once(lambda dt: self.update_level_bar())
[self.add_transaction(transaction) for transaction in App.transactions]
App.transactions = []
def add_transaction(self, transaction):
self.ids.transactions.add_widget(Label(text=transaction, font_size=16, color=(1, 1, 1, 1), size_hint_y=None,
height=40+transaction.count("\n")*20, halign="left", markup=True))
self.transactions_counter += 1
if self.ids.transactions_scroll.scroll_y == 0:
scroll_down = True
else:
scroll_down = False
if self.transactions_counter > 101:
self.ids.transactions.remove_widget(self.ids.public_chat.children[-1])
self.ids.transactions.children[-1].text = "ONLY SHOWING LATEST 100 TRANSACTIONS"
self.transactions_counter -= 1
message_height = 0
for i in reversed(range(self.transactions_counter)):
self.ids.transactions.children[i].y = message_height
self.ids.transactions.children[i].x = 0
message_height += self.ids.transactions.children[i].height
self.ids.transactions.height = message_height
if scroll_down:
self.ids.transactions_scroll.scroll_y = 0
else:
pass # todo make stay still
def on_pre_enter(self, *args):
self.r_coins = App.r_coin+" R"
self.d_coins = App.d_coin+" D"
self.welcome_text = f"Welcome back {App.uname}"
self.transfer_cost = "0.00"
self.transfer_send = "0.00"
self.transfer_fee = "0.00"
self.coin_conversion = "0.00 R"
self.direction_text = "Conversion Calculator (£->R)"
def check_transfer(self): # check if transfer is valid
if self.transfer_amt.text != "":
self.transfer_amt.text = self.transfer_amt.text[:12]
if float(self.transfer_amt.text) > float(App.r_coin)*0.995:
self.transfer_amt.text = str(round(float(App.r_coin)*0.995, 2))
if "." in self.transfer_amt.text:
if len(self.transfer_amt.text.split(".")[1]) > 2:
self.transfer_amt.text = self.transfer_amt.text[:-1]
self.transfer_cost = str(round(float(self.transfer_amt.text)/0.995, 2))
self.transfer_send = self.transfer_amt.text
self.transfer_fee = str(round(float(self.transfer_cost)-float(self.transfer_amt.text), 2))
if self.transfer_amt.text == ".":
self.transfer_amt.text = ""
if self.transfer_amt.text == "":
self.transfer_cost = "0.00"
self.transfer_send = "0.00"
self.transfer_fee = "0.00"
def transfer_coins(self):
if self.transfer_amt.text in ["", "."]:
popup("error", "Below Minimum Transfer\n- Transaction amount below the 3 R minimum")
elif len(self.transfer_uid.text) < 8:
popup("error", "Invalid Username/UID For Transfer")
elif self.transfer_uid.text == App.uid or self.transfer_uid.text == App.uname:
popup("error", "You cannot transfer funds to yourself\n- WHY ARE YOU EVEN TRYING TO?!")
elif float(self.transfer_amt.text) < 3:
popup("error", "Below Minimum Transfer\n- Transaction amount below the 3 R minimum")
elif float(self.transfer_amt.text) > float(App.r_coin)*0.995:
popup("error", "Insufficient funds For Transfer")
else:
s.send_e(f"TRF:{self.transfer_uid.text}{self.transfer_amt.text}")
if s.recv_d() != "V":
popup("error", "Invalid Username/UID For Transfer")
else:
popup("success", f"Transfer of {self.transfer_amt.text} R to {self.transfer_uid.text} Successful")
self.add_transaction(f"Sent [color=f46f0eff]{self.transfer_amt.text} R[/color] "
f"to {self.transfer_uid.text}")
App.r_coin = str(round(float(App.r_coin)-float(self.transfer_amt.text)/0.995, 2))
if App.r_coin.endswith(".0"):
App.r_coin = App.r_coin[:-2]
self.r_coins = App.r_coin+" R"
self.transfer_uid.text = ""
self.transfer_amt.text = ""
def check_code(self):
if not len(self.code.text) == 19:
popup("error", "Invalid Code\n- Does not match format xxxx-xxxx-xxxx-xxxx")
elif not self.code.text[5] == "-" and self.code.text[10] == "-" and self.code.text[15] == "-":
popup("error", "Invalid Code\n- Does not match format xxxx-xxxx-xxxx-xxxx")
else:
s.send_e(f"CLM:{self.code.text}")
code_resp = s.recv_d()
if code_resp != "N":
if code_resp.startswith("R"):
App.r_coin = str(round(float(App.r_coin)+float(code_resp[2:]), 2))
if App.r_coin.endswith(".0"):
App.r_coin = App.r_coin[:-2]
self.r_coins = App.r_coin+" R"
popup("success", f"Successfully claimed {code_resp[2:]} R")
self.add_transaction(f"Claimed [color=f46f0eff]{code_resp[2:]} R[/color] from gift code")
else:
popup("error", "Invalid Code")
def convert_coins(self, amount_convert):
if amount_convert not in ["", "."]:
amount_convert = amount_convert[:7]
if "." in amount_convert:
if len(amount_convert.split(".")[1]) > 2:
amount_convert = amount_convert[:-1]
if self.transfer_direction == "R":
amount_converted = str(round(float(amount_convert)/0.06, 2))
else:
amount_converted = str(round(float(amount_convert)*0.0585, 2))
if "." in amount_converted:
amount_converted = amount_converted[:amount_converted.index(".")+3]
if self.transfer_direction == "R":
self.coin_conversion = f"{amount_converted} R"
else:
self.coin_conversion = f"£{amount_converted}"
else:
if amount_convert == "":
if self.transfer_direction == "R":
self.coin_conversion = "0.00 R"
else:
self.coin_conversion = "£0.00"
def change_conversion_direction(self):
if self.transfer_direction == "R":
self.transfer_direction = "D"
self.direction_text = "Conversion Calculator (R->£)"
else:
self.transfer_direction = "R"
self.direction_text = "Conversion Calculator (£->R)"
# screen for public chat room
class Chat(Screen):
r_coins = StringProperty()
d_coins = StringProperty()
public_room_msg_counter = 0
public_room_inp = ObjectProperty(None)
def msg_watch(self): # look for new messages
s.send_e("JNC")
while True:
msg_author, msg_content = s.recv_d().split("")
if msg_author == "LVC":
break
Clock.schedule_once(lambda dt: self.add_msg(msg_author[:-4], msg_content))
def on_pre_enter(self, *args):
self.r_coins = App.r_coin+" R"
self.d_coins = App.d_coin+" D"
Thread(target=self.msg_watch, daemon=True).start()
def on_leave(self, *args): # on leave stop looking for new messages
s.send_e("LVC")
def add_msg(self, name, text):
if "https://" in text or "http://" in text:
self.ids.public_chat.add_widget(AsyncImage(source=text, size_hint_y=None, height=300, anim_delay=0.05))
else:
self.ids.public_chat.add_widget(Label(text=f"[color=#14e42bff]{name}[/color] [color=#858d8fff] "
f"{str(datetime.now())[:-7]}[/color] {text}", font_size=16,
color=(1, 1, 1, 1), size_hint_y=None, height=40, markup=True))
self.public_room_msg_counter += 1
if self.ids.public_room_scroll.scroll_y == 0:
scroll_down = True
else:
scroll_down = False
if self.public_room_msg_counter > 101:
self.ids.public_chat.remove_widget(self.ids.public_chat.children[-1])
self.ids.public_chat.children[-1].text = "MESSAGES ABOVE DELETED DUE 100 MESSAGE LIMIT"
self.public_room_msg_counter -= 1
message_height = 0
for i in range(self.public_room_msg_counter):
self.ids.public_chat.children[i].y = message_height
self.ids.public_chat.children[i].x = 0
message_height += self.ids.public_chat.children[i].height
self.ids.public_chat.height = message_height
if scroll_down:
self.ids.public_room_scroll.scroll_y = 0
else:
pass # todo make stay still
def send_public_message(self):
if self.public_room_inp.text != "":
self.add_msg(App.uname[:-4], self.public_room_inp.text)
s.send_e(f"{self.public_room_inp.text}")
self.public_room_inp.text = ""
# screen for the store
class Store(Screen):
r_coins = StringProperty()
d_coins = StringProperty()
def on_pre_enter(self, *args):
self.r_coins = App.r_coin+" R"
self.d_coins = App.d_coin+" D"
# screen for selecting a game
class Games(Screen):
r_coins = StringProperty()
d_coins = StringProperty()
def on_pre_enter(self, *args):
self.r_coins = App.r_coin+" R"
self.d_coins = App.d_coin+" D"
# screen for viewing inventory items
class Inventory(Screen):
r_coins = StringProperty()
d_coins = StringProperty()
def on_pre_enter(self, *args):
self.r_coins = App.r_coin+" R"
self.d_coins = App.d_coin+" D"
# screen for changing account details and other settings
class Settings(Screen):
r_coins = StringProperty()
d_coins = StringProperty()
uname = StringProperty()
uid = StringProperty()
uname_to = ObjectProperty(None)
n_pass = ObjectProperty(None)
def on_pre_enter(self, *args):
self.r_coins = App.r_coin+" R"
self.d_coins = App.d_coin+" D"
self.uname = App.uname
self.uid = App.uid
def change_name(self):
if float(App.d_coin) < 5:
popup("error", "Insufficient Funds\n- You require 5 D to change your username")
elif 4 < len(self.uname_to.text) < 25:
s.send_e(f"CUN:{self.uname_to.text}")
new_uname = s.recv_d()
if new_uname != "N":
App.uname = new_uname
self.uname = App.uname
App.d_coin = str(round(float(App.d_coin)-5, 2))
if App.d_coin.endswith(".0"):
App.d_coin = App.d_coin[:-2]
self.d_coins = App.d_coin+" D"
popup("success", f"Username changed to {self.uname}")
App.transactions.append(f"Spent [color=#16c2e1ff]5 D[/color] to change username to "
f"[color=#14e42aff]{self.uname}[/color]")
else:
popup("error", "Invalid Username\n- Username must be between 5 and 24 characters")
def change_pass(self):
if len(self.n_pass.text) < 9:
popup("error", "Password Invalid\n- Password must be at least 9 characters")
else:
s.send_e(f"CUP:{pass_to_key(self.n_pass.text, default_salt, 50000)}")
if s.recv_d() == "V":
App.path = "CHANGE_PASS"
App.sm.switch_to(NacPass(), direction="left")
else:
popup("error", "Incorrect Password\n- Please try again")
# screen for changing the colour scheme
class ColorSettings(Screen):
r_coins = StringProperty()
d_coins = StringProperty()
selected_color = None
color_list_old = None
def on_pre_enter(self, *args):
self.r_coins = App.r_coin+" R"
self.d_coins = App.d_coin+" D"
self.color_list_old = App.col.copy()
def select_color(self, color_name):
self.selected_color = color_name
self.ids.color_picker.color = App.col[color_name]
def change_color(self, color=None):
if not color:
color = [round(col, 5) for col in self.ids.color_picker.color]
if self.selected_color is not None:
App.col[self.selected_color] = color
with self.ids[self.selected_color+"_btn"].canvas:
Color(*color)
RoundedRectangle(size=self.ids[self.selected_color+"_btn"].size,
pos=self.ids[self.selected_color+"_btn"].pos, radius=[10])
def reset_colors(self, color=None):
if self.selected_color:
if color:
self.change_color(self.color_list_old[self.selected_color])
else:
for color in App.col:
self.selected_color = color
self.change_color(self.color_list_old[color])
@staticmethod # call reload from KV file
def reload():
reload("reload")
@staticmethod
def save_colors():
with open("color_scheme.txt", "w", encoding="utf-8") as f:
f.write(f"# CUSTOM COLOR SCHEME #\n")
for color in App.col:
hex_color = " #"
for rgb1 in App.col[color]:
hex_color += hex(int(rgb1*255))[2:].zfill(2)
f.write(f"{color}:{hex_color}\n")
def default_theme(self, theme): # set default theme
if theme in ["purple", "pink", "green", "lime"]:
App.col = App.theme[theme]
for color in App.col:
self.selected_color = color
self.change_color(App.theme[theme][color])
# store screen for buying gift cards
class GiftCards(Screen):
r_coins = StringProperty()
d_coins = StringProperty()
def on_pre_enter(self, *args):
self.r_coins = App.r_coin+" R"
self.d_coins = App.d_coin+" D"
def buy_gift_card(self, amount):
if float(App.r_coin) >= float(amount):
s.send_e(f"BGC:{amount}")
gift_code = s.recv_d()
App.r_coin = str(round(float(App.r_coin)-float(amount), 2))
if App.r_coin.endswith(".0"):
App.r_coin = App.r_coin[:-2]
self.r_coins = App.r_coin+" R"
popup("success", f"Successfully bought {amount} R gift card\nCode: {gift_code}\n\n"
f"To view this code again,\ngo to your transaction history")
App.transactions.append(f"Bought [color=f46f0eff]{amount} R gift card[/color] for [color=f46f0eff]"
f"{amount} R[/color]\n Code: [color=25be42ff]{gift_code}[/color]")
else:
popup("error", "Insufficient Funds\n- You require more R Coins")
# store screen for buying data coins
class DataCoins(Screen):
r_coins = StringProperty()
d_coins = StringProperty()
def on_pre_enter(self, *args):
self.r_coins = App.r_coin+" R"
self.d_coins = App.d_coin+" D"
def buy_d(self, amount):
if float(App.r_coin) < float(amount):
popup("error", "Insufficient Funds\n- You require more R Coins")
else:
s.send_e(f"BYD:{amount}")
if s.recv_d() == "V":
App.r_coin = str(round(float(App.r_coin)-float(amount), 2))
d_amount = {15: 150, 35: 375, 50: 550, 100: 1150, 210: 2500}.get(amount)
App.d_coin = str(round(float(App.d_coin)+d_amount, 2))
if App.r_coin.endswith(".0"):
App.r_coin = App.r_coin[:-2]
if App.d_coin.endswith(".0"):
App.d_coin = App.d_coin[:-2]
self.d_coins = App.d_coin+" D"
self.r_coins = App.r_coin+" R"
popup("success", f"Successfully bought {d_amount} D for {amount} R")
App.transactions.append(f"Bought [color=15c1e0ff]{d_amount} D[/color] for "
f"[color=f46f0eff]{amount} R[/color]")
# draw a circle with segments and a rotation
def draw_circle(self, segments, rotation=0):
seg = [seg*0.36 for seg in segments]
with self.canvas:
seg_count = 0
total = 0
cols = [App.col['green'], App.col['red'], App.col['link_blue'], App.col['yellow'], App.col['orange']]
for i in range(len(segments)):
Color(*cols[i], mode="rgb")
Line(circle=[self.center[0], self.center[1]+(self.center[1]/7), 150, total+rotation,
seg[i]+rotation+total], width=18, cap="none")
total += seg[i]
seg_count += 1
# draw a coloured triangle
def draw_triangle(self, color):
with self.canvas:
Color(*App.col[color])
Line(points=[self.center[0], self.center[1]-(self.center[1]/2.5), self.center[0]-15,
self.center[1]-(self.center[1]/2.5)-30, self.center[0]+15, self.center[1]-(self.center[1]/2.5)-30,
self.center[0], self.center[1]-(self.center[1]/2.5)], width=2, cap="none")
# update a canvas with a color
def canvas_update(canvas, color):
with canvas.canvas:
Color(*color)
RoundedRectangle(size=canvas.size, pos=canvas.pos, radius=[10])
# check outcome of value against odds
def check_odd(odds, value): # todo make support multiple odds
value = float(str(round(value/360, 3)).split(".")[1])
if 500-odds[0] <= value < 500: