-
Notifications
You must be signed in to change notification settings - Fork 0
/
piBlockSSHControlServer.py
1128 lines (847 loc) · 44.6 KB
/
piBlockSSHControlServer.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
#!/usr/local/bin/python3
# coding=utf-8
import sys
import os
import cmd
import time
import readline
import socket
import logging
import urllib3.request
import json
import threading
import logging
import bz2
import hashlib
from kivy.support import install_twisted_reactor
install_twisted_reactor()
from twisted.internet import protocol, reactor
from twisted.conch import avatar, recvline
from twisted.conch.interfaces import IConchUser, ISession
from twisted.conch.ssh import factory, keys, session
from twisted.conch.insults import insults
from twisted.cred import portal, checkers, error
from twisted.cred.checkers import ICredentialsChecker
from twisted.cred.credentials import IUsernameHashedPassword
from twisted.internet.defer import Deferred
from zope.interface import implements
from piBlockEngine import PiBlockEngine
class PiBlockSSHProtocol(recvline.HistoricRecvLine):
portal = None
avatar = None
logout = None
ruler = '='
doc_leader = ""
doc_header = "Documented commands (type help <topic>):"
misc_header = "Miscellaneous help topics:"
undoc_header = "Undocumented commands:"
nohelp = "*** No help on %s"
#-------------------------------------------------------------
#Command: Boilerplate
#-------------------------------------------------------------
def __init__(self, user, app):
self.user = user
self.app = app
self.logger = self.getPiBlockControlServerLogger()
def connectionMade(self):
recvline.HistoricRecvLine.connectionMade(self)
self.outputWelcomeBannerText()
self.do_help()
self.showPrompt()
def showPrompt(self):
print ("User: {}".format(self.user.username))
print ("Status: {}".format(self.app.status))
self.terminal.write("{}@PiBlock::{}> ".format(self.user.username, self.app.status))
def getCommandFunc(self, cmd):
return getattr(self, 'do_' + cmd, None)
def lineReceived(self, line):
self.logger.debug("DEBUG OUTPUT - Line Received: {}".format(line))
# if not self.avatar:
line = line.strip()
if line:
cmdAndArgs = line.split()
cmd = cmdAndArgs[0]
args = cmdAndArgs[1:]
if cmd == '?':
cmd = 'help'
elif cmd == 'cls':
cmd = 'clear'
elif cmd == 'q':
cmd = 'close'
elif cmd == 'cfg':
cmd = 'currentConfig'
elif cmd == 'curr':
cmd = 'supportedCurrencies'
elif cmd == 'stat':
cmd = 'sysStatus'
elif cmd == 'startX':
cmd = 'startTendering'
elif cmd == 'stopX':
cmd = 'stopTendering'
func = self.getCommandFunc(cmd)
if func:
try:
func(*args)
except Exception, e:
self.terminal.nextLine()
self.terminal.write("Error: %s" % e)
self.terminal.nextLine()
else:
self.terminal.nextLine()
self.terminal.write("No such command {}".format(cmd))
self.terminal.nextLine()
self.terminal.nextLine()
self.showPrompt()
#-------------------------------------------------------------
#Commands: User - Reset Password
#-------------------------------------------------------------
def do_resetPassword(self, *args):
#DOCUMENTATION BLOCK
"""\nResets a User's Password.\n=========================\n
No Arguments expected but an optional argument or list of arguments can be specified to query values of particular settings.
If no Arguments supplied, piBlock will output all the current configuration setting values.\n
Conditions: User == 'admin' & Status == 'Initialised'
Usage Syntax: 'currentConfig [<key(1) <key(2)> ... <key(n)>]'\n
Example:
piBlock> currentConfig\n
Example to Query Config Value for 'email':
piBlock> currentConfig email\n
Example to Query Multiple Config Values:
piBlock> currentConfig email defaultCurrency timeout\n"""
self.terminal.nextLine()
self.terminal.write(self.stillToBeImplemented('currentConfig'))
self.terminal.nextLine()
#-------------------------------------------------------------
#Commands: Config - Current Configuration
#-------------------------------------------------------------
def do_currentConfig(self, *args):
#DOCUMENTATION BLOCK
"""\nDisplays PiBlock's Current Configuration Settings.\n==================================================\n
No Arguments expected but an optional argument or list of arguments can be specified to query values of particular settings.
If no Arguments supplied, piBlock will output all the current configuration setting values.\n
Conditions: None\n
Shortcut: 'cfg'
Usage Syntax: 'currentConfig [<key(1) <key(2)> ... <key(n)>]'\n
Example:
piBlock> currentConfig\n
Example to Query Config Value for 'email':
piBlock> currentConfig email\n
Example to Query Multiple Config Values:
piBlock> currentConfig email defaultCurrency timeout\n"""
self.logger.debug("Started...")
self.outputTitleText("PiBlock's Current Configuration Settings")
if len(args) == 0:
self.logger.debug("Displaying All Current Config Values")
self.terminal.write(self.app.piBlockEngine.getVerboseConfigData())
self.terminal.nextLine()
else:
for configKey in args:
if not self.app.piBlockEngine.doesConfigKeyExist(configKey):
self.logger.debug("No Key {} exists...".format(configKey))
self.terminal.write("Config Setting for '{}' does not exist or have a value set.".format(configKey))
self.terminal.nextLine()
else:
self.logger.debug("Key {} exists...".format(configKey))
configValue = self.app.piBlockEngine.getConfigValueForKey(configKey)
self.terminal.write("Config Setting '{}' has value '{}'".format(configKey, configValue))
self.terminal.nextLine()
self.terminal.nextLine()
self.logger.debug("Finished!")
#-------------------------------------------------------------
#Commands: Config - Add a Configuration
#-------------------------------------------------------------
def do_addConfig(self, *args):
# DOCUMENTATION BLOCK
"""\nAdds (and saves) a Config Setting.\n==================================\n
Expects 2 Arguments, seperated by a ' '. A <key> for the setting name and <value> for the setting value. Note: <key> must not exist in configuration.\n
Conditions: <key> must Not Exist, User = 'admin' & Status = 'Initialised'\n
Usage Syntax: 'addConfig <key> <value>'\n
Example:
piBlock> addConfig email someone@somewhere.com\n"""
self.logger.debug("Started...")
if not self.isAdminUser() or not self.isAppStatusInitialised():
self.terminal.write("[Permission Denied] - Only Admin user can add a config setting or PiBlock can only add a config setting when it is in the 'Initialised' state.")
self.terminal.nextLine()
self.terminal.write("To add a config setting, make sure you are logged in as 'admin' and PiBlock is in the 'Initialised' state.")
self.terminal.nextLine()
self.terminal.nextLine()
else:
if len(args) != 2:
self.terminal.write("[Error] - Invalid number of arguments supplied.")
self.terminal.nextLine()
self.terminal.write("""Expects 2 Arguments, seperated by a ' '. A <key> for the setting name and <value> for the setting value. Note: <key> must not exist in configuration.\n
Conditions: <key> must Not Exist, User = 'admin' & Status = 'Initialised'\n
Usage Syntax: 'addConfig <key> <value>'\n
Example:
piBlock> addConfig email someone@somewhere.com\n""")
self.terminal.nextLine()
self.terminal.nextLine()
else:
if self.app.piBlockEngine.doesConfigKeyExist(args[0]):
originalValue = self.app.piBlockEngine.getConfigValueForKey(args[0])
self.terminal.write("[Error] - Cannot Add Config Setting '{}' because it already exists".format(args[0]))
self.terminal.nextLine()
self.terminal.write("Config Setting for '{}' already exists with value '{}'. Cannot add a setting that already exists in the config. If you wanted to update this '{}' setting with the value '{}', use the updateConfig command by issuing 'updateConfig {} {}'.".format(args[0], originalValue, args[0], args[1], args[0], args[1]))
self.terminal.nextLine()
self.terminal.write("""Expects 2 Arguments, seperated by a ' '. A <key> for the setting name and <value> for the setting value. Note: <key> must not exist in configuration.\n
Conditions: <key> must Not Exist, User = 'admin' & Status = 'Initialised'\n
Usage Syntax: 'addConfig <key> <value>'\n
Example:
piBlock> addConfig email someone@somewhere.com\n""")
self.terminal.nextLine()
self.terminal.nextLine()
else:
self.logger.debug('Valid Number of Arguments were Provided...')
self.logger.debug("Attempting to Add Config setting '{}' with value '{}'".format(args[0], args[1]))
try:
self.app.piBlockEngine.addConfig(args[0], args[1])
self.terminal.nextLine()
self.terminal.write("Successfully added configuration setting '{}' with value '{}'".format(args[0], args[1]))
self.terminal.nextLine()
self.outputTitleText("PiBlock's Current Configuration Settings")
self.logger.debug("Displaying All Current Config Values")
self.terminal.write(self.app.piBlockEngine.getVerboseConfigData())
self.terminal.nextLine()
self.terminal.nextLine()
except BaseException as e:
self.terminal.write("[Error] - {}.".format(e.message))
self.terminal.nextLine()
self.terminal.write("""Expects 2 Arguments, seperated by a ' '. A <key> for the setting name and <value> for the setting value. Note: <key> must not exist in configuration.\n
Conditions: <key> must Not Exist, User = 'admin' & Status = 'Initialised'\n
Usage Syntax: 'addConfig <key> <value>'\n
Example:
piBlock> addConfig email someone@somewhere.com\n""")
self.terminal.nextLine()
self.terminal.nextLine()
self.logger.debug("Finished!")
#-------------------------------------------------------------
#Commands: Config - Update a Configuration
#-------------------------------------------------------------
def do_updateConfig(self, *args):
#DOCUMENTATION BLOCK
"""\nUpdates (and saves) a Config Setting.\n=====================================\n
Expects 2 Arguments, seperated by a ' '. A <key> for the setting name and <value> for the setting value. Note: <key> must exist in configuration.\n
Conditions: <key> must Exist, User = 'admin' & Status = 'Initialised'\n
Usage Syntax: 'updateConfig <key> <value>'\n
Example:
piBlock> updateConfig email someone@somewhere.com\n"""
self.logger.debug("Started...")
if not self.isAdminUser() or not self.isAppStatusInitialised():
self.terminal.write("[Permission Denied] - Only Admin user can add a config setting or PiBlock can only add a config setting when it is in the 'Initialised' state.")
self.terminal.nextLine()
self.terminal.write("To add a config setting, make sure you are logged in as 'admin' and PiBlock is in the 'Initialised' state.")
self.terminal.nextLine()
self.terminal.nextLine()
else:
if len(args) != 2:
self.terminal.write("[Error] - Invalid number of arguments supplied.")
self.terminal.nextLine()
self.terminal.write("""Expects 2 Arguments, seperated by a ' '. A <key> for the setting name and <value> for the setting value. Note: <key> must exist in configuration.\n
Conditions: <key> must Exist, User = 'admin' & Status = 'Initialised'\n
Usage Syntax: 'updateConfig <key> <value>'\n
Example:
piBlock> updateConfig email someone@somewhere.com\n""")
self.terminal.nextLine()
self.terminal.nextLine()
else:
if not self.app.piBlockEngine.doesConfigKeyExist(args[0]):
self.terminal.write("[Error] - Cannot Update Config Setting '{}' because it does not Exist.".format(args[0]))
self.terminal.nextLine()
self.terminal.write("Config Setting for '{}' does not exist. Cannot update a setting that does not exists in the config. If you wanted to add this '{}' setting with the value '{}', use the addConfig command by issuing 'addConfig {} {}'.".format(args[0], args[0], args[1], args[0], args[1]))
self.terminal.nextLine()
self.terminal.write("""Expects 2 Arguments, seperated by a ' '. A <key> for the setting name and <value> for the setting value. Note: <key> must not exist in configuration.\n
Conditions: <key> must Not Exist, User = 'admin' & Status = 'Initialised'\n
Usage Syntax: 'addConfig <key> <value>'\n
Example:
piBlock> addConfig email someone@somewhere.com\n""")
self.terminal.nextLine()
self.terminal.nextLine()
else:
self.logger.debug('Valid Number of Arguments were Provided...')
self.logger.debug("Attempting to Update Config setting '{}' with value '{}'".format(args[0], args[1]))
try:
self.app.piBlockEngine.updateConfig(args[0], args[1])
self.terminal.nextLine()
self.terminal.write("Successfully updated configuration setting '{}' with value '{}'".format(args[0], args[1]))
self.terminal.nextLine()
self.outputTitleText("PiBlock's Current Configuration Settings")
self.logger.debug("Displaying All Current Config Values")
self.terminal.write(self.app.piBlockEngine.getVerboseConfigData())
self.terminal.nextLine()
self.terminal.nextLine()
except BaseException as e:
self.terminal.write("[Error] - {}.".format(e.message))
self.terminal.nextLine()
self.terminal.write("""Expects 2 Arguments, seperated by a ' '. A <key> for the setting name and <value> for the setting value. Note: <key> must not exist in configuration.\n
Conditions: <key> must Not Exist, User = 'admin' & Status = 'Initialised'\n
Usage Syntax: 'addConfig <key> <value>'\n
Example:
piBlock> addConfig email someone@somewhere.com\n""")
self.terminal.nextLine()
self.terminal.nextLine()
self.logger.debug("Finished!")
#-------------------------------------------------------------
#Commands: Quotation - Get List of supported currencies
#-------------------------------------------------------------
def do_supportedCurrencies(self, *args):
#DOCUMENTATION BLOCK
"""\nDisplays a list of PiBlock's Supported Fiat Currencies.\n=======================================================\n
Expects No Arguments.\n
Conditions: None\n
Shortcut: 'curr'
Usage Syntax: 'supportedCurrencies'\n
Example:
piBlock> supportedCurrencies\n"""
self.logger.debug("Started...")
self.terminal.nextLine()
listOfSupportedCurrencies = self.app.piBlockEngine.getListOfSupportedCurrencies()
listOfOutputCurrText = list()
for n in range(len(listOfSupportedCurrencies)):
listOfOutputCurrText.append("({}){}".format(self.app.piBlockEngine.getSymbolForCurrency(listOfSupportedCurrencies[n]), listOfSupportedCurrencies[n]))
self.print_topics("PiBlock's Current Supported Currencies", listOfOutputCurrText, 15, 80)
self.logger.debug("Finished!")
#-------------------------------------------------------------
#Commands: Quotation - Get Rate for a Currency Pair - Supports Multiple Currency Queries
#-------------------------------------------------------------
def do_rate(self, *args):
#DOCUMENTATION BLOCK
"""\nDisplays Rate for BTC-Currency Pair.\n====================================\n
No Arguments expected but an optional argument or list of arguments can be specified for a particular currency quotations. (Note: Currency Identifiers are specified by a 3 character alphabet string.)
If no Arguments supplied, rate quoted is for the Default Currency. It also supports quoting rates for a list of supported currencies. For list of supported currencies by issue the 'supportedCurrencies' command.\n
Conditions: None\n
Usage Syntax: 'rate [<CurrencyIdentifier(1)> <CurrencyIdentifier(2)> ... <CurrencyIdentifier(n)>]'\n
Example to Query Default Currency Rate:
piBlock> rate\n
Example to Query Currency Rate in (€)EURO:
piBlock> rate EUR\n
Example to Query Currency Rate in (€)EURO & ($)USD:
piBlock> rate EUR USD\n"""
self.logger.debug("Started...")
self.terminal.nextLine()
if len(args) == 0:
currency = self.app.piBlockEngine.getConfigValueForKey('defaultCurrency')
if currency == None:
self.logger.debug("No Default Currency set!")
self.terminal.write("[WARNING] - Default Currency Not Found! Unable to get any Exchange Rate because there is no 'defaultCurrency' set in the configuration. You need to resolve this immediately.")
self.terminal.nextLine()
if self.app.status != 'Initialised':
self.terminal.write("- Stop Tendering... (issue 'stopTendering' command)")
self.terminal.nextLine()
if self.user.username != 'admin':
self.terminal.write("- Close this session and re-login as admin user")
self.terminal.nextLine()
self.terminal.write("- Add a Config Setting for 'defaultCurrency' setting. (Example: piBlock> addConfig defaultCurrency EUR)")
self.terminal.nextLine()
self.terminal.nextLine()
self.terminal.write("Note: You could re-issue this command 'rate' with a currency specifier.\nExample to Query Currency Rate in (€)EURO:\npiBlock> rate EUR\nPlease consult 'supportedCurrencies' command for a currency identifier")
self.terminal.nextLine()
else:
self.logger.debug("Querying Currency Rate for Default Currency '{}'...".format(currency))
currencySymbol = self.app.piBlockEngine.getSymbolForCurrency(currency)
self.outputTitleText("Latest Quote for ({}){}".format(currencySymbol, currency))
self.terminal.write("{} {}{} buys you 1.0 BTC\n{} {}1.00 buys you {} BTC".format(currency, currencySymbol, self.app.piBlockEngine.rateForCurrency(currency), currency, currencySymbol, self.app.piBlockEngine.rateForBTC(currency)))
self.terminal.nextLine()
self.logger.debug("Querying Currency Rate...Done!")
else:
for curr in args:
currency = curr.upper()
if len(currency) == 3:
if self.app.piBlockEngine.btcPricingLookup.isSupportedCurrency(currency):
currencySymbol = self.app.piBlockEngine.getSymbolForCurrency(currency)
self.outputTitleText("Latest Quote for ({}){}".format(currencySymbol, currency))
self.terminal.write("{} {}{} buys you 1.0 BTC\n{} {}1.00 buys you {} BTC".format(currency, currencySymbol, self.app.piBlockEngine.rateForCurrency(currency), currency, currencySymbol, self.app.piBlockEngine.rateForBTC(currency)))
self.terminal.nextLine()
self.terminal.nextLine()
else:
self.terminal.write("[WARNING] - Currency Specified: '{}' is not supported by PiBlock.".format(currency))
self.terminal.nextLine()
self.terminal.write("Please consult the documentation or issue the 'supportedCurrencies' command to get a full list of PiBlock's supported currencies.")
self.terminal.nextLine()
self.terminal.nextLine()
else:
self.terminal.write("[WARNING] - Currency Specified: '{}' is not supported by PiBlock.".format(currency))
self.terminal.nextLine()
self.terminal.write("Please consult the documentation or issue the 'supportedCurrencies' command to get a full list of PiBlock's supported currencies.")
self.terminal.nextLine()
self.terminal.nextLine()
self.logger.debug("Finished!")
#-------------------------------------------------------------
#Commands: Quotation - Gets a BTC Amount for Currency Amount
#-------------------------------------------------------------
def do_convertToBTC(self, *args):
#DOCUMENTATION BLOCK
"""\nDisplays a BTC Amount equivalent to the Currency Amount Given.\n==============================================================\n
Expects 1 Argument and a second optional Argument. The 1st argument is the amount of currency to be converted, the second argument is the currency identifier. If there is no second argument specified then piBlock will resolve the calculation in the default currency.\n
Conditions: None\n
Usage Syntax: 'convertToBTC <amount> <currency>'\n
Example:
piBlock> convertToBTC 10\n
Example with specifying a currency:
piBlock> convertToBTC 10 CAD\n"""
self.logger.debug("Started...")
if (len(args) < 1) or (len(args) > 2):
self.terminal.write("[Error] - Invalid number of arguments supplied.")
self.terminal.nextLine()
self.terminal.write("""Expects 1 Argument and a second optional Argument. The 1st argument is the amount of currency to be converted, the second argument is the currency identifier. If there is no second argument specified then piBlock will resolve the calculation in the default currency.\n
Conditions: None\n
Usage Syntax: 'convertToBTC <amount> <currency>'\n
Example:
piBlock> convertToBTC 10\n
Example with specifying a currency:
piBlock> convertToBTC 10 CAD""")
self.terminal.nextLine()
self.terminal.nextLine()
else:
amount = args[0]
try:
amountFloat = float(amount)
currency = self.app.piBlockEngine.getConfigValueForKey("defaultCurrency")
currencySymbol = self.app.piBlockEngine.getSymbolForCurrency(currency)
if (len(args) == 2):
currency = args[1]
currency = currency.upper()
if self.app.piBlockEngine.btcPricingLookup.isSupportedCurrency(currency):
currencySymbol = self.app.piBlockEngine.getSymbolForCurrency(currency)
finalAmountFloat = self.app.piBlockEngine.convertToBTC(amount,currency)
rate = self.app.piBlockEngine.rateForBTC(currency)
rateFloat = float(rate)
formattedAmount = "{0:.2f}".format(amountFloat)
formattedFinalAmount = "{0:.9f}".format(finalAmountFloat)
self.logger.debug("Rate is {} per {}1.00".format(rateFloat, currencySymbol))
self.logger.debug("Amount Queried is {} {}{}".format(currency, currencySymbol, amountFloat))
self.logger.debug("Final Amount is {0:.2f}".format(finalAmountFloat))
self.outputTitleText("({}) {} Currency Conversion to BTC:".format(currencySymbol, currency))
self.terminal.write("{} {}{} buys you {} BTC\nRate:{} {}{} buys you 1.00 BTC".format(currency, currencySymbol, formattedAmount, formattedFinalAmount, currency, currencySymbol, self.app.piBlockEngine.rateForCurrency(currency)))
self.terminal.nextLine()
self.terminal.nextLine()
except BaseException as e:
self.terminal.write("[Error] - {}".format(e.message))
self.terminal.nextLine()
self.terminal.write("""Expects 1 Argument and a second optional Argument. The 1st argument is the amount of currency to be converted, the second argument is the currency identifier. If there is no second argument specified then piBlock will resolve the calculation in the default currency.\n
Conditions: None\n
Usage Syntax: 'convertToBTC <amount> <currency>'\n
Example:
piBlock> convertToBTC 10\n
Example with specifying a currency:
piBlock> convertToBTC 10 CAD""")
self.terminal.nextLine()
self.terminal.nextLine()
self.logger.debug("Finished!")
# self.terminal.nextLine()
# self.terminal.write(self.stillToBeImplemented('convertToBTC'))
# self.terminal.nextLine()
#-------------------------------------------------------------
#Commands: Quotation - Gets a Currency Amount for BTC Amount
#-------------------------------------------------------------
def do_convertToCurrency(self, *args):
#DOCUMENTATION BLOCK
"""\nDisplays a Currency Amount equivalent to the BTC Amount Given.\n==============================================================\n
Expects 1 Argument and a second optional Argument. The 1st argument is the amount of BTC to be converted, the second argument is the currency identifier. If there is no second argument specified then piBlock will resolve the calculation in the default currency.\n
Conditions: None\n
Usage Syntax: 'convertToCurrency <amount> <currency>'\n
Example:
piBlock> convertToCurrency 1.9020\n
Example with specifying a currency:
piBlock> convertToCurrency 1.9020 CAD\n"""
self.logger.debug("Started...")
if (len(args) < 1) or (len(args) > 2):
self.terminal.write("[Error] - Invalid number of arguments supplied.")
self.terminal.nextLine()
self.terminal.write("""Expects 1 Argument and a second optional Argument. The 1st argument is the amount of BTC to be converted, the second argument is the currency identifier. If there is no second argument specified then piBlock will resolve the calculation in the default currency.\n
Conditions: None\n
Usage Syntax: 'convertToCurrency <amount> <currency>'\n
Example:
piBlock> convertToCurrency 1.9020\n
Example with specifying a currency:
piBlock> convertToCurrency 1.9020 CAD""")
self.terminal.nextLine()
self.terminal.nextLine()
else:
amount = args[0]
try:
amountFloat = float(amount)
currency = self.app.piBlockEngine.getConfigValueForKey("defaultCurrency")
currencySymbol = self.app.piBlockEngine.getSymbolForCurrency(currency)
if (len(args) == 2):
currency = args[1]
currency = currency.upper()
if self.app.piBlockEngine.btcPricingLookup.isSupportedCurrency(currency):
currencySymbol = self.app.piBlockEngine.getSymbolForCurrency(currency)
finalAmountFloat = self.app.piBlockEngine.convertToCurrency(amount,currency)
rate = self.app.piBlockEngine.rateForBTC(currency)
rateFloat = float(rate)
amountFloat = float(amount)
formattedAmount = "{0:.9f}".format(amountFloat)
formattedFinalAmount = "{0:.2f}".format(finalAmountFloat)
self.logger.debug("Rate is {} BTC per {}1.00".format(rateFloat, currencySymbol))
self.logger.debug("Amount Queried is {} BTC".format(amountFloat))
self.logger.debug("Final Amount is {}".format(formattedFinalAmount))
self.outputTitleText("BTC Conversion to ({}) {}:".format(currencySymbol, currency))
self.terminal.write("{} BTC buys you {} {}{}\nRate:{} {}{} buys you 1.00 BTC".format(formattedAmount, currency, currencySymbol, formattedFinalAmount, currency, currencySymbol, self.app.piBlockEngine.rateForCurrency(currency)))
self.terminal.nextLine()
self.terminal.nextLine()
except BaseException as e:
self.terminal.write("[Error] - {}".format(e.message))
self.terminal.nextLine()
self.terminal.write("""Expects 1 Argument and a second optional Argument. The 1st argument is the amount of BTC to be converted, the second argument is the currency identifier. If there is no second argument specified then piBlock will resolve the calculation in the default currency.\n
Conditions: None\n
Usage Syntax: 'convertToCurrency <amount> <currency>'\n
Example:
piBlock> convertToCurrency 1.9020\n
Example with specifying a currency:
piBlock> convertToCurrency 1.9020 CAD""")
self.terminal.nextLine()
self.terminal.nextLine()
self.logger.debug("Finished!")
#-------------------------------------------------------------
#Command: System - Uptime
#-------------------------------------------------------------
def do_uptime(self, *args):
#DOCUMENTATION BLOCK
"""\nDisplays the system uptime.\n===========================\n
Expects No Arguments.\n
Conditions: None\n
Usage Syntax: 'uptime'\n
Example:
piBlock> uptime\n"""
self.logger.debug("Started...")
self.terminal.nextLine()
self.terminal.write("PiBlock has been running for ~ {}".format(self.app.uptime))
self.terminal.nextLine()
self.logger.debug("Finished!")
#-------------------------------------------------------------
#Command: System - SysStatus
#-------------------------------------------------------------
def do_sysStatus(self, *args):
#DOCUMENTATION BLOCK
"""\nDisplays the status state of the system.\n========================================\n
Expects No Arguments.\n
Conditions: None\n
Shortcut: 'stat'
Usage Syntax: 'sysStatus'\n
Example:
piBlock> sysStatus\n"""
self.logger.debug("Started...")
self.terminal.nextLine()
self.terminal.write("PiBlock's Current System Status is '{}'".format(self.app.status))
self.terminal.nextLine()
self.logger.debug("Finished!")
#-------------------------------------------------------------
#Command: Help
#-------------------------------------------------------------
def do_help(self, *args):
#DOCUMENTATION BLOCK
"""\nDisplays Help.\n==============\n
No Arguments expected but an optional argument can be specified to display additional help of a particular command.
When no arguments specified it displays a list of available commands.\n
Conditions: None\n
Usage Syntax: 'help [<command>]'\n
Shortcut: '?'
Example:
piBlock> help\n
Example when requesting help for a specific command:
piBlock> help sysStatus\n"""
self.logger.debug("Started...")
if len(args) != 0:
# XXX check arg syntax
try:
func = getattr(self, 'help_' + args[0])
except AttributeError:
try:
doc=getattr(self, 'do_' + args[0]).__doc__
if doc:
self.terminal.write("%s\n"%str(doc))
return
except AttributeError:
pass
self.terminal.write("%s\n"%str(self.nohelp % (args[0],)))
return
func()
else:
names = self.get_names()
cmds_doc = []
cmds_undoc = []
help = {}
for name in names:
if name[:5] == 'help_':
help[name[5:]]=1
names.sort()
# There can be duplicates if routines overridden
prevname = ''
for name in names:
if name[:3] == 'do_':
if name == prevname:
continue
prevname = name
cmd=name[3:]
if cmd in help:
cmds_doc.append(cmd)
del help[cmd]
elif getattr(self, name).__doc__:
cmds_doc.append(cmd)
else:
cmds_undoc.append(cmd)
self.terminal.write("%s\n"%str(self.doc_leader))
self.print_topics(self.doc_header, cmds_doc, 15,80)
self.print_topics(self.misc_header, help.keys(),15,80)
self.print_topics(self.undoc_header, cmds_undoc, 15,80)
self.logger.debug("Finished!")
#-------------------------------------------------------------
#Commands: Clear
#-------------------------------------------------------------
def do_clear(self):
#DOCUMENTATION BLOCK
"""\nClears the output of this Interactive Terminal.\n===============================================\n
Expects No Arguments.\n
Conditions: None\n
Shortcut: 'cls'
Usage Syntax: 'clear'\n
Example:
piBlock> clear\n"""
self.logger.debug("Started...")
self.terminal.reset()
self.logger.debug("Finished!")
#-------------------------------------------------------------
#Commands: Close
#-------------------------------------------------------------
def do_close(self):
#DOCUMENTATION BLOCK
"""\nCloses this Interactive Session with PiBlock.\n=============================================\n
Expects No Arguments.\n
Conditions: None\n
Shortcut: 'q'
Usage Syntax: 'close'\n
Example:
piBlock> close\n"""
self.logger.debug("Started...")
self.terminal.write("Quitting... Thanks for using piBlock... Bye bye!")
self.terminal.nextLine()
self.terminal.loseConnection()
self.logger.debug("Finished!")
#-------------------------------------------------------------
#Commands: Start Tendering
#-------------------------------------------------------------
def do_startTendering(self):
#DOCUMENTATION BLOCK
"""\nMoves PiBlock from an Initialised State to a Tendering State.\n=============================================================\n
Expects No Arguments. A Tendering State where PiBlock is ready to tender Bitcoin transactions\n
Conditions: User = 'admin' & Status = 'Initialised'\n
Shortcut: 'startX'
Usage Syntax: 'startTendering'\n
Example:
piBlock> startTendering\n"""
self.logger.debug("Started...")
if not self.isAdminUser() or not self.isAppStatusInitialised():
self.terminal.write("[Permission Denied] - Only Admin user can add move PiBlock into a 'Tendering' state when it is in the 'Initialised' state.")
self.terminal.nextLine()
self.terminal.write("To move PiBlock into a 'Tendering' state, make sure you are logged in as 'admin' and PiBlock is in the 'Initialised' state.")
self.terminal.nextLine()
self.terminal.nextLine()
else:
self.terminal.write("Attempting to move PiBlock to a Tendering State!")
self.terminal.nextLine()
try:
self.app.moveIntoTenderingState()
except Exception as e:
self.terminal.write("Could not move PiBlock to a Tendering State!")
self.terminal.nextLine()
self.terminal.write("Reason: {}".format(e.message))
self.logger.debug("Finished!")
#-------------------------------------------------------------
#Commands: Start Tendering
#-------------------------------------------------------------
def do_stopTendering(self):
#DOCUMENTATION BLOCK
"""\nMoves PiBlock from a Tendering State to an Initialised State.\n=============================================================\n
Expects No Arguments. An Initialised state is when PiBlock cannot process Bitcoins but config settings can be adjusted and other administrative tasks performed.\n
Conditions: User = 'admin' & Status = 'Tendering'\n
Shortcut: 'stopX'
Usage Syntax: 'stopTendering'\n
Example:
piBlock> stopTendering\n"""
self.logger.debug("Started...")
if not self.isAdminUser() or not self.isAppStatusTendering():
self.terminal.write("[Permission Denied] - Only Admin user can add move PiBlock out of a 'Tendering' state when it is not in the 'Tendering' state.")
self.terminal.nextLine()
self.terminal.write("To move PiBlock into a 'Tendering' state, make sure you are logged in as 'admin' and PiBlock is in the 'Tendering' state.")
self.terminal.nextLine()
self.terminal.nextLine()
else:
self.terminal.write("Attempting to move PiBlock to a Tendering State!")
self.terminal.nextLine()
try:
self.app.moveOutOfTenderingState()
except Exception as e:
self.terminal.write("Could not move PiBlock out of a Tendering State!")
self.terminal.nextLine()
self.terminal.write("Reason: {}".format(e.message))
self.logger.debug("Finished!")
#-------------------------------------------------------------
# Convenience Methods: Canned Text OUTPUT & Other Stuff
#-------------------------------------------------------------
def isAppStatusProcessing(self):
if self.app.status == 'Processing':
return True
else:
return False
def isAppStatusTendering(self):
if self.app.status == 'Tendering':
return True
else:
return False
def isAppStatusInitialised(self):
if self.app.status == 'Initialised':
return True
else:
return False
def isAdminUser(self):
if self.user.username == 'admin':
return True
else:
return False
def get_names(self):
# This method used to pull in base class attributes
# at a time dir() didn't do it yet.
return dir(self.__class__)
def print_topics(self, header, cmds, cmdlen, maxcol):
if cmds:
self.terminal.write("%s\n"%str(header))
if self.ruler:
self.terminal.write("%s\n"%str(self.ruler * len(header)))
self.columnize(cmds, maxcol-1)
self.terminal.write("\n")
def columnize(self, list, displaywidth=80):
"""Display a list of strings as a compact set of columns.
Each column is only as wide as necessary.
Columns are separated by two spaces (one was not legible enough).
"""
if not list:
self.terminal.write("<empty>\n")
return
nonstrings = [i for i in range(len(list))
if not isinstance(list[i], str)]
if nonstrings:
raise TypeError, ("list[i] not a string for i in %s" %
", ".join(map(str, nonstrings)))
size = len(list)
if size == 1:
self.terminal.write('%s\n'%str(list[0]))
return
# Try every row count from 1 upwards
for nrows in range(1, len(list)):
ncols = (size+nrows-1) // nrows
colwidths = []
totwidth = -2
for col in range(ncols):
colwidth = 0
for row in range(nrows):
i = row + nrows*col
if i >= size:
break
x = list[i]
colwidth = max(colwidth, len(x))
colwidths.append(colwidth)
totwidth += colwidth + 2
if totwidth > displaywidth:
break
if totwidth <= displaywidth:
break
else:
nrows = len(list)
ncols = 1
colwidths = [0]
for row in range(nrows):
texts = []