-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathecchat.py
More file actions
1521 lines (857 loc) · 41.2 KB
/
ecchat.py
File metadata and controls
1521 lines (857 loc) · 41.2 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
#!/usr/bin/env python3
# coding: UTF-8
import datetime
import argparse
import pyqrcode
import pathlib
import logging
import signal
import codecs
import urwid
import time
import zmq
import sys
import re
from uuid import uuid4
# ZMQ event loop adapter for urwid
from zmqeventloop import zmqEventLoop
#from slickrpc import Proxy
from slickrpc import exc # RpcWalletUnlockNeeded only TO BE REMOVED !!!!! # TIDY
# Configuration file management : eccoin.conf & ecchat.conf
from configure import loadConfigurationECC, loadConfigurationAlt
# eccPacket, cryptoNode & transaction classes
from eccpacket import eccPacket
from cryptonode import cryptoNode, eccoinNode, bitcoinNode, moneroNode, cryptoNodeException
from transactions import txChat, txSend, txReceive
# urwid extension classes
from urwidext import GridFlowPlus, YesNoDialog, PassphraseDialog, MessageListBox, FrameFocus, MessageWalker
################################################################################
## ChatApp class ###############################################################
################################################################################
class ChatApp:
_version = '1.5'
_clock_fmt = '[%H:%M:%S] '
_palette = [('header', 'black' , 'brown' , 'standout'),
('status', 'black' , 'brown' , 'standout'),
('text' , 'light gray' , 'black' , 'default' ),
('tnak' , 'dark gray' , 'black' , 'default' ),
('tack' , 'light gray' , 'black' , 'default' ),
('time' , 'brown' , 'black' , 'default' ),
('self' , 'light cyan' , 'black' , 'default' ),
('other' , 'light green' , 'black' , 'default' ),
('ecchat', 'brown' , 'black' , 'default' ),
('scroll', 'text' ),
('footer', 'text' ),
('btn_nm', 'black' , 'brown' , 'default' ),
('btn_hl', 'black' , 'yellow' , 'standout')]
############################################################################
def __init__(self, name, conf, debug=False):
urwid.set_encoding('utf-8')
self.party_name = ['ecchat', name, '']
self.party_separator = ['|', '>', '<']
self.party_name_style = ['ecchat', 'self', 'other']
self.party_text_style = ['ecchat', 'text', 'text']
self.conf = conf
self.debug = debug
self.exitMsg = ''
self.swap_pending = False
self.swap_uuid = ''
self.swap_timeout_h = 0
self.swap_amountGive = 0.0
self.swap_amountTake = 0.0
self.swap_indexGive = 0
self.swap_indexTake = 0
self.txid = ''
self.subscribers = []
self.coins = []
self.txChat = None
self.txSend = {}
self.txReceive = {}
self.txSwap = {}
############################################################################
def check_symbol(self, symbol):
return_valid = False
return_index = 0
for index, coin in enumerate(self.coins):
if symbol.lower() == coin.symbol:
return_valid = True
return_index = index
return return_valid, return_index
############################################################################
def build_ui(self):
self.walker = MessageWalker ()
self.headerT = urwid.Text ('')
self.headerA = urwid.AttrMap (self.headerT, 'header')
self.scrollT = MessageListBox(self.walker)
self.scrollA = urwid.AttrMap (self.scrollT, 'scroll')
self.statusT = urwid.Text ('')
self.statusA = urwid.AttrMap (self.statusT, 'status')
self.footerT = urwid.Edit ('> ')
self.footerA = urwid.AttrMap (self.footerT, 'footer')
self.frame = urwid.Frame (body = self.scrollA, header = self.headerA, footer = self.statusA)
self.window = FrameFocus (body = self.frame, footer = self.footerA, focus_part = 'footer')
# Set initial text
self.set_party_name(2, '')
self.set_status_text(u'Initializing ...')
self.party_size = max(len(t) for t in self.party_name)
############################################################################
def set_party_name(self, party, name):
self.party_name[party] = name
self.party_size = max(len(t) for t in self.party_name)
self.set_header_text(self.party_name[1], self.party_name[2])
############################################################################
def set_header_text(self, local_name, remote_name):
if remote_name:
self.headerT.set_text(u'ecchat {} : {} > {}'.format(self._version, local_name, remote_name))
else:
self.set_header_text(local_name, '(no chat active)')
############################################################################
def set_status_text(self, text):
self.statusT.set_text(text)
############################################################################
def send_ecchat_packet(self, meth, data):
if self.txChat:
ecc_packet = eccPacket(eccPacket._protocol_id_ecchat, 0,
self.txChat.tag,
self.coins[0].routingTag,
meth,
data)
if self.debug:
logging.info('TX({}): {}'.format(eccPacket._protocol_id_ecchat, ecc_packet.to_json()))
ecc_packet.send(self.coins[0])
############################################################################
def send_ecresolve_packet(self, meth, data):
for tag in self.coins[0].ecresolve_tags:
ecc_packet = eccPacket(eccPacket._protocol_id_ecresolve,
self.coins[0].respondId, tag,
self.coins[0].routingTag,
meth,
data)
if self.debug:
logging.info('TX({}): {}'.format(eccPacket._protocol_id_ecresolve, ecc_packet.to_json()))
ecc_packet.send(self.coins[0])
############################################################################
def append_message(self, party, text, uuid = '', ack = True):
tstyle = {True : self.party_text_style[party], False : 'tnak'} [ack]
markup = [('time', datetime.datetime.now().strftime(self._clock_fmt)), (self.party_name_style[party], u'{0:>{1}s} {2} '.format(self.party_name[party], self.party_size, self.party_separator[party])), (tstyle, text)]
self.walker.append(party, markup, uuid)
self.scrollT.set_focus(len(self.scrollT.body) - 1)
############################################################################
def replace_message(self, party, text, uuid = '', ack = True):
tstyle = {True : self.party_text_style[party], False : 'tnak'} [ack]
markup = [('time', datetime.datetime.now().strftime(self._clock_fmt)), (self.party_name_style[party], u'{0:>{1}s} {2} '.format(self.party_name[party], self.party_size, self.party_separator[party])), (tstyle, text)]
self.walker.replace(party, markup, uuid)
self.scrollT.set_focus(len(self.scrollT.body) - 1)
############################################################################
def delete_message(self, party, text, uuid = '', ack = True):
del_text = '\u2588' * len(text)
tstyle = {True : self.party_text_style[party], False : 'tnak'} [ack]
markup = [('time', datetime.datetime.now().strftime(self._clock_fmt)), (self.party_name_style[party], u'{0:>{1}s} {2} '.format(self.party_name[party], self.party_size, self.party_separator[party])), (tstyle, del_text)]
self.walker.replace(party, markup, uuid)
self.scrollT.set_focus(len(self.scrollT.body) - 1)
############################################################################
def ack_message(self, uuid):
self.walker.set_markup_style(uuid, 2, 'tack')
############################################################################
def clock_refresh(self, loop = None, data = None):
text = datetime.datetime.now().strftime(self._clock_fmt)
for coin in self.coins:
text += ' {} # {:d}/{:d} '.format(coin.symbol, coin.blocks, coin.peers)
self.set_status_text(text)
loop.set_alarm_in(1, self.clock_refresh)
############################################################################
def reset_buffer_timeouts(self, loop = None, data = None):
try:
if self.coins[0].reset_buffer_timeouts():
loop.set_alarm_in(10, self.reset_buffer_timeouts)
except cryptoNodeException as error:
self.exitMsg = str(error)
raise urwid.ExitMainLoop()
############################################################################
def block_refresh_timed(self, loop, data = None):
for coin in self.coins:
if not coin.zmqAddress:
coin.refresh()
loop.set_alarm_in(10, self.block_refresh_timed)
############################################################################
def advertise_chat_name(self, loop = None, data = None):
uuid = str(uuid4())
data = {'uuid' : str(uuid4()),
'name' : self.party_name[1],
'type' : 'chatname'}
self.send_ecresolve_packet(eccPacket.METH_nameAdv, data)
loop.set_alarm_in(60, self.advertise_chat_name)
############################################################################
def block_refresh(self, index):
if not self.coins[index].no_refresh:
self.coins[index].refresh()
self.coins[index].no_refresh = True
self.loop.set_alarm_in(1, self.unblock_block_refresh, index)
############################################################################
def unblock_block_refresh(self, loop, index):
self.coins[index].no_refresh = False
############################################################################
def show_passphrase_dialog(self, symbol, retry_no, retry_max, callback):
dialog = PassphraseDialog(text = u'Enter {} wallet unlock passphrase ({:d}/{:d}):'.format(symbol, retry_no, retry_max), loop = self.loop)
urwid.connect_signal(dialog, 'commit', callback)
dialog.show()
############################################################################
def start_swap(self, amountGive, indexGive, amountTake, indexTake):
# Check 1 - Is a swap currently pending ?
if self.swap_pending:
self.loop.remove_alarm(self.swap_timeout_h)
self.swap_pending = False
self.swap_uuid = ''
self.swap_timeout_h = 0
self.swap_amountGive = 0.0
self.swap_amountTake = 0.0
self.swap_indexGive = 0
self.swap_indexTake = 0
# Check 2 - Can the swap amount be converted to a float correctly ?
try:
float_amountGive = float(amountGive)
float_amountTake = float(amountTake)
except ValueError:
self.append_message(0, 'Invalid swap amount - number expected')
return
# Check 3 - Is the swap amount in a sensible range ?
if (float_amountGive <= 0) or (float_amountTake <= 0):
self.append_message(0, 'Invalid swap amount - must be greater than zero')
return
# Check 4 - Does the user's wallet hold an adequate balance ?
balance = self.coins[indexGive].get_unlocked_balance()
if float_amountGive >= balance:
self.append_message(0, 'Invalid swap amount - must be less than current balance = {:f}'.format(balance))
return
# Check 5 - Ensure the user's wallet is unlocked
# TODO
# Send swap information
data = {'uuid' : str(uuid4()),
'cogv' : self.coins[indexGive].symbol,
'amgv' : float_amountGive,
'cotk' : self.coins[indexTake].symbol,
'amtk' : float_amountTake}
self.send_ecchat_packet(eccPacket.METH_swapInf, data)
handle = self.loop.set_alarm_in(60, self.timeout_swap)
self.swap_pending = True
self.swap_uuid = data['uuid']
self.swap_timeout_h = handle
self.swap_amountGive = float_amountGive
self.swap_amountTake = float_amountTake
self.swap_indexGive = indexGive
self.swap_indexTake = indexTake
############################################################################
def swap_proposed(self, symbolGive, amountGive, symbolTake, amountTake):
# Notify user of swap proposal
self.append_message(0, 'Swap proposed : {} {} for {} {}'.format(amountGive, symbolGive, amountTake, symbolTake))
# Check 1 - Is a swap currently incomplete ?
if self.swap_pending:
self.swap_pending = False
self.swap_uuid = ''
self.swap_timeout_h = 0
self.swap_amountGive = 0.0
self.swap_amountTake = 0.0
self.swap_indexGive = 0
self.swap_indexTake = 0
# Check 2 - Are both the coins in the proposed swap available
validGive, indexGive = self.check_symbol(symbolGive)
validTake, indexTake = self.check_symbol(symbolTake)
if not validGive:
self.append_message(0, 'Unknown coin symbol: {}'.format(match.group('symbolGive')))
return
if not validTake:
self.append_message(0, 'Unknown coin symbol: {}'.format(match.group('symbolTake')))
return
# Check 3 - Can the swap amount be converted to a float correctly ?
try:
float_amountGive = float(amountGive)
float_amountTake = float(amountTake)
except ValueError:
self.append_message(0, 'Invalid swap amount - number expected')
return
# Check 4 - Is the swap amount in a sensible range ?
if (float_amountGive <= 0) or (float_amountTake <= 0):
self.append_message(0, 'Invalid swap amount - must be greater than zero')
return
# Check 5 - Does the user's wallet hold an adequate balance ?
balance = self.coins[indexTake].get_unlocked_balance()
if float_amountTake >= balance:
self.append_message(0, 'Invalid swap amount - must be less than current balance = {:f}'.format(balance))
return
self.swap_pending = True
self.swap_uuid = ''
self.swap_timeout_h = 0
self.swap_amountGive = float_amountGive
self.swap_amountTake = float_amountTake
self.swap_indexGive = indexGive
self.swap_indexTake = indexTake
############################################################################
def swap_execute(self):
# Check 1 - Ensure the user's wallet is unlocked
# TODO
if not self.swap_pending:
self.append_message(0, 'No swap available to execute')
return
address = self.coins[self.swap_indexGive].get_new_address()
data = {'uuid' : self.swap_uuid,
'cogv' : self.coins[self.swap_indexGive].symbol,
'adgv' : address}
self.send_ecchat_packet(eccPacket.METH_swapReq, data)
self.loop.set_alarm_in(10, self.timeout_execute)
############################################################################
def swap_request(self, symbolGive, addressGive):
if self.swap_pending:
assert symbolGive == self.coins[self.swap_indexGive].symbol
self.swap_addressGive = addressGive
address = self.coins[self.swap_indexTake].get_new_address()
data = {'uuid' : self.swap_uuid,
'cotk' : self.coins[self.swap_indexTake].symbol,
'adtk' : address}
self.send_ecchat_packet(eccPacket.METH_swapRes, data)
else:
data = {'uuid' : '',
'cotk' : '',
'adtk' : '0'}
self.send_ecchat_packet(eccPacket.METH_swapRes, data)
############################################################################
def swap_response(self, symbolTake, addressTake):
if addressTake == '0':
self.append_message(0, 'Other party is unable or unwilling to receive swaped {}'.format(symbolTake))
#TODO : Test this !!!
if self.swap_pending and addressTake != '0':
assert symbolTake == self.coins[self.swap_indexTake].symbol
try:
self.txid = self.coins[self.swap_indexTake].send_to_address(addressTake, str(self.swap_amountTake), "ecchat")
except exc.RpcWalletUnlockNeeded: # TODO RpcWalletInsufficientFunds
self.append_message(0, 'Wallet locked - please unlock')
else:
self.append_message(0, '{:f} {} sent to {}'.format(self.swap_amountTake, symbolTake, addressTake))
# Send the METH_txidInf message - (coin, amount, address, txid)
data = {'coin' : self.coins[self.swap_indexTake].symbol,
'amnt' : '{:f}'.format(self.swap_amountTake),
'addr' : addressTake,
'txid' : self.txid}
self.send_ecchat_packet(eccPacket.METH_txidInf, data)
# /execute command complete - reset state variables
self.swap_pending = False
self.swap_uuid = ''
self.swap_timeout_h = 0
self.swap_amountGive = 0.0
self.swap_amountTake = 0.0
self.swap_indexGive = 0
self.swap_indexTake = 0
############################################################################
def complete_swap(self):
if self.swap_pending:
try:
self.txid = self.coins[self.swap_indexGive].send_to_address(self.swap_addressGive, str(self.swap_amountGive), "ecchat")
except exc.RpcWalletUnlockNeeded: # TODO RpcWalletInsufficientFunds
self.append_message(0, 'Wallet locked - please unlock')
else:
self.append_message(0, '{:f} {} sent to {}'.format(self.swap_amountGive, self.coins[self.swap_indexGive].symbol, self.swap_addressGive))
# Send the METH_txidInf message - (coin, amount, address, txid)
data = {'coin' : self.coins[self.swap_indexGive].symbol,
'amnt' : '{:f}'.format(self.swap_amountGive),
'addr' : self.swap_addressGive,
'txid' : self.txid}
self.send_ecchat_packet(eccPacket.METH_txidInf, data)
# /swap command complete - reset state variables
self.swap_pending = False
self.swap_uuid = ''
self.swap_timeout_h = 0
self.swap_amountGive = 0.0
self.swap_amountTake = 0.0
self.swap_indexGive = 0
self.swap_indexTake = 0
############################################################################
def timeout_swap(self, loop = None, data = None):
if self.swap_pending:
self.append_message(0, 'No /execute from other party - swap cancelled')
# /swap command cancelled - reset state variables
self.swap_pending = False
self.swap_uuid = ''
self.swap_timeout_h = 0
self.swap_amountGive = 0.0
self.swap_amountTake = 0.0
self.swap_indexGive = 0
self.swap_indexTake = 0
############################################################################
def timeout_execute(self, loop = None, data = None):
if self.swap_pending:
self.append_message(0, 'No response from other party - swap cancelled')
# /execute command cancelled - reset state variables
self.swap_pending = False
self.swap_uuid = ''
self.swap_timeout_h = 0
self.swap_amountGive = 0.0
self.swap_amountTake = 0.0
self.swap_indexGive = 0
self.swap_indexTake = 0
############################################################################
def echo_ecchat_startup(self):
self.append_message(0, " _ _ ")
self.append_message(0, "Welcome to: | | | | ")
self.append_message(0, " ___ ___ ___| |__ __ _| |_ ")
self.append_message(0, " / _ \/ __/ __| '_ \ / _` | __|")
self.append_message(0, " | __/ (_| (__| | | | (_| | |_ ")
self.append_message(0, " \___|\___\___|_| |_|\__,_|\__|")
self.append_message(0, " ")
self.append_message(0, "For help: /help for commands ")
self.append_message(0, " /keys for special keys")
############################################################################
def echo_help(self):
self.append_message(0, '%-8s - %s' % ('/help ', 'display help - commands'))
self.append_message(0, '%-8s - %s' % ('/keys ', 'display help - keys'))
self.append_message(0, '%-8s - %s' % ('/exit ', 'exit - also /quit and ESC'))
self.append_message(0, '%-8s - %s' % ('/version ', 'display ecchat version info'))
self.append_message(0, '%-8s - %s' % ('/chat <name>', 'start a chat by name or routing tag'))
self.append_message(0, '%-8s - %s' % ('/chat ', 'end current chat'))
self.append_message(0, '%-8s - %s' % ('/blocks <coin>', 'display block count'))
self.append_message(0, '%-8s - %s' % ('/peers <coin>', 'display peer count'))
self.append_message(0, '%-8s - %s' % ('/tag ', 'display routing tag public key'))
self.append_message(0, '%-8s - %s' % ('/qr ', 'display routing tag as QR code'))
self.append_message(0, '%-8s - %s' % ('/balance <coin>', 'display wallet balance'))
self.append_message(0, '%-8s - %s' % ('/address <coin>', 'generate a new address'))
self.append_message(0, '%-8s - %s' % ('/send x <coin>', 'send x to other party'))
self.append_message(0, '%-8s - %s' % ('/txid ', 'display txid of last transaction'))
self.append_message(0, '%-8s - %s' % ('/list <coin>', 'list all transactions this session'))
self.append_message(0, '%-8s - %s' % (' <coin>', 'optional coin symbol - defaults to ecc'))
# self.append_message(0, '%-8s - %s' % ('/swap x <coin-1> for y <coin-2>', 'proposes a swap'))
# self.append_message(0, '%-8s - %s' % ('/execute ', 'executes the proposed swap'))
############################################################################
def echo_keys(self):
self.append_message(0, '------------------------------------')
self.append_message(0, 'Recall, replace, erase, scroll, exit')
self.append_message(0, '------------------------------------')
self.append_message(0, 'CURSOR UP/DOWN - Recall previous message / command')
self.append_message(0, 'ENTER - Send as new message / command')
self.append_message(0, 'ALT+ENTER/LEFT/RIGHT - Replace previous message')
self.append_message(0, 'ALT+DELETE - Erase previous message')
self.append_message(0, 'ALT+CURSOR UP/DOWN - Scroll messages one line')
self.append_message(0, 'PAGE UP/DOWN - Scroll messages one page')
self.append_message(0, 'ESCAPE - Exit ecchat')
############################################################################
def echo_balance(self, coin):
try:
balance_con = coin.get_balance()
balance_unl = coin.get_unlocked_balance()
balance_unc = coin.get_unconfirmed_balance()
except cryptoNodeException as error:
self.append_message(0, str(error))
else:
if balance_con != balance_unl:
if balance_unc > 0:
self.append_message(0, '{} : {:f} confirmed ({:f} unlocked) + {:f} unconfirmed'.format(coin.symbol, balance_con, balance_unl, balance_unc))
else:
self.append_message(0, '{} : {:f} ({:f} unlocked)'.format(coin.symbol, balance_con, balance_unl))
else:
if balance_unc > 0:
self.append_message(0, '{} : {:f} confirmed + {:f} unconfirmed'.format(coin.symbol, balance_con, balance_unc))
else:
self.append_message(0, '{} : {:f}'.format(coin.symbol, balance_con))
############################################################################
def echo_qrcode(self, text):
qrdecode = [[' ', '\u2584'], ['\u2580', '\u2588']]
lines = text.splitlines()
lines_top = lines[::2]
lines_bot = lines[1::2]
if len(lines_bot) < len(lines_top):
lines_bot.append(lines_bot[0])
for i in range(0, len(lines_top)):
qrline = ''
for j in range(0, len(lines_top[i])):
qrline += qrdecode[int(lines_top[i][j])][int(lines_bot[i][j])]
self.append_message(0, qrline)
############################################################################
def echo_transactions(self, symbol):
for tx in self.txSend.values():
if tx.coin.symbol == symbol:
self.append_message(0, 'TX: {} {} {:f} {} {}'.format(tx.time_tx.strftime('%x %X'), tx.coin.symbol, tx.f_amount, tx.addr, tx.txid))
for tx in self.txReceive.values():
if tx.coin.symbol == symbol:
self.append_message(0, 'RX: {} {} {:f} {} {}'.format(tx.time_tx.strftime('%x %X'), tx.coin.symbol, tx.f_amount, tx.addr, tx.txid))
############################################################################
def process_user_entry(self, text):
if len(text) > 0:
uuid = str(uuid4())
self.footerT.set_edit_text(u'')
self.append_message(1, text, uuid, text.startswith('/'))
if text.startswith('/exit'):
self.check_quit('exit')
elif text.startswith('/quit'):
self.check_quit('quit')
elif text.startswith('/help'):
self.echo_help()
elif text.startswith('/keys'):
self.echo_keys()
elif text.startswith('/chat'):
match = re.match('/chat (?P<name>\S+)', text)
if match:
if self.txChat:
#TODO123 - Improve this aspect
self.append_message(0, 'Please end your existing chat first using /chat with no name')
else:
uuid = str(uuid4())
self.txChat = txChat(self, uuid, match.group('name'))
self.txChat.resolve_chat()
else:
if self.txChat:
self.txChat.stop_chat()
self.txChat = None
else:
self.append_message(0, 'To start a new chat, specify chat name following /chat command')
elif text.startswith('/version'):
self.append_message(0, self._version)
elif text.startswith('/blocks'):
match = re.match('/blocks (?P<symbol>\w+)', text)
if match:
valid, index = self.check_symbol(match.group('symbol'))
if valid:
self.append_message(0, '{:d}'.format(self.coins[index].blocks))
else:
self.append_message(0, 'Unknown coin symbol: {}'.format(match.group('symbol')))
else:
for coin in self.coins:
self.append_message(0, '{} : {:d}'.format(coin.symbol, coin.blocks))
elif text.startswith('/peers'):
match = re.match('/peers (?P<symbol>\w+)', text)
if match:
valid, index = self.check_symbol(match.group('symbol'))
if valid:
self.append_message(0, '{:d}'.format(self.coins[index].peers))
else:
self.append_message(0, 'Unknown coin symbol: {}'.format(match.group('symbol')))
else:
for coin in self.coins:
self.append_message(0, '{} : {:d}'.format(coin.symbol, coin.peers))
elif text.startswith('/tag'):
self.append_message(0, '{}'.format(self.coins[0].routingTag))
elif text.startswith('/qr'):
self.echo_qrcode(pyqrcode.create(self.coins[0].routingTag).text(quiet_zone=2))
elif text.startswith('/balance'):
match = re.match('/balance (?P<symbol>\w+)', text)
if match:
valid, index = self.check_symbol(match.group('symbol'))
if valid:
self.echo_balance(self.coins[index])
else:
self.append_message(0, 'Unknown coin symbol: {}'.format(match.group('symbol')))
else:
for coin in self.coins:
self.echo_balance(coin)
elif text.startswith('/address'):
match = re.match('/address (?P<symbol>\w+)', text)
if match:
valid, index = self.check_symbol(match.group('symbol'))
if valid:
address = self.coins[index].get_new_address()
self.append_message(0, '{}'.format(address))
else:
self.append_message(0, 'Unknown coin symbol: {}'.format(match.group('symbol')))
else:
address = self.coins[0].get_new_address()
self.append_message(0, '{}'.format(address))
elif text.startswith('/send'):
match_default = re.match('/send (?P<amount>([0-9]*\.)?[0-9]+)' , text)
match_symbol = re.match('/send (?P<amount>([0-9]*\.)?[0-9]+) (?P<symbol>\w+)', text)
if match_symbol:
valid, index = self.check_symbol(match_symbol.group('symbol'))
if valid:
uuid = str(uuid4())
self.txSend[uuid] = txSend(self, uuid, self.coins[index], match_symbol.group('amount'))
self.txSend[uuid].do_checks()
else:
self.append_message(0, 'Unknown coin symbol: {}'.format(match_symbol.group('symbol')))
elif match_default:
uuid = str(uuid4())
self.txSend[uuid] = txSend(self, uuid, self.coins[0], match_default.group('amount'))
self.txSend[uuid].do_checks()
else:
self.append_message(0, 'Unknown command syntax - try /help for a list of commands')
# elif text.startswith('/swap'):
# match = re.match('/swap (?P<amountGive>([0-9]*\.)?[0-9]+) (?P<symbolGive>\w+) for (?P<amountTake>([0-9]*\.)?[0-9]+) (?P<symbolTake>\w+)', text)
# if match:
# validGive, indexGive = self.check_symbol(match.group('symbolGive'))
# validTake, indexTake = self.check_symbol(match.group('symbolTake'))
# if validGive and validTake:
# self.start_swap(match.group('amountGive'), indexGive,
# match.group('amountTake'), indexTake)
# else:
# if not validGive:
# self.append_message(0, 'Unknown coin symbol: {}'.format(match.group('symbolGive')))
# if not validTake: