forked from jamescoxon/RetroXRBWallet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gui.py
723 lines (593 loc) · 26.4 KB
/
gui.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
#TODO
#Previous - could reduce server involvement by storing previous hash, requesting server on boot + updating with each transaction
#Convert PoW to cpython or even a c binary that could be dropped in to increase speed (would also benefit from multicore support)
#Increase timeout on server
from pyblake2 import blake2b
import time
import threading
import tkinter
import websocket
import json
import sys
import os
from websocket import create_connection
import websocket
from tkinter import *
import tkinter.simpledialog as simpledialog
import tkinter.messagebox as messagebox
from tkinter import ttk
import base64
icon = "AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAQAACkuAAApLgAAAAAAAAAAAAAAAAAAAAAAAEm3SQBJt0kASbdJAEm3SQFFuEpBX7FBv72ZIL/WkhhB0pMZAdKTGQDSkxkA0pMZAAAAAAAAAAAASbdJAEm3SQBJt0kASbdJAEm3SSJJt0mKSLdJ6FqzQ//Clx//05MZ6NKTGYrSkxki0pMZANKTGQDSkxkA0pMZAD3HhABGulUASbdJEUm3SWtJt0nXSbdJ/0i3Sf9as0P+wpcf/tOTGf/Skxn/0pMZ2NKTGWvSkxkR0pMZANKTGQAz07ADR7lQSUm3R79Jt0n9SbdJ/0m3Sf9It0n/WrND/sKXH/7Tkxn/0pMZ/9KTGf/Skxn90pMZv9KTGUnSkxkDMda6FjnMlc5Dv2b/SbdK/0m3SP9Jt0n/R7dJ/1iyQf7Clxz+05MY/9KTGf/Skxn/0pMZ/9KTGf/SkxnP0pMZFjHWvBkx1r3UM9Sz/zvJi/5FvFr+SLdI/1C5UP+FwXv9y6te/dKWIv/Skxj/0pMZ/9KTGf/Skxn/0pMZ1NKTGRkw1rwZMNa81DDWvf8w173/MtKs/lbJi/2z0bH919jV/tHNyv7QvJf+0Zsz/tKSF//Skxn/0pMZ/9KTGdTSkxkZPdKsGT3SrNM90qz/PdKt/jrSrP512sH85+fm/d/d3PzS0c/90c/N/tOpU/3UlRf+1JYa/tSWGv/UlhrT1JYaGY22TxmMtk/TjLZP/4y2T/6Ltk3+p8R9/Nva2f3W1NP85uXk/OPh3/3ivFr85Ksa/uSsHv7krR7/5K0e0+StHhmasj8ZmrI/1JqyP/+asj//mas7/qOgS/29tZr9zcvH/u3s6f7x5sn97sdh/ei0KP7msB7/5rAf/+awH9TmsB8ZmbJAGZmzQNSZrz//mZ44/pqKL/6agiv/nIYz/7Oja/3s1Jf99dBz//XObP/zyWD+7L1A/ueyJP/msB7U5rAeGZmyQBaZozrOmo8x/5qDLP+agyz/moMs/5mCK/+kizL+6sVj/vbObP/1zmz/9c5t//XOa//xxln/67o4zuawIBaZrz8DmoYtSZqCLL+agyz9moMs/5qDLP+Zgiz/pYw0/urFZP72z2z/9c5s//XObP/1zmz99c5tv/TMZ0nosycDmZw3AJqILgCagywRmoMsa5qDLNeagyz/mYIs/6WMNP7qxWT+9s9s//XObP/1zmzY9c5sa/XObBHzy2QA7b9EAJqDLACagywAmoMsAJqDLACagywimoMsipmCK+iljDT/6sVk//bPbej1zmyK9c5sIvXObAD1zmwA9c5sAPXObAAAAAAAAAAAAJqDLACagywAmoMsAJqDLAGXgSpBqI82v+fCYr/40G5B9c5sAfXObAD1zmwA9c5sAAAAAAAAAAAAwAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAMAAA=="
icondata= base64.b64decode(icon)
tempFile= "logo.ico"
iconfile= open(tempFile,"wb")
iconfile.write(icondata)
iconfile.close()
root=Tk()
root.withdraw()
root.minsize(width=600, height=300)
root.wm_iconbitmap('logo.ico')
root.title('XRB Light Wallet')
def root_destroy():
root.destroy()
def address_to_clipboard(self=1):
root.clipboard_clear()
root.clipboard_append(account)
import binascii
import random, getpass
from bitstring import BitArray
from pure25519 import ed25519_oop as ed25519
from simplecrypt import encrypt, decrypt
from configparser import SafeConfigParser
import pyqrcode
default_representative = \
'xrb_16k5pimotz9zehjk795wa4qcx54mtusk8hc5mdsjgy57gnhbj3hj6zaib4ic'
raw_in_xrb = 1000000000000000000000000000000.0
choices = u'Send,Account History,Display QR Code,,Configure PoW,Configure Rep,Configure Server,,Refresh,Quit'.split(',')
running_pow_gen = False
class StringDialog(simpledialog._QueryString):
def body(self, master):
super().body(master)
self.iconbitmap('logo.ico')
def ask_string(title, prompt, **kargs):
d = StringDialog(title, prompt, **kargs)
return d.result
def xrb_account(address):
# Given a string containing an XRB address, confirm validity and
# provide resulting hex address
if len(address) == 64 and (address[:4] == 'xrb_'):
# each index = binary value, account_lookup[0] == '1'
account_map = "13456789abcdefghijkmnopqrstuwxyz"
account_lookup = {}
# populate lookup index with prebuilt bitarrays ready to append
for i in range(32):
account_lookup[account_map[i]] = BitArray(uint=i,length=5)
# we want everything after 'xrb_' but before the 8-char checksum
acrop_key = address[4:-8]
# extract checksum
acrop_check = address[-8:]
# convert base-32 (5-bit) values to byte string by appending each
# 5-bit value to the bitstring, essentially bitshifting << 5 and
# then adding the 5-bit value.
number_l = BitArray()
for x in range(0, len(acrop_key)):
number_l.append(account_lookup[acrop_key[x]])
# reduce from 260 to 256 bit (upper 4 bits are never used as account
# is a uint256)
number_l = number_l[4:]
check_l = BitArray()
for x in range(0, len(acrop_check)):
check_l.append(account_lookup[acrop_check[x]])
# reverse byte order to match hashing format
check_l.byteswap()
result = number_l.hex.upper()
# verify checksum
h = blake2b(digest_size=5)
h.update(number_l.bytes)
if (h.hexdigest() == check_l.hex):
return result
else:
return False
else:
return False
def account_xrb(account):
# Given a string containing a hex address, encode to public address
# format with checksum
# each index = binary value, account_lookup['00001'] == '3'
account_map = "13456789abcdefghijkmnopqrstuwxyz"
account_lookup = {}
# populate lookup index for binary string to base-32 string character
for i in range(32):
account_lookup[BitArray(uint=i,length=5).bin] = account_map[i]
# hex string > binary
account = BitArray(hex=account)
# get checksum
h = blake2b(digest_size=5)
h.update(account.bytes)
checksum = BitArray(hex=h.hexdigest())
# encode checksum
# swap bytes for compatibility with original implementation
checksum.byteswap()
encode_check = ''
for x in range(0,int(len(checksum.bin)/5)):
# each 5-bit sequence = a base-32 character from account_map
encode_check += account_lookup[checksum.bin[x*5:x*5+5]]
# encode account
encode_account = ''
while len(account.bin) < 260:
# pad our binary value so it is 260 bits long before conversion
# (first value can only be 00000 '1' or 00001 '3')
account = '0b0' + account
for x in range(0,int(len(account.bin)/5)):
# each 5-bit sequence = a base-32 character from account_map
encode_account += account_lookup[account.bin[x*5:x*5+5]]
# build final address string
return 'xrb_'+encode_account+encode_check
def private_public(private):
return ed25519.SigningKey(private).get_verifying_key().to_bytes()
def seed_account(seed, index):
# Given an account seed and index #, provide the account private and
# public keys
h = blake2b(digest_size=32)
seed_data = BitArray(hex=seed)
seed_index = BitArray(int=index,length=32)
h.update(seed_data.bytes)
h.update(seed_index.bytes)
account_key = BitArray(h.digest())
return account_key.bytes, private_public(account_key.bytes)
def get_pow(hash, type):
global running_pow_gen
cached_work = parser.get('wallet', 'cached_pow')
if cached_work == '' or type == 'open':
#Generate work for block
pow_source = parser.get('wallet', 'pow_source')
if running_pow_gen == True:
messagebox.showinfo('Generating PoW', 'The wallet is still generating PoW, please wait until it is complete. This should not take long.')
if pow_source == 'external':
data = json.dumps({'action' : 'work_generate', 'hash' : hash})
ws.send(data)
block_work = json.loads(str(ws.recv()))
work = block_work['work']
else:
running_pow_gen = True
pow_work = pow_generate(hash)
work = str(pow_work, 'ascii')
running_pow_gen = False
return work
else:
save_config('cached_pow', '')
return cached_work
def pow_threshold(check):
if check > b'\xFF\xFF\xFF\xC0\x00\x00\x00\x00': return True
else: return False
def pow_generate(hash):
hash_bytes = bytearray.fromhex(hash)
test = False
inc = 0
while test == False:
inc += 1
# generate random array of bytes
random_bytes = bytearray((random.getrandbits(8) for i in range(8)))
for r in range(0,256):
# iterate over the last byte of the random bytes
random_bytes[7] =(random_bytes[7] + r) % 256
h = blake2b(digest_size=8)
h.update(random_bytes)
h.update(hash_bytes)
final = bytearray(h.digest())
final.reverse()
test = pow_threshold(final)
if test:
break
random_bytes.reverse()
return binascii.hexlify(random_bytes)
def get_balance(account):
data = json.dumps({'action' : 'account_balance', 'account' : account})
ws.send(data)
balance_result = json.loads(str(ws.recv()))
#print(balance_result['balance'])
balance = float(balance_result['balance']) / raw_in_xrb
return balance
def get_raw_balance(account):
data = json.dumps({'action' : 'account_balance', 'account' : account})
ws.send(data)
balance_result = json.loads(str(ws.recv()))
#print(balance_result['balance'])
balance = int(balance_result['balance'])
return balance
def get_previous():
#Get account info
accounts_list = [account]
data = json.dumps({'action' : 'accounts_frontiers', 'accounts' : accounts_list})
ws.send(data)
result = ws.recv()
#print(result)
account_info = json.loads(str(result))
previous = account_info['frontiers'][account]
return previous
def get_pending():
#Get pending blocks
data = json.dumps({'action' : 'pending', 'account' : account})
ws.send(data)
pending_blocks = ws.recv()
#print("Received '%s'" % pending_blocks)
rx_data = json.loads(str(pending_blocks))
return rx_data['blocks']
def save_config(variable, value):
cfgfile = open("config.ini",'w')
parser.set('wallet', variable, value)
parser.write(cfgfile)
cfgfile.close()
def send_xrb(dest_address, final_balance):
previous = get_previous()
priv_key, pub_key = seed_account(seed,index)
hex_balance = hex(final_balance)
hex_final_balance = hex_balance[2:].upper().rjust(32, '0')
#print(final_balance)
#print("Starting PoW Generation")
work = get_pow(previous, 'send')
#workbytes = pow_generate(previous)
#work = str(workbytes, 'ascii')
#print("Completed PoW Generation")
#Calculate signature
bh = blake2b(digest_size=32)
bh.update(BitArray(hex=previous).bytes)
bh.update(BitArray(hex=xrb_account(dest_address)).bytes)
bh.update(BitArray(hex=hex_final_balance).bytes)
sig = ed25519.SigningKey(priv_key+pub_key).sign(bh.digest())
signature = str(binascii.hexlify(sig), 'ascii')
finished_block = '{ "type" : "send", "destination" : "%s", "balance" : "%s", "previous" : "%s" , "work" : "%s", "signature" : "%s" }' % (dest_address, hex_final_balance, previous, work, signature)
data = json.dumps({'action' : 'process', 'block' : finished_block})
#print(data)
ws.send(data)
block_reply = ws.recv()
#print(block_reply)
return block_reply
def receive_xrb():
time.sleep(10)
pending = get_pending()
if len(pending) > 0:
data = json.dumps({'action' : 'account_info', 'account' : account})
ws.send(data)
info = ws.recv()
if len(info) == 37:
#print('Not found')
open_xrb()
else:
source = pending[0]
#Get account info
previous = get_previous()
priv_key, pub_key = seed_account(seed,index)
#print("Starting PoW Generation")
work = get_pow(previous, 'receive')
#print("Completed PoW Generation")
#Calculate signature
bh = blake2b(digest_size=32)
bh.update(BitArray(hex=previous).bytes)
bh.update(BitArray(hex=source).bytes)
sig = ed25519.SigningKey(priv_key+pub_key).sign(bh.digest())
signature = str(binascii.hexlify(sig), 'ascii')
finished_block = '{ "type" : "receive", "source" : "%s", "previous" : "%s" , "work" : "%s", "signature" : "%s" }' % (source, previous, work, signature)
data = json.dumps({'action' : 'process', 'block' : finished_block})
#print(data)
ws.send(data)
block_reply = ws.recv()
save_config('balance', str(get_balance(account)))
#print(block_reply)
else:
if parser.get('wallet', 'cached_pow') == '' and parser.get('wallet', 'open') == '1':
previous = get_previous()
work = get_pow(previous, 'cache')
save_config('cached_pow', work)
time.sleep(50)
def open_xrb():
representative = parser.get('wallet', 'representative')
#Get pending blocks
data = json.dumps({'action' : 'pending', 'account' : account})
ws.send(data)
pending_blocks = ws.recv()
#print("Received '%s'" % pending_blocks)
rx_data = json.loads(str(pending_blocks))
#for blocks in rx_data['blocks']:
#print(rx_data['blocks'][0])
source = rx_data['blocks'][0]
priv_key, pub_key = seed_account(seed,index)
public_key = ed25519.SigningKey(priv_key).get_verifying_key().to_ascii(encoding="hex")
#print("Starting PoW Generation")
work = get_pow(str(public_key, 'ascii'), 'open')
#print("Completed PoW Generation")
#Calculate signature
bh = blake2b(digest_size=32)
bh.update(BitArray(hex=source).bytes)
bh.update(BitArray(hex=xrb_account(representative)).bytes)
bh.update(BitArray(hex=xrb_account(account)).bytes)
sig = ed25519.SigningKey(priv_key+pub_key).sign(bh.digest())
signature = str(binascii.hexlify(sig), 'ascii')
finished_block = '{ "type" : "open", "source" : "%s", "representative" : "%s" , "account" : "%s", "work" : "%s", "signature" : "%s" }' % (source, representative, account, work, signature)
data = json.dumps({'action' : 'process', 'block' : finished_block})
#print(data)
ws.send(data)
block_reply = ws.recv()
save_config('open', '1')
#print(block_reply)
def change_xrb():
representative = parser.get('wallet', 'representative')
previous = get_previous()
priv_key, pub_key = seed_account(seed,index)
public_key = ed25519.SigningKey(priv_key).get_verifying_key().to_ascii(encoding="hex")
#print("Starting PoW Generation")
work = get_pow(previous, 'change')
#print("Completed PoW Generation")
#Calculate signature
bh = blake2b(digest_size=32)
bh.update(BitArray(hex=previous).bytes)
bh.update(BitArray(hex=xrb_account(representative)).bytes)
sig = ed25519.SigningKey(priv_key+pub_key).sign(bh.digest())
signature = str(binascii.hexlify(sig), 'ascii')
finished_block = '{ "type" : "change", "previous" : "%s", "representative" : "%s" , "work" : "%s", "signature" : "%s" }' % (previous, representative, work, signature)
data = json.dumps({'action' : 'process', 'block' : finished_block})
#print(data)
ws.send(data)
block_reply = ws.recv()
#print(block_reply)
def item_chosen(choice):
if choice == 'Refresh':
global saved_balance
save_config('balance', str(get_balance(account)))
saved_balance = str(get_balance(account))
balance_text.set(('Balance: {} Mxrb').format(int(float(saved_balance))))
root.update_idletasks()
elif choice == 'Send':
global top
top = Toplevel()
var = IntVar()
top.grab_set()
top.wm_iconbitmap('logo.ico')
top.title('Send')
addr = Label(top, text="Destination Address").grid(row=0)
amount = Label(top, text="Amount in Mxrb").grid(row=1)
e1 = Entry(top,width=80)
e2 = Entry(top,width=80)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
save=Button(top, text="Send", command=lambda: confirm_send(e1.get(), e2.get()),width=5,pady=5).grid(row=2, column=0)
back=Button(top, text="Back", command=lambda: top.destroy(),width=5,pady=5).grid(row=2, column=1)
top.mainloop()
elif choice == 'Configure PoW':
pow_source = parser.get('wallet', 'pow_source')
top = Toplevel()
var = IntVar()
top.grab_set()
top.wm_iconbitmap('logo.ico')
top.title('Configure PoW Source')
rb1 = Radiobutton(top, text = 'Internal PoW', variable = var,value = 1)
rb2 =Radiobutton(top, text = 'External PoW', variable = var,value = 2)
save=Button(top, text="Save", command=lambda: change_pow(var.get()),width=5,pady=5)
back=Button(top, text="Back", command=lambda: top.destroy(),width=5,pady=5)
if pow_source == 'internal':
var.set(1)
elif pow_source == 'external':
var.set(2)
rb1.pack()
rb2.pack()
save.pack()
back.pack()
top.mainloop()
elif choice == 'Configure Rep':
representative = parser.get('wallet', 'representative')
xrb_rep = simpledialog.askstring('Configure Representative', 'Representative:', initialvalue=representative)
if xrb_rep != None:
update_rep(xrb_rep)
elif choice == 'Configure Server':
node_server = parser.get('wallet', 'server')
xrb_server = simpledialog.askstring('Configure Server', 'Server:', initialvalue=node_server)
if xrb_server != None:
update_server(xrb_server)
elif choice == 'Display QR Code':
data = 'xrb:' + account
xrb_qr = pyqrcode.create(data, error='L', version=4, mode=None, encoding='iso-8859-1')
xrb_qr_xbm = xrb_qr.xbm(scale=10)
top = Toplevel()
top.grab_set()
code_bmp = BitmapImage(data=xrb_qr_xbm)
code_bmp.config(background="white")
label = Label(top,image=code_bmp)
label.pack()
back=Button(top, text="Back", command=lambda: top.destroy(),width=5,pady=5)
back.pack()
top.mainloop()
elif choice == 'Account History':
data = json.dumps({ "action": "account_block_count", "account": account })
ws.send(data)
block_count = ws.recv()
rx_data = json.loads(str(block_count))
if 'error' in rx_data:
account_block_count = '0'
history_title = 'Account History (' + account_block_count + ')'
top = Toplevel()
top.title(history_title)
master = tkinter.Frame(top)
master.pack()
tree = ttk.Treeview(master, columns=['Transaction Type','Account','Amount'])
tree.heading('Transaction Type', text='Transaction Type')
tree.heading('Account', text='Account')
tree.heading('Amount', text='Amount')
tree.pack()
else:
account_block_count = rx_data['block_count']
data = json.dumps({'action' : 'account_history', 'account' : account, 'count': int(account_block_count)})
ws.send(data)
history_blocks = ws.recv()
rx_data = json.loads(str(history_blocks))
history_title = 'Account History (' + account_block_count + ')'
top = Toplevel()
top.title(history_title)
master = tkinter.Frame(top)
master.pack()
tree = ttk.Treeview(master, columns=['Transaction Type','Account','Amount'])
tree.heading('Transaction Type', text='Transaction Type')
tree.heading('Account', text='Account')
tree.heading('Amount', text='Amount')
tree.pack()
rx_data['history'].reverse()
tree['show'] = 'headings'
for i in range (len(rx_data['history'])):
tree.insert("",index=0,text=str(len(rx_data['history'])-i),values=[rx_data['history'][i]['type'],rx_data['history'][i]['account'],(float(rx_data['history'][i]['amount'])/10**30)])
def update_rep(xrb_rep):
new_rep = xrb_rep
if len(new_rep) != 64 or new_rep[:4] != "xrb_":
messagebox.showerror('Error', 'That is not a valid RaiBlocks address.')
else:
save_config('representative', new_rep)
#Send change block
change_xrb()
def update_server(xrb_server):
save_config('server', xrb_server)
ws.close()
simpledialog.messagebox.showinfo('Restart', 'The program requires a restart.')
root.destroy()
def restart():
"""Restarts the current program.
Note: this function does not return. Any cleanup action (like
saving data) must be done before calling this function."""
python = sys.executable
os.execl(python, python, * sys.argv)
def change_pow(response):
if response == 1:
save_config('pow_source', 'internal')
pow_source = 'internal'
elif response == 2:
save_config('pow_source', 'external')
pow_source = 'external'
top.destroy()
def confirm_send(final_address, xrb_amount):
#Lets check the details here
#Calculate amount to send
#send_amount is in Mxrb,
send_amount = xrb_amount
send_address = final_address
rai_send = float(send_amount) * 1000000 #float of total send
raw_send = str(int(rai_send)) + '000000000000000000000000'
#Create the new balance
int_balance = int(get_raw_balance(account))
new_balance = int_balance - int(raw_send)
#print(new_balance)
if len(send_address) != 64 or send_address[:4] != "xrb_":
messagebox.showerror('Error', 'Invalid Address')
top.destroy()
elif type(xrb_amount) is int:
if not xrb_amount <= int_balance:
messagebox.showerror('Error', 'Invalid Amount')
top.destroy()
else:
if messagebox.askyesno('Sending', ('Dest: {}\n Amount: {} Mxrb\n New Balance: {} Mxrb\n Are You Sure?').format(send_address,send_amount,new_balance)) == True:
process_send(send_address, int(rai_send))
def process_send(final_address, final_balance):
outcome = send_xrb(str(final_address), final_balance)
if len(outcome) == 4:
messagebox.showinfo('Sent', 'Transaction Successfully Sent')
save_config('balance', str(get_balance(account)))
top.destroy()
else:
messagebox.showerror('Failed', 'Transaction Failed')
top.destroy()
class StringDialog(simpledialog._QueryString):
def body(self, master):
super().body(master)
self.iconbitmap('logo.ico')
def ask_string(title, prompt, **kargs):
d = StringDialog(title, prompt, **kargs)
return d.result
def read_encrypted(password, filename, string=True):
with open(filename, 'rb') as input:
ciphertext = input.read()
plaintext = decrypt(password, ciphertext)
if string:
return plaintext.decode('utf8')
else:
return plaintext
def write_encrypted(password, filename, plaintext):
with open(filename, 'wb') as output:
ciphertext = encrypt(password, plaintext)
output.write(ciphertext)
parser = SafeConfigParser()
config_files = parser.read('config.ini')
while True:
password = ask_string("Password", "Enter password:", show='*')
password_confirm = ask_string("Password", "Confirm password:", show='*')
if password == None or (password == '' and password_confirm == ''):
sys.exit()
if password == password_confirm:
break
messagebox.showerror('Error', 'Password Mismatch')
if len(config_files) == 0:
full_wallet_seed = hex(random.SystemRandom().getrandbits(256))
wallet_seed = full_wallet_seed[2:].upper()
write_encrypted(password, 'seed.txt', wallet_seed)
cfgfile = open("config.ini",'w')
parser.add_section('wallet')
priv_key, pub_key = seed_account(str(wallet_seed), 0)
public_key = str(binascii.hexlify(pub_key), 'ascii')
account = account_xrb(str(public_key))
with open('data.txt', 'w') as f:
f.write(('Wallet Seed: {}\nPublic Key: {}\nAccount Address: {}\n').format(wallet_seed, public_key, account))
f.write('\nStore the data in a safe place (for example on paper) and DELETE THIS FILE!')
f.close()
messagebox.showinfo('Info','Seed and Address written to "data.txt", ensure that you store your data in a safe place and delete this file.')
parser.set('wallet', 'account', account)
parser.set('wallet', 'index', '0')
parser.set('wallet', 'representative', default_representative)
parser.set('wallet', 'pow_source', 'external')
parser.set('wallet', 'server', 'wss://yapraiwallet.space')
parser.set('wallet', 'cached_pow', '')
parser.set('wallet', 'balance', '0')
parser.set('wallet', 'open', '0')
parser.write(cfgfile)
cfgfile.close()
index = 0
seed = wallet_seed
else:
try:
seed = read_encrypted(password, 'seed.txt', string=True)
except:
messagebox.showerror('Error', 'Error decoding seed, check password and try again')
sys.exit()
account = parser.get('wallet', 'account')
index = int(parser.get('wallet', 'index'))
representative = parser.get('wallet', 'representative')
pow_source = parser.get('wallet', 'pow_source')
node_server = parser.get('wallet', 'server')
cached_work = parser.get('wallet', 'cached_pow')
saved_balance =float(parser.get('wallet', 'balance'))
account_open = parser.get('wallet', 'open')
try:
ws = create_connection(node_server)
except Exception as e:
print (e)
messagebox.showerror('Error', ' Failed to connect to backend server\nTry again later or change the server in config.ini')
sys.exit()
thread = threading.Thread(target=receive_xrb)
thread.start()
root.deiconify()
balance_text = StringVar()
balance_text.set(('Balance: {} Mxrb').format(int(float(saved_balance))))
l_title = Label(root, text="RetroXRBWallet")
l_address = Text(root,height=1, width=65)
l_address.insert(1.0, account)
l_address.bind('<Double-Button-1>',address_to_clipboard)
l_balance = Label(root, textvariable=balance_text)
l_title.pack()
l_address.pack()
l_balance.pack()
b_send=Button(root, text="Send", command=lambda:item_chosen('Send'),width=25,pady=7)
b_history=Button(root, text="Account History", command=lambda:item_chosen('Account History'),width=25,pady=7)
b_qr=Button(root, text="Display QR Code", command=lambda:item_chosen('Display QR Code'),width=25,pady=7)
b_pow=Button(root, text="Configure PoW", command=lambda:item_chosen('Configure PoW'),width=25,pady=7)
b_rep=Button(root, text="Configure Rep", command=lambda:item_chosen('Configure Rep'),width=25,pady=7)
b_server=Button(root, text="Configure Server", command=lambda:item_chosen('Configure Server'),width=25,pady=7)
b_refresh=Button(root, text="Refresh", command=lambda:item_chosen('Refresh'),width=25,pady=7)
b_quit=Button(root, text="Quit", command=root_destroy,width=25,pady=7)
for c in sorted(root.children):
root.children[c].pack()
l_address.configure(state="disabled",exportselection=1)
root.mainloop()