-
Notifications
You must be signed in to change notification settings - Fork 27
/
raiwalletbot.py
1859 lines (1711 loc) · 73.8 KB
/
raiwalletbot.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/bin/env python
# -*- coding: utf-8 -*-
#
# Nano Telegram bot
# @NanoWalletBot https://t.me/NanoWalletBot
#
# Source code:
# https://github.com/SergiySW/NanoWalletBot
#
# Released under the BSD 3-Clause License
#
"""
Usage:
Press Ctrl-C on the command line or send a signal to the process to stop the bot.
"""
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from telegram.ext.dispatcher import run_async
from telegram import Bot, ParseMode, ReplyKeyboardMarkup, ReplyKeyboardRemove, ChatAction
from telegram.error import BadRequest, RetryAfter, TimedOut, NetworkError
import logging
import urllib3, certifi, socket, json, re
import hashlib, binascii, string, math
from mysql.connector import ProgrammingError
import time
from time import sleep
import os, sys
# Parse config
from six.moves import configparser
config = configparser.ConfigParser()
config.read('bot.cfg')
api_key = config.get('main', 'api_key')
url = config.get('main', 'url')
log_file = config.get('main', 'log_file')
log_file_messages = config.get('main', 'log_file_messages')
domain = config.get('main', 'domain')
listen_port = config.get('main', 'listen_port')
qr_folder_path = config.get('main', 'qr_folder_path')
passport_folder_path = config.get('main', 'passport_folder_path')
wallet = config.get('main', 'wallet')
wallet_password = config.get('main', 'password')
fee_account = config.get('main', 'fee_account')
fee_amount = int(config.get('main', 'fee_amount'))
welcome_account = config.get('main', 'welcome_account')
welcome_amount = int(config.get('main', 'welcome_amount'))
raw_welcome_amount = welcome_amount * (10 ** 24)
incoming_fee_text = '\n'
min_send = int(config.get('main', 'min_send'))
min_receive = int(config.get('main', 'min_receive'))
feeless_seconds = int(config.get('main', 'feeless_seconds'))
feeless_hours = int(feeless_seconds / 3600)
ddos_protect_seconds = config.get('main', 'ddos_protect_seconds')
admin_list = json.loads(config.get('main', 'admin_list'))
extra_limit = int(config.get('main', 'extra_limit'))
LIST_OF_FEELESS = json.loads(config.get('main', 'feeless_list'))
enable_registration = json.loads(config.get('main', 'enable_registration').lower())
salt = config.get('password', 'salt')
pbkdf2_iterations = int(config.get('password', 'pbkdf2_iterations'))
private_key = config.get('password', 'private_key')
block_count_difference_threshold = int(config.get('monitoring', 'block_count_difference_threshold'))
proxy_url = config.has_option('proxy', 'url') and config.get('proxy', 'url') or None
proxy_user = config.has_option('proxy', 'user') and config.get('proxy', 'user') or None
proxy_pass = config.has_option('proxy', 'password') and config.get('proxy', 'password') or None
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO, filename=log_file)
logging.getLogger("requests").setLevel(logging.WARNING)
logger = logging.getLogger(__name__)
account_url = 'https://nanocrawler.cc/explorer/account/'
hash_url = 'https://nanocrawler.cc/explorer/block/'
faucet_url = 'https://faucet.raiblockscommunity.net/form.php'
nanocrawler_url = 'https://api.nanocrawler.cc/block_count_by_type'
header = {'user-agent': 'RaiWalletBot/1.0'}
# MySQL requests
from common_mysql import *
# QR code handler
from common_qr import *
# Request to node
from common_rpc import *
# Common functions
from common import *
# unlock(wallet, wallet_password)
# Restrict access to admins only
from functools import wraps
def restricted(func):
@wraps(func)
def wrapped(bot, update, *args, **kwargs):
# extract user_id from arbitrary update
try:
user_id = update.message.from_user.id
except (NameError, AttributeError):
try:
user_id = update.inline_query.from_user.id
except (NameError, AttributeError):
try:
user_id = update.chosen_inline_result.from_user.id
except (NameError, AttributeError):
try:
user_id = update.callback_query.from_user.id
except (NameError, AttributeError):
print("No user_id available in update.")
return
if user_id not in admin_list:
print("Unauthorized access denied for {0}.".format(user_id))
return
return func(bot, update, *args, **kwargs)
return wrapped
# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
with open('language.json') as lang_file:
language = json.load(lang_file)
def lang(user_id, text_id):
lang_id = mysql_select_language(user_id)
try:
return language[lang_id][text_id]
except KeyError:
return language['en'][text_id]
def lang_text(text_id, lang_id):
try:
return language[lang_id][text_id]
except KeyError:
return language['en'][text_id]
@run_async
def custom_keyboard(bot, chat_id, buttons, text):
reply_markup = ReplyKeyboardMarkup(buttons, resize_keyboard = True)
try:
bot.sendMessage(chat_id=chat_id,
text=text,
parse_mode=ParseMode.MARKDOWN,
disable_web_page_preview=True,
reply_markup=reply_markup)
except BadRequest:
bot.sendMessage(chat_id=chat_id,
text=replace_unsafe(text),
parse_mode=ParseMode.MARKDOWN,
disable_web_page_preview=True,
reply_markup=reply_markup)
except RetryAfter:
sleep(240)
bot.sendMessage(chat_id=chat_id,
text=text,
parse_mode=ParseMode.MARKDOWN,
disable_web_page_preview=True,
reply_markup=reply_markup)
except TimedOut:
sleep(10)
bot.sendMessage(chat_id=chat_id,
text=text,
parse_mode=ParseMode.MARKDOWN,
disable_web_page_preview=True,
reply_markup=reply_markup)
except:
sleep(1)
bot.sendMessage(chat_id=chat_id,
text=text,
parse_mode=ParseMode.MARKDOWN,
disable_web_page_preview=True,
reply_markup=reply_markup)
@run_async
def default_keyboard(bot, chat_id, text):
custom_keyboard(bot, chat_id, lang(chat_id, 'menu'), text)
@run_async
def lang_keyboard(lang_id, bot, chat_id, text):
custom_keyboard(bot, chat_id, lang_text('menu', lang_id), text)
@run_async
def hide_keyboard(bot, chat_id, text):
reply_markup = ReplyKeyboardRemove()
try:
bot.sendMessage(chat_id=chat_id, text=text, reply_markup=reply_markup)
except:
sleep(1)
bot.sendMessage(chat_id=chat_id, text=text, reply_markup=reply_markup)
@run_async
def typing_illusion(bot, chat_id):
try:
bot.sendChatAction(chat_id=chat_id, action=ChatAction.TYPING) # typing illusion
except:
sleep(1)
bot.sendChatAction(chat_id=chat_id, action=ChatAction.TYPING) # typing illusion
@run_async
def ddos_protection(bot, update, callback):
user_id = update.message.from_user.id
message_id = int(update.message.message_id)
ddos = mysql_ddos_protector(user_id, message_id)
if (ddos == True):
logging.warning('DDoS or double message by user {0} message {1}'.format(user_id, message_id))
elif (ddos == False):
text_reply(update, lang(user_id, 'ddos_error').format(ddos_protect_seconds))
logging.warning('Too fast request by user {0}'.format(user_id))
else:
callback(bot, update)
@run_async
def ddos_protection_args(bot, update, args, callback):
user_id = update.message.from_user.id
message_id = int(update.message.message_id)
ddos = mysql_ddos_protector(user_id, message_id)
if (ddos == True):
logging.warning('DDoS or double message by user {0} message {1}'.format(user_id, message_id))
elif (ddos == False):
text_reply(update, lang(user_id, 'ddos_error').format(ddos_protect_seconds))
logging.warning('Too fast request by user {0}'.format(user_id))
else:
callback(bot, update, args)
@run_async
def info_log(update, protected = False):
result = {}
full_text = True
if (protected is True):
password_hash = mysql_check_password(update.message.from_user.id) # Check password protection
if (password_hash is not False):
split_text = update.message.text.rsplit(' ', 1) # split text in 2 parts
if(len(split_text) > 1):
full_text = False
result['text'] = update.message.text.rsplit(' ', 1)[0]+' PossiblePassword'
elif ((update.message.text.lower() not in language['commands']['yes']) and (update.message.text.lower() not in language['commands']['not'])):
m = mysql_select_user(update.message.from_user.id)
# Only if send destination is defined
if (m[5] is not None):
full_text = False
result['text'] = 'PossiblePassword'
if (full_text is True):
result['text'] = update.message.text
result['user_id'] = update.message.from_user.id
result['username'] = update.message.from_user.username
result['first_name'] = update.message.from_user.first_name
result['last_name'] = update.message.from_user.last_name
result['timestamp'] = int(time.mktime(update.message.date.timetuple()))
result['message_id'] = update.message.message_id
logging.info(result)
@run_async
def language_select(bot, update, args):
info_log(update)
ddos_protection_args(bot, update, args, language_select_callback)
@run_async
def language_select_callback(bot, update, args):
user_id = update.message.from_user.id
chat_id = update.message.chat_id
if (len(args) > 0):
lang_id = args[0].lower()
if (lang_id in language['common']['language_list']):
try:
mysql_set_language(user_id, lang_id)
start_text(bot, update)
except:
text_reply(update, lang(user_id, 'language_error'))
else:
text_reply(update, lang(user_id, 'language_error'))
logging.info('Language change failed for user {0}'.format(user_id))
else:
text_reply(update, lang(user_id, 'language_command'))
@run_async
def start(bot, update):
info_log(update)
ddos_protection(bot, update, start_text)
@run_async
def start_text(bot, update):
user_id = update.message.from_user.id
chat_id = update.message.chat_id
lang_id = mysql_exist_language(user_id)
if (lang_id is False):
try:
lang_id = update.message.from_user.language_code
if (lang_id in language['common']['language_list']):
mysql_set_language(user_id, lang_id)
else:
lang_id = mysql_select_language(user_id)
except Exception as e:
lang_id = mysql_select_language(user_id)
if (enable_registration is False):
text_reply(update, lang_text('registration_disabled', lang_id))
sleep(1)
text_reply(update, lang_text('start_introduce', lang_id))
sleep(1)
lang_keyboard(lang_id, bot, chat_id, lang_text('start_basic_commands', lang_id).format(mrai_text(fee_amount), mrai_text(min_send), incoming_fee_text, mrai_text(min_receive), feeless_hours))
sleep(1)
message_markdown(bot, chat_id, lang_text('start_learn_more', lang_id))
# Check user existance in database
exist = mysql_user_existance(user_id)
# Select language if 1st time
if (exist is False):
sleep(1)
custom_keyboard(bot, chat_id, lang_text('language_keyboard', 'common'), lang_text('language_selection', 'common'))
sleep(2)
message_markdown(bot, chat_id, lang_text('start_recovery_policy', lang_id))
sleep(2)
message_markdown(bot, chat_id, lang_text('start_recovery_policy_2', lang_id))
@run_async
def help(bot, update):
info_log(update)
ddos_protection(bot, update, help_callback)
@run_async
def help_callback(bot, update):
user_id = update.message.from_user.id
chat_id = update.message.chat_id
lang_id = mysql_select_language(user_id)
lang_keyboard(lang_id, bot, chat_id, lang_text('help_advanced_usage', lang_id).format(mrai_text(fee_amount), mrai_text(min_send), incoming_fee_text, mrai_text(min_receive), feeless_hours))
sleep(1)
message_markdown(bot, chat_id, lang_text('help_learn_more', lang_id))
@run_async
def help_text(bot, update):
user_id = update.message.from_user.id
chat_id = update.message.chat_id
lang_id = mysql_select_language(user_id)
lang_keyboard(lang_id, bot, chat_id, lang_text('start_basic_commands', lang_id).format(mrai_text(fee_amount), mrai_text(min_send), incoming_fee_text, mrai_text(min_receive), feeless_hours))
sleep(1)
message_markdown(bot, chat_id, lang_text('help_learn_more', lang_id))
def user_id(bot, update):
user_id = update.message.from_user.id
text_reply(update, user_id)
@run_async
def block_count(bot, update):
info_log(update)
ddos_protection(bot, update, block_count_callback)
@run_async
def block_count_callback(bot, update):
user_id = update.message.from_user.id
count = rpc({"action": "block_count"}, 'count')
text_reply(update, "{:,}".format(int(count)))
# default_keyboard(bot, update.message.chat_id, r)
# Admin block count check from nanocrawler.cc
if (user_id in admin_list):
http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED',ca_certs=certifi.where())
response = http.request('GET', nanocrawler_url, headers=header, timeout=20.0)
json_data = json.loads(response.data)
nanocrawler_count = int(json_data['send']) + int(json_data['receive']) + int(json_data['open']) + int(json_data['change']) + int(json_data['state'])
if (math.fabs(int(nanocrawler_count) - int(count)) > block_count_difference_threshold):
text_reply(update, 'nanocrawler.cc: {0}'.format("{:,}".format(int(nanocrawler_count))))
reference_count = int(reference_block_count())
sleep(1)
text_reply(update, 'Reference: {0}'.format("{:,}".format(reference_count)))
response = http.request('GET', 'https://raiwallet.info/api/block_count.php', headers=header, timeout=20.0)
raiwallet_count = int(response.data)
sleep(1)
text_reply(update, 'raiwallet.info: {0}'.format("{:,}".format(raiwallet_count)))
# broadcast
@restricted
def broadcast(bot, update):
info_log(update)
bot = Bot(api_key)
# list users from MySQL
accounts_list = mysql_select_accounts_balances()
# some users are bugged & stop broadcast - they deleted chat with bot. So we blacklist them
BLACK_LIST = mysql_select_blacklist()
for account in accounts_list:
# if not in blacklist and has balance
if ((account[0] not in BLACK_LIST) and (int(account[1]) > 0)):
mysql_set_blacklist(account[0])
print(account[0])
push_simple(bot, account[0], update.message.text.replace('/broadcast ', ''))
sleep(0.2)
mysql_delete_blacklist(account[0]) # if someone deleted chat, broadcast will fail and he will remain in blacklist
# bootstrap
@restricted
def bootstrap(bot, update):
info_log(update)
bootstrap_multi()
bot.sendMessage(update.message.chat_id, "Bootstraping...")
@restricted
def restart(bot, update):
bot.sendMessage(update.message.chat_id, "Bot is restarting...")
sleep(0.2)
os.execl(sys.executable, sys.executable, *sys.argv)
#@restricted
@run_async
def account(bot, update):
info_log(update)
ddos_protection(bot, update, account_text)
@run_async
def account_list(bot, update):
info_log(update)
ddos_protection(bot, update, account_text_list)
@run_async
def account_text_list(bot, update):
account_text(bot, update, True)
@run_async
def accounts_hide(bot, update):
info_log(update)
ddos_protection(bot, update, accounts_hide_callback)
@run_async
def accounts_hide_callback(bot, update):
user_id = update.message.from_user.id
hide = mysql_select_hide(user_id)
if (hide == 0):
extra_accounts = mysql_select_user_extra(user_id)
if (len(extra_accounts) > 0):
mysql_set_hide(user_id, 1)
else:
mysql_set_hide(user_id, 0)
account_text(bot, update)
@run_async
def account_text(bot, update, list = False):
user_id = update.message.from_user.id
chat_id = update.message.chat_id
lang_id = mysql_select_language(user_id)
username=update.message.from_user.username
if (username is None):
username = ''
#print(username)
m = mysql_select_user(user_id)
try:
r = m[2]
qr_by_account(r)
balance = account_balance(r)
total_balance = balance
# FEELESS
if ((user_id in LIST_OF_FEELESS) or (mysql_select_send_time(user_id) is not False)):
final_fee_amount = 0
else:
final_fee_amount = fee_amount
# FEELESS
max_send = balance - final_fee_amount
extra_accounts = mysql_select_user_extra(user_id)
extra_array = []
for extra_account in extra_accounts:
extra_array.append(extra_account[3])
if (len(extra_accounts) > 0):
balances = accounts_balances(extra_array)
hide = mysql_select_hide(user_id)
num = 0
for extra_account in extra_accounts:
num = num + 1
total_balance = total_balance + balances[extra_account[3]]
# price
price = mysql_select_price()
if (int(price[0][0]) > 0):
last_price = ((float(price[0][0]) * float(price[0][6])) + (float(price[1][0]) * float(price[1][6])) + (float(price[3][0]) * float(price[3][6])) + (float(price[5][0]) * float(price[5][6]))) / (float(price[0][6]) + float(price[1][6]) + float(price[3][6]) + float(price[5][6]))
else:
last_price = int(price[1][0])
btc_price = last_price / (10 ** 14)
btc_balance = ('%.8f' % (btc_price * total_balance))
# price
if (list is not False):
text = 'Total: *{0} Nano*\n~ {1} BTC\n/{3}\n{4}'.format(mrai_text(total_balance), btc_balance, '', lang_text('account_add', lang_id).replace("_", "\_"), lang_text('send_all', lang_id))
message_markdown(bot, chat_id, text)
sleep(1)
message_markdown(bot, chat_id, '*0.* {0} Nano'.format(mrai_text(balance)))
sleep(1)
message_markdown(bot, chat_id, '*{0}*'.format(r))
sleep(1)
for extra_account in extra_accounts:
message_markdown(bot, chat_id, '*{0}.* {1} Nano /{2} {0}'.format(extra_account[2], mrai_text(balances[extra_account[3]]), lang_text('send_from_command', lang_id).replace("_", "\_")))
sleep(1)
text_reply(update, extra_account[3])
sleep(1)
else:
if ((balance == 0) and (list is False)):
text = lang_text('account_balance_zero', lang_id).format(faucet_url, r)
elif ((max_send < min_send) and (list is False)):
text = lang_text('account_balance_low', lang_id).format(faucet_url, r, mrai_text(balance), mrai_text(final_fee_amount), mrai_text(min_send))
else:
if (balance == total_balance):
text = lang_text('account_balance', lang_id).format(mrai_text(balance), btc_balance, mrai_text(max_send))
else:
text = lang_text('account_balance_total', lang_id).format(mrai_text(balance), btc_balance, mrai_text(max_send), mrai_text(total_balance))
text = '{0}\n\n{1}'.format(text, lang_text('account_your', lang_id))
message_markdown(bot, chat_id, text)
sleep(1)
message_markdown(bot, chat_id, '*{0}*'.format(r))
sleep(1)
if ((num > 3) and (hide == 0)):
message_markdown(bot, chat_id, lang_text('account_history', lang_id).format(r, account_url, faucet_url, '').replace(lang_text('account_add', lang_id).replace("_", "\_"), lang_text('account_list', lang_id).replace("_", "\_"))) # full accounts list
elif (hide == 1):
message_markdown(bot, chat_id, lang_text('account_history', lang_id).format(r, account_url, faucet_url, '').replace(lang_text('account_add', lang_id).replace("_", "\_"), lang_text('account_list', lang_id).replace("_", "\_")).replace(lang_text('accounts_hide', lang_id).replace("_", "\_"), lang_text('accounts_expand', lang_id).replace("_", "\_"))) # hide-expand
else:
message_markdown(bot, chat_id, lang_text('account_history', lang_id).format(r, account_url, faucet_url, ''))
sleep(1)
# list
if (hide == 0):
n = 0
for extra_account in extra_accounts:
n = n + 1
if (n <= 3):
message_markdown(bot, chat_id, '*{0}.* {1} Nano /{2} {0}'.format(extra_account[2], mrai_text(balances[extra_account[3]]), lang_text('send_from_command', lang_id).replace("_", "\_")))
sleep(1)
text_reply(update, extra_account[3])
sleep(1)
# list
#bot.sendPhoto(chat_id=update.message.chat_id, photo=open('{1}{0}.png'.format(r, qr_folder_path), 'rb'), caption=r)
try:
bot.sendPhoto(chat_id=update.message.chat_id, photo=open('{1}nano:{0}.png'.format(r, qr_folder_path), 'rb'))
except (urllib3.exceptions.ProtocolError) as e:
sleep(3)
bot.sendPhoto(chat_id=update.message.chat_id, photo=open('{1}nano:{0}.png'.format(r, qr_folder_path), 'rb'))
except TimedOut as e:
sleep(10)
bot.sendPhoto(chat_id=update.message.chat_id, photo=open('{1}nano:{0}.png'.format(r, qr_folder_path), 'rb'))
except NetworkError as e:
sleep(20)
bot.sendPhoto(chat_id=update.message.chat_id, photo=open('{1}nano:{0}.png'.format(r, qr_folder_path), 'rb'))
seed = mysql_select_seed(user_id)
password_hash = mysql_check_password(user_id)
if ((seed is False) and (password_hash is False)):
sleep(1)
seed_callback(bot, update, [0])
elif (password_hash is not False):
sleep(1)
text_reply(update, lang_text('seed_protected', lang_id))
except (TypeError):
if (enable_registration is True):
r = rpc({"action": "account_create", "wallet": wallet}, 'account')
qr_by_account(r)
if ('xrb_' in r or 'nano_' in r): # check for errors
insert_data = {
'user_id': user_id,
'account': r,
'chat_id': chat_id,
'username': username,
}
mysql_insert(insert_data)
text_reply(update, lang_text('account_created', lang_id))
sleep(1)
message_markdown(bot, chat_id, '*{0}*'.format(r))
sleep(1)
message_markdown(bot, chat_id, lang_text('account_explorer', lang_id).format(r, account_url))
sleep(1)
message_markdown(bot, chat_id, lang_text('account_balance_start', lang_id).format(faucet_url, r))
sleep(1)
custom_keyboard(bot, chat_id, lang_text('language_keyboard', 'common'), lang_text('language_selection', 'common'))
if (welcome_amount > 0):
try:
welcome = rpc_send(wallet, welcome_account, r, raw_welcome_amount)
sleep(0.5) # workaround
new_balance = account_balance(welcome_account)
if (new_balance == 0): # workaround
sleep(2)
new_balance = account_balance(account)
if (new_balance == 0):
sleep(16)
new_balance = account_balance(account)
mysql_update_balance(welcome_account, new_balance)
mysql_update_frontier(welcome_account, welcome)
except Exception as e:
logging.exception("message")
logging.info('New user registered {0} {1}'.format(user_id, r))
sleep(2)
seed_callback(bot, update, [0])
else:
text_reply(update, lang_text('account_error', lang_id))
else:
text_reply(update, lang_text('registration_disabled', lang_id))
#@restricted
@run_async
def account_add(bot, update):
info_log(update)
ddos_protection(bot, update, account_add_callback)
@run_async
def account_add_callback(bot, update):
user_id = update.message.from_user.id
chat_id = update.message.chat_id
lang_id = mysql_select_language(user_id)
extra_accounts = mysql_select_user_extra(user_id)
if (enable_registration is False):
text_reply(update, lang_text('registration_disabled', lang_id))
elif (len(extra_accounts) >= extra_limit):
text_reply(update, lang_text('account_extra_limit', lang_id).format(extra_limit))
else:
r = rpc({"action": "account_create", "wallet": wallet}, 'account')
extra_id = len(mysql_select_user_extra(user_id)) + 1
if ('xrb_' in r or 'nano_' in r): # check for errors
insert_data = {
'user_id': user_id,
'account': r,
'extra_id': extra_id,
}
mysql_insert_extra(insert_data)
text_reply(update, lang_text('account_created', lang_id))
sleep(1)
message_markdown(bot, chat_id, '[{0}]({1}{0})'.format(r, account_url))
logging.info('New account registered {0} {1}'.format(user_id, r))
else:
text_reply(update, lang_text('account_error', lang_id))
def password_check(update, password):
user_id = update.message.from_user.id
password_hash = mysql_check_password(user_id)
if (password_hash is not False):
dk = '0000'
try:
if (len(password_hash) == 128):
# New Scrypt KDF
dk = hashlib.scrypt(password.encode('utf-8'), salt=(hashlib.sha3_224(user_id.to_bytes(6, byteorder='little')).hexdigest()+salt).encode('utf-8'), n=2**15, r=8, p=1, maxmem=2**26, dklen=64)
else:
# Old PBKDF2 KDF
dk = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt.encode(), pbkdf2_iterations)
except UnicodeEncodeError as e:
text_reply(update, lang(user_id, 'encoding_error'))
sleep(0.5)
hex = binascii.hexlify(dk).decode()
if (hex == password_hash):
valid = True
else:
valid = False
logging.info('Wrong password for user {0}. Expected: {1}, given: {2}'.format(user_id, password_hash, hex))
else:
valid = True
return valid
@run_async
def send(bot, update, args):
info_log(update, True)
ddos_protection_args(bot, update, args, send_callback)
@run_async
def send_from(bot, update, args):
info_log(update, True)
ddos_protection_args(bot, update, args, send_from_callback)
@run_async
def send_from_callback(bot, update, args):
user_id = update.message.from_user.id
if (len(args) > 0):
if ('xrb_' in args[0] or 'nano_' in args[0]):
xrb_account = validate_account_number(args[0])
if (xrb_account is not False):
from_account = mysql_select_by_account_extra(xrb_account)
else:
from_account = False
else:
try:
extra_id = int(args[0].replace('.',''))
from_account = mysql_select_by_id_extra(user_id, extra_id)
except (ValueError, ProgrammingError) as e:
from_account = False
text_reply(update, lang(user_id, 'value_error'))
try:
if (from_account is not False):
if (user_id == from_account[0]):
args = args[1:]
send_callback(bot, update, args, from_account)
else:
text_reply(update, lang(user_id, 'send_from_id_error').format(args[0]))
logging.warning('User {0} trying to steal funds from {1}'.format(user_id, args[0]))
elif ((int(args[0]) == 0) or (args[0] == 'default')):
args = args[1:]
send_callback(bot, update, args)
else:
text_reply(update, lang(user_id, 'send_from_id_error').format(args[0]))
except ValueError as e:
text_reply(update, lang(user_id, 'value_error'))
else:
m = mysql_select_user(user_id)
chat_id = update.message.chat_id
lang_id = mysql_select_language(user_id)
lang_keyboard(lang_id, bot, chat_id, lang_text('send_wrong_command', lang_id).format(mrai_text(min_send), 'nano\\_accountsample'))
# Instant receiving
@run_async
def receive(destination, send_hash):
destination_local = mysql_select_by_account(destination)
if (destination_local is False):
destination_local = mysql_select_by_account_extra(destination)
if (destination_local is not False):
receive = rpc({"action": "receive", "wallet": wallet, "account": destination, "block": send_hash}, 'block')
if ('receive' not in receive):
logging.warning('Block already received {0}'.format(send_hash))
@run_async
def send_callback(bot, update, args, from_account = 0):
user_id = update.message.from_user.id
chat_id = update.message.chat_id
lang_id = mysql_select_language(user_id)
if (len(args) >= 2):
try:
# Check user existance in database
m = mysql_select_user(user_id)
if (from_account == 0):
account = m[2]
else:
account = from_account[1]
# Check balance to send
try:
balance = account_balance(account)
# FEELESS
if ((user_id in LIST_OF_FEELESS) or (mysql_select_send_time(user_id) is not False)):
final_fee_amount = 0
else:
final_fee_amount = fee_amount
# FEELESS
max_send = balance - final_fee_amount
if ((args[0].lower() == 'all') or (args[0].lower() == 'everything')):
send_amount = max_send
else:
send_amount = int(float(args[0]) * (10 ** 6))
raw_send_amount = send_amount * (10 ** 24)
if (max_send < min_send):
text_reply(update, lang_text('send_low_balance', lang_id).format(mrai_text(final_fee_amount), mrai_text(min_send)))
elif (send_amount > max_send):
text_reply(update, lang_text('send_limit_max', lang_id).format(mrai_text(final_fee_amount), mrai_text(max_send)))
elif (send_amount < min_send):
text_reply(update, lang_text('send_limit_min', lang_id).format(mrai_text(min_send)))
else:
# Check destination address
destination = args[1]
if ((len(args) > 2) and ((args[1].lower() == 'mrai') or (args[1].lower() == 'xrb') or (args[1].lower() == 'nano'))):
destination = args[2]
# if destination is username
if (destination.startswith('@') and len(destination) >= 5 and len(destination) <= 32):
username = destination.replace('@', '').replace(' ','').replace('\r','').replace('\n','')
username = username.replace(r'[^[0-9a-zA-Z_]+', '')
try:
dest_account = mysql_account_by_username(username)
if (dest_account is not False):
destination = dest_account
else:
text_reply(update, lang_text('send_user_not_found', lang_id).format(destination))
except UnicodeEncodeError as e:
text_reply(update, lang_text('send_user_not_found', lang_id).format(destination))
destination = validate_account_number(destination)
# Check password protection
valid_password = False
if ((len(args) > 3) and ((args[1].lower() == 'mrai') or (args[1].lower() == 'xrb') or (args[1].lower() == 'nano'))):
password = args[3]
valid_password = password_check(update, password)
elif (len(args) > 2):
password = args[2]
valid_password = password_check(update, password)
else:
password_hash = mysql_check_password(user_id)
if (password_hash is False):
valid_password = True
# typing_illusion(bot, update.message.chat_id) # typing illusion
# Check password protection and frontier existance
if (from_account == 0):
frontier = m[3]
else:
frontier = from_account[2]
check_frontier = check_block(frontier)
account_user_id = mysql_user_id_from_account (account)
if ((destination is not False) and (valid_password) and (check_frontier) and (account_user_id == user_id)):
# Sending
try:
try:
send_hash = rpc_send(wallet, account, destination, raw_send_amount)
except Exception as e:
send_hash = '0000000000000000000000000000000000000000000000000000000000000000'
logging.exception("message")
if (('0000000000000000000000000000000000000000000000000000000000000000' not in send_hash) and ('locked' not in send_hash)):
new_balance = block_balance(send_hash)
if (new_balance != balance - send_amount - final_fee_amount):
logging.error('Unexpected balance for send block {0}, account {1}. Result {2}, expected {3}'.format(send_hash, account, mrai_text(new_balance), mrai_text(balance - send_amount - final_fee_amount)))
if (from_account == 0):
mysql_update_balance(account, new_balance)
mysql_update_frontier(account, send_hash)
else:
mysql_update_balance_extra(account, new_balance)
mysql_update_frontier_extra(account, send_hash)
lang_keyboard(lang_id, bot, chat_id, lang_text('send_completed', lang_id).format(mrai_text(final_fee_amount), mrai_text(new_balance)))
mysql_update_send_time(user_id)
sleep(1)
message_markdown(bot, chat_id, '[{0}]({1}{0})'.format(send_hash, hash_url))
logging.info('Send from {0} to {1} amount {2} hash {3}'.format(account, destination, mrai_text(send_amount), send_hash))
# update username
if (from_account == 0):
old_username = m[8]
username=update.message.from_user.username
if (username is None):
username = ''
if (not (username == old_username)):
username_text = 'Username updated: @{0} --> @{1}'.format(old_username, username)
mysql_update_username(user_id, username)
print(username_text)
logging.info(username_text)
# update username
receive(destination, send_hash)
else:
logging.warning('Transaction FAILURE! Account {0}'.format(account))
sleep(0.5) # workaround
new_balance = account_balance(account)
lang_keyboard(lang_id, bot, chat_id, lang_text('send_tx_error', lang_id).format(mrai_text(new_balance)))
unlock(wallet, wallet_password) # try to unlock wallet
except (GeneratorExit, ValueError):
lang_keyboard(lang_id, bot, chat_id, lang_text('send_error', lang_id))
elif (not valid_password):
text_reply(update, lang_text('password_error', lang_id))
logging.info('Send failure for user {0}. Reason: Wrong password'.format(user_id))
elif (not (check_frontier)):
text_reply(update, lang_text('send_frontier', lang_id))
logging.info('Send failure for user {0}. Reason: Frontier not found'.format(user_id))
elif (destination is False):
message_markdown(bot, chat_id, lang_text('send_invalid', lang_id))
elif (not (destination.startswith('@'))):
message_markdown(bot, chat_id, lang_text('send_invalid', lang_id))
elif (not (account_user_id == user_id)):
message_markdown(bot, chat_id, lang_text('send_invalid', lang_id))
logging.warning('Send failure for user {0}. Reason: User ID mismatch'.format(user_id))
except (ValueError):
text_reply(update, lang_text('send_digits', lang_id))
except (TypeError):
message_markdown(bot, chat_id, lang_text('send_no_account', lang_id))
except (IndexError):
lang_keyboard(lang_id, bot, chat_id, lang_text('send_wrong_command', lang_id).format(mrai_text(min_send), 'nano\\_accountsample'))
else:
lang_keyboard(lang_id, bot, chat_id, lang_text('send_wrong_command', lang_id).format(mrai_text(min_send), 'nano\\_accountsample'))
@run_async
def send_all(bot, update):
info_log(update)
ddos_protection(bot, update, send_all_callback)
@run_async
def send_all_callback(bot, update):
user_id = update.message.from_user.id
chat_id = update.message.chat_id
lang_id = mysql_select_language(user_id)
m = mysql_select_user(user_id)
destination = m[2]
final_fee_amount = 0 # 0 fee to accumulate
extra_accounts = mysql_select_user_extra(user_id)
extra_array = []
for extra_account in extra_accounts:
extra_array.append(extra_account[3])
reply = 0
active = mysql_select_send_all(user_id)
if ((len(extra_accounts) > 0) and (active is False)):
balances = accounts_balances(extra_array)
mysql_set_send_all(user_id)
for account, balance in balances.items():
max_send = balance - final_fee_amount
account_user_id = mysql_user_id_from_account (account)
if ((max_send >= min_send) and (account_user_id == user_id)):
if (reply == 0):
lang_keyboard(lang_id, bot, chat_id, lang_text('send_mass', lang_id))
reply = 1
try:
send_amount = max_send
raw_send_amount = send_amount * (10 ** 24)
send_hash = rpc_send(wallet, account, destination, raw_send_amount)
except Exception as e:
send_hash = '0000000000000000000000000000000000000000000000000000000000000000'
logging.exception("message")
if (('0000000000000000000000000000000000000000000000000000000000000000' not in send_hash) and ('locked' not in send_hash)):
new_balance = block_balance(send_hash)
if (new_balance != balance - send_amount - final_fee_amount):
logging.error('Unexpected balance for send block {0}, account {1}. Result {2}, expected {3}'.format(send_hash, account, mrai_text(new_balance), mrai_text(balance - send_amount - final_fee_amount)))
mysql_update_balance_extra(account, new_balance)
mysql_update_frontier_extra(account, send_hash)
mysql_update_send_time(user_id)
logging.info('Send from {0} to {1} amount {2} hash {3} /send_all'.format(account, destination, mrai_text(send_amount), send_hash))
sleep(2)
receive(destination, send_hash)
sleep(4)
else:
logging.warning('Transaction FAILURE! Account {0}'.format(account))
new_balance = account_balance(account)
lang_keyboard(lang_id, bot, chat_id, lang_text('send_tx_error', lang_id).format(mrai_text(new_balance)))
elif (not (account_user_id == user_id)):
logging.warning('Send failure for user {0}. Reason: User ID mismatch'.format(user_id))
mysql_delete_send_all(user_id)
if (reply == 0):
lang_keyboard(lang_id, bot, chat_id, lang_text('send_all_min_error', lang_id).format(mrai_text(min_send)))
@run_async
def send_text(bot, update, default = False):
user_id = update.message.from_user.id
chat_id = update.message.chat_id
lang_id = mysql_select_language(user_id)
# FEELESS
if ((user_id in LIST_OF_FEELESS) or (mysql_select_send_time(user_id) is not False)):
final_fee_amount = 0
else:
final_fee_amount = fee_amount
# FEELESS
m = mysql_select_user(user_id)
try:
account = m[2]
balance = account_balance(account)
# extra
extra_accounts = mysql_select_user_extra(user_id)
hide = mysql_select_hide(user_id)
extra_keyboard = [['Default - {0} XRB'.format(mrai_text(balance))]]
if ((len(extra_accounts) > 0) and (default is False) and (hide == 0)):
extra_array = []
for extra_account in extra_accounts:
extra_array.append(extra_account[3])
balances = accounts_balances(extra_array)
for extra_account in extra_accounts:
if (balances[extra_account[3]] >= (min_send + final_fee_amount)):
extra_keyboard.append(['{0} - {1} XRB'.format(extra_account[3], mrai_text(balances[extra_account[3]]))])
if (len(extra_keyboard) <= 1):
default = True
if ((default is False) and (hide == 0)):
custom_keyboard(bot, chat_id, extra_keyboard, lang_text('send_from', lang_id).format(''))
# extra
elif (balance >= (final_fee_amount + min_send)):
text_reply(update, lang_text('send_amount', lang_id).format(mrai_text(final_fee_amount), mrai_text(min_send)))
else:
text_reply(update, lang_text('send_low_balance', lang_id).format(mrai_text(final_fee_amount), mrai_text(min_send)))
except (TypeError):
lang_keyboard(lang_id, bot, update.message.chat_id, lang_text('send_no_account_text', lang_id))
@run_async
def send_destination(bot, update, text, qr = False):
user_id = update.message.from_user.id
chat_id = update.message.chat_id
lang_id = mysql_select_language(user_id)
# FEELESS
if ((user_id in LIST_OF_FEELESS) or (mysql_select_send_time(user_id) is not False)):
final_fee_amount = 0
else:
final_fee_amount = fee_amount
# FEELESS
# Check user existance in database
m = mysql_select_user(user_id)
try:
account = m[2]
destination = validate_account_number(text)
if (destination is not False):
mysql_update_send_destination(account, destination)
if (m[6] != 0):
custom_keyboard(bot, chat_id, lang_text('yes_no', lang_id), lang_text('send_confirm', lang_id).format(mrai_text(m[6]), mrai_text(m[6]+final_fee_amount), destination))
elif (qr is False):
text_reply(update, lang_text('send_amount', lang_id).format(mrai_text(final_fee_amount), mrai_text(min_send)))
else:
message_markdown(bot, chat_id, lang_text('send_invalid', lang_id))
except (TypeError):
lang_keyboard(lang_id, bot, chat_id, lang_text('send_no_account_text', lang_id))
@run_async
def send_destination_username(bot, update, text):
user_id = update.message.from_user.id
username = text.replace('@', '').replace(' ','').replace('\r','').replace('\n','')
username = username.replace(r'[^[0-9a-zA-Z_]+', '')
if (len(username) >= 5 and len(username) <= 32):
try:
account = mysql_account_by_username(username)
if (account is not False):
text_reply(update, lang(user_id, 'send_user').format(text, account))
send_destination(bot, update, account)
else:
text_reply(update, lang(user_id, 'send_user_not_found').format(text))