forked from dansinclair25/duco-rest-api
-
Notifications
You must be signed in to change notification settings - Fork 10
/
app.py
2977 lines (2519 loc) · 98.4 KB
/
app.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 python3
"""
Duino-Coin REST API © MIT licensed
https://duinocoin.com
https://github.com/revoxhere/duco-rest-api
Duino-Coin Team & Community 2019-2022
"""
import gevent.monkey
gevent.monkey.patch_all()
from werkzeug.utils import secure_filename
import string
import redis
import secrets
from datetime import timedelta
from functools import reduce
from time import time
from dotenv import load_dotenv
import base64
import functools
from flask_caching import Cache
from flask import Flask, request, jsonify, render_template
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_ipban import IpBan
from socket import socket
import json
import random
import requests
from bitcash import Key
from cashaddress import convert
from tronapi import Tron
from tronapi import HttpProvider
from nano_lib_rvx import Account
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import ssl
import smtplib
from colorama import Back, Fore, Style, init
from re import sub, match
from random import randint, choice
from time import sleep, time
from sqlite3 import connect as sqlconn
from bcrypt import hashpw, gensalt, checkpw
from json import load
import os
import traceback
import threading
from hashlib import sha1
from xxhash import xxh64
from fastrand import pcg32bounded as fastrandint
from Server import (
now, SAVE_TIME, POOL_DATABASE, CONFIG_WHITELIST_USR,
jail, global_last_block_hash, HOSTNAME,
DATABASE, DUCO_EMAIL, DUCO_PASS, alt_check, acc_check,
DB_TIMEOUT, CONFIG_MINERAPI, SERVER_VER,
CONFIG_TRANSACTIONS, API_JSON_URI, temporary_ban,
BCRYPT_ROUNDS, user_exists, SOCKET_TIMEOUT,
email_exists, send_registration_email, protocol_ban, protocol_loved_verified_mail,
DECIMALS, CONFIG_BANS, protocol_verified_mail, protocol_unverified_mail,
CONFIG_JAIL, CONFIG_WHITELIST, perm_ban,
NodeS_Overide, CAPTCHA_SECRET_KEY, CONFIG_BASE_DIR)
from validate_email import validate_email
from wrapped_duco_functions import *
import datetime
import jwt
html_recovery_template = """\
<html lang="en-US">
<head>
<style type="text/css">
@import url('https://fonts.googleapis.com/css2?family=Lato:wght@300&display=swap');
* {
font-family: 'Lato', sans-serif;
}
a:hover {
text-decoration: none !important;
}
.btn {
background: #ff9f43;
text-decoration: none !important;
font-weight: semibold;
border-radius: 16px;
margin-top: 35px;
color: #fff !important;
text-transform: uppercase;
font-size: 14px;
padding: 10px 24px;
display: inline-block;
}
.btn:hover {
background: #feca57;
}
</style>
</head>
<body marginheight="0" topmargin="0" marginwidth="0" style="margin: 0px; background-color: #fff8ee;" leftmargin="0">
<table cellspacing="0" border="0" cellpadding="0" width="100%" bgcolor="#fff8ee"">
<tr>
<td>
<table style=" background-color: #ffffff; max-width:670px; margin:0 auto;" width="100%" border="0"
align="center" cellpadding="0" cellspacing="0">
<tr>
<td style="height:80px;"> </td>
</tr>
<tr>
<td style="text-align:center;">
<a href="https://www.duinocoin.com" title="logo" target="_blank">
<img src="https://github.com/revoxhere/duino-coin/raw/master/Resources/ducobanner.png?raw=true"
width="50%" height="auto">
</a>
</td>
</tr>
<tr>
<td style="height:20px;"> </td>
</tr>
<tr>
<td>
<table width="95%" border="0" align="center" cellpadding="0" cellspacing="0"
style="max-width:670px;background:#fff; border-radius:3px; text-align:center; box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);">
<tr>
<td style="text-align:center; padding-top: 25px; height:40px; font-size: 32px;">
Hey there, {username}!
</td>
</tr>
<tr>
<td style="padding:0 35px; text-align:center;">
<h1 style="color:#1e1e2d; font-weight:500; margin:0; margin-top: 25px; font-size:16px;">
You have requested to reset your private key</h1>
<span
style="display:inline-block; vertical-align:middle; margin:29px 0 26px; border-bottom:1px solid #cecece; width:100px;"></span>
<p style="color:#455056; font-size:15px;line-height:24px; margin:0;">
Because we don't store the private keys directly, we can't just send you your old key.<br>
<b>A unique link to reset your passphrase has been generated for you.</b><br>
To reset your private key, click the following link and follow the instructions.<br>
<b>You have 30 minutes to reset your key.</b><br>
If you did not request a passphrase reset, please ignore this email.
</p>
<a href="{link}" class="btn">
Reset passphrase
</a>
</td>
</tr>
<tr>
<td style="height:40px;"> </td>
</tr>
</table>
</td>
<tr>
<td style="height:20px;"> </td>
</tr>
<tr>
<td style="text-align:center;">
<p style="font-size:14px; color:rgba(69, 80, 86, 0.7411764705882353); line-height:18px; margin:0 0 0;">
Have a great day, <a href="https://duinocoin.com/team">the Duino-Coin Team</a> 😊</p>
</td>
</tr>
<tr>
<td style="height:80px;"> </td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
"""
def forwarded_ip_check():
return request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
def dbg(*message):
if "TX" in str(message):
fg_color = Fore.YELLOW
elif "EX" in str(message):
fg_color = Fore.CYAN
elif "Error" in str(message):
fg_color = Fore.RED
elif "Success" in str(message):
fg_color = Fore.GREEN
else:
fg_color = Fore.WHITE
print(now().strftime(
Style.RESET_ALL
+ Style.DIM
+ Fore.WHITE
+ "%H:%M:%S")
+ Style.BRIGHT
+ fg_color,
*message,
Style.RESET_ALL)
# Exchange settings
exchange_address = {
"duco": "coinexchange",
"xmg": "95JLhkyWVDce5D17LyApULc5YC4vrVzaio",
"lke": "Like3yYC34YQJRMQCSbTDWKLhnzCoZvo9AwWuu5kooh",
"bch": "bitcoincash:qpgpd7slludx5h9p53qwf8pxu9z702n95qteeyzay3",
"trx": "TQUowTaHwvkWHbNVkxkAbcnbYyhF4or1Qy",
# "xrp": "rGT84ryubURwFMmiJChRbWUg9iQY18VGuQ (Destination tag: 2039609160)",
# "dgb": "DHMV4BNGpWbdhpq6Za3ArncuhpmtCjyQXg",
"nano": "nano_3fpqpbcgt3nga3s81td6bk7zcqdr7ockgnyjkcy1s8nfn98df6c5wu14fuuq",
# "rvn": "RH4bTDaHH7LSSCVSvXJzJ5KkiGR1QRMaqN",
# "nim": "NQ88 Q9ME 470X 8KY8 HXQG J96N 6FHR 8G0B EDMH"
}
fees = {
"duco": 0,
"xmg": 0.05,
"lke": 0,
"bch": 0.00006,
"trx": 1,
"nano": 0
}
load_dotenv()
IPDB_KEY = os.getenv('IPDB_KEY')
PROXYCHECK_KEY = os.getenv('PROXYCHECK_KEY')
TRX_SECRET_KEY = os.getenv('TRX_SECRET_KEY')
BCH_SECRET_KEY = os.getenv('BCH_SECRET_KEY')
LIKECOIN_SECRET_KEY = os.getenv('LIKECOIN_SECRET_KEY')
NANO_SECRET_KEY = os.getenv('NANO_SECRET_KEY')
EXCHANGE_MAIL = DUCO_EMAIL
SERVER_NAME = "duino-master-1"
STAKE_DAYS = 14
STAKING_PERC = 1.5
IP_CHECK_DISABLED = False
XXHASH_TX_PROB = 30
POOL_SYNC_TIME = 15
chain_accounts = ["bscDUCO", "celoDUCO", "maticDUCO"]
overrides = [
NodeS_Overide,
DUCO_PASS
]
config = {
"DEBUG": False,
"CACHE_TYPE": "RedisCache",
"CACHE_REDIS_URL": "redis://localhost:6379/0",
"CACHE_DEFAULT_TIMEOUT": SAVE_TIME,
"SECRET_KEY": DUCO_PASS,
"JSONIFY_PRETTYPRINT_REGULAR": False}
proxy_redis = redis.Redis(host='localhost', port=6379, db=1)
auth_redis = redis.Redis(host='localhost', port=6379, db=2)
limiter = Limiter(
key_func=forwarded_ip_check,
default_limits=["5000 per day", "5 per 1 second"])
ip_ban = IpBan(
ban_seconds=60*60,
ban_count=10,
persist=False,
ip_header='HTTP_X_REAL_IP',
record_dir="config/ipbans/",
ipc=True,
secret_key=DUCO_PASS)
app = Flask(__name__, template_folder='config/error_pages')
app.config.from_mapping(config)
cache = Cache(app)
limiter.init_app(app)
ip_ban.init_app(app)
requests_session = requests.Session()
thread_lock = threading.Lock()
nano_key = Account(priv_key=NANO_SECRET_KEY)
bch_key = Key(BCH_SECRET_KEY)
trx_key = Tron(
full_node=HttpProvider('https://api.trongrid.io'),
solidity_node=HttpProvider('https://api.trongrid.io'),
event_server=HttpProvider('https://api.trongrid.io'))
trx_key.private_key = TRX_SECRET_KEY
trx_key.default_address = exchange_address["trx"]
network = {
"name": "Duino-Coin",
"color": 'e67e22',
"avatar": 'https://github.com/revoxhere/duino-coin/raw/master/Resources/duco.png?raw=true',
}
last_transactions_update, last_miners_update, last_balances_update = 0, 0, 0
miners, balances, transactions = [], [], []
rate_count, last_transfer = {}, {}
banlist, jailedusr, registrations, whitelisted_usr = [], [], [], []
registration_db = {}
with open('config/emails/sell_manual_email.html', 'r') as file:
html_exc = file.read()
with open('config/emails/sell_email.html', 'r') as file:
html_auto = file.read()
with open('config/emails/buy_email.html', 'r') as file:
html_buy = file.read()
with open('config/emails/sell_error.html', 'r') as file:
html_error = file.read()
with open('config/emails/stake_finished.html', 'r') as file:
html_stake_finished = file.read()
def fetch_bans():
global jail, banlist, whitelisted_usr, whitelist
jail, banlist, whitelisted_usr, whitelist = [], [], [], []
while True:
with open(CONFIG_JAIL, "r") as jailedfile:
jailedusr = jailedfile.read().splitlines()
for username in jailedusr:
jail.append(username.strip())
with open(CONFIG_BANS, "r") as bannedusrfile:
bannedusr = bannedusrfile.read().splitlines()
for username in bannedusr:
banlist.append(username.strip())
with open(CONFIG_WHITELIST_USR, "r") as whitelistedusrfile:
whitelist = whitelistedusrfile.read().splitlines()
for username in whitelist:
whitelisted_usr.append(username.strip())
with open(CONFIG_WHITELIST, "r") as whitelistfile:
whitelist = whitelistfile.read().splitlines()
for ip in whitelist:
ip_ban.ip_whitelist_add(ip.strip())
dbg("Loaded bans and whitelist")
sleep(30)
jail, banlist, whitelisted_usr, whitelist = [], [], [], []
with open(CONFIG_JAIL, "r") as jailedfile:
jailedusr = jailedfile.read().splitlines()
for username in jailedusr:
jail.append(username.strip())
with open(CONFIG_BANS, "r") as bannedusrfile:
bannedusr = bannedusrfile.read().splitlines()
for username in bannedusr:
banlist.append(username.strip())
with open(CONFIG_WHITELIST_USR, "r") as whitelistedusrfile:
whitelist = whitelistedusrfile.read().splitlines()
for username in whitelist:
whitelisted_usr.append(username.strip())
with open(CONFIG_WHITELIST, "r") as whitelistfile:
whitelist = whitelistfile.read().splitlines()
for ip in whitelist:
ip_ban.ip_whitelist_add(ip.strip())
dbg("Loaded bans and whitelist")
# threading.Thread(target=fetch_bans).start()
def clear_obs():
global observations
while True:
observations = {}
dbg("Cleared observations")
sleep(15*60)
# threading.Thread(target=clear_obs).start()
def likecoin_transaction(recipient: str, amount: int, comment: str):
data = {
"address": str(recipient),
"amount": str(int(amount) * 1000000000),
"comment": str(comment),
"prv": LIKECOIN_SECRET_KEY}
r = requests.post(
"https://wallet.likecoin.pro/api/v0/new-transfer",
data=data).json()
if "error" in r:
raise Exception(r["error"])
else:
return r["hash"]
observations = {}
@app.errorhandler(429)
def error429(e):
global observations
ip_addr = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
ip_ban.add(ip=ip_addr)
try:
observations[ip_addr] += 1
except:
observations[ip_addr] = 1
if observations[ip_addr] > 30:
# if not ip_addr in whitelist:
#dbg("Too many observations", ip_addr)
# ip_addr_ban(ip_addr)
# ip_ban.block(ip_addr)
return render_template('403.html'), 403
else:
limit_err = str(e).replace("429 Too Many Requests: ", "")
#dbg("Error 429", ip_addr, limit_err, os.getpid())
return render_template('429.html', limit=limit_err), 429
@app.errorhandler(404)
def error404(e):
ip_addr = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
page_name = str(request.url)
ip_ban.add(ip=ip_addr)
if "php" in page_name:
print("serio xD")
return "we're not even using php you dumb fuck"
elif "eval" in page_name:
print("serio 2 xD")
return "debil XD"
try:
observations[ip_addr] += 1
except:
observations[ip_addr] = 1
if observations[ip_addr] > 30:
# if not ip_addr in whitelist:
#dbg("Too many observations", ip_addr)
# ip_addr_ban(ip_addr)
# ip_ban.block(ip_addr)
return render_template('403.html'), 403
else:
if "auth" in page_name:
return _success("OK")
dbg("Error 404", ip_addr, page_name)
return render_template('404.html', page_name=page_name), 404
@app.errorhandler(500)
def error500(e):
ip_addr = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
dbg("Error 500", ip_addr)
try:
observations[ip_addr] += 1
except:
observations[ip_addr] = 1
if observations[ip_addr] > 30:
# if not ip_addr in whitelist:
#dbg("Too many observations - banning", ip_addr)
# ip_addr_ban(ip_addr)
# ip_ban.block(ip_addr)
return render_template('403.html'), 403
else:
return render_template('500.html'), 500
@app.errorhandler(403)
def error403(e):
ip_addr = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
ip_ban.add(ip=ip_addr)
ip_ban.block(ip_addr)
dbg("Error 403", ip_addr)
try:
observations[ip_addr] += 1
except:
observations[ip_addr] = 1
if observations[ip_addr] > 30:
if not ip_addr in whitelist:
dbg("Too many observations - banning", ip_addr)
ip_addr_ban(ip_addr)
# ip_ban.block(ip_addr)
return render_template('403.html'), 403
cached_logins = {}
def login(username: str, unhashed_pass: str):
global cached_logins
try:
try:
data = jwt.decode(unhashed_pass, app.config['SECRET_KEY'], algorithms=['HS256'])
except jwt.ExpiredSignatureError:
return (False, 'Token expired. Please log in again.')
except jwt.DecodeError: # if the token is invalid
if not match(r"^[A-Za-z0-9_-]*$", username):
return (False, "Incorrect username")
if username in cached_logins:
if unhashed_pass == cached_logins[username]:
return (True, "Logged in")
else:
return (False, "Invalid password")
try:
with sqlconn(DATABASE, timeout=DB_TIMEOUT) as conn:
datab = conn.cursor()
datab.execute(
"""SELECT *
FROM Users
WHERE username = ?""",
(str(username),))
data = datab.fetchone()
if len(data) > 1:
stored_password = data[1]
else:
return (False, "No user found")
try:
if checkpw(unhashed_pass, stored_password):
cached_logins[username] = unhashed_pass
return (True, "Logged in")
return (False, "Invalid password")
except Exception:
if checkpw(unhashed_pass, stored_password.encode('utf-8')):
cached_logins[username] = unhashed_pass
return (True, "Logged in")
return (False, "Invalid password")
except Exception as e:
return (False, "DB Err: " + str(e))
try:
email = get_email(username)
if data['email'] == email:
return (True, "Logged in")
except Exception as e:
return (False, "DB Err:" + str(e))
except Exception as e:
print(e)
def check_ip(ip):
global IP_CHECK_DISABLED
try:
if IP_CHECK_DISABLED or ip in whitelist:
return "False,None"
elif not ip:
return "True,Your IP address is hidden"
elif proxy_redis.get(ip):
if "," in proxy_redis.get(ip).decode():
if "True" in proxy_redis.get(ip).decode():
print(ip, "is cached", proxy_redis.get(ip).decode())
return proxy_redis.get(ip).decode()
try:
response = requests_session.get(
f"http://proxycheck.io/v2/{ip}"
+ f"?key={PROXYCHECK_KEY}&vpn=1&proxy=1").json()
if "proxy" in response[ip]:
if response[ip]["proxy"] == "yes":
dbg("Proxy detected: " + str(ip))
proxy_redis.get(ip, "True,You're using a proxy")
return "True,You're using a proxy"
if "vpn" in response[ip]:
if response[ip]["vpn"] == "yes":
dbg("VPN detected: " + str(ip))
proxy_redis.get(ip, "True,You're using a VPN")
return "True,You're using a VPN"
except:
IP_CHECK_DISABLED = True
proxy_redis.get(ip, "False,None")
return "False,None"
except Exception as e:
return "False,None"
def ip_addr_ban(ip, perm=False):
if not ip in whitelist:
ip_ban.block(ip)
if perm:
perm_ban(ip)
else:
temporary_ban(ip)
def _success(result, code=200):
return jsonify(result=result, success=True, server=SERVER_NAME), code
def _error(result, code=200):
ip_addr = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
ip_ban.add(ip=ip_addr)
print(result)
try:
observations[ip_addr] += 1
except:
observations[ip_addr] = 1
if observations[ip_addr] > 30:
if not ip_addr in whitelist:
dbg("Too many observations - banning", ip_addr)
ip_addr_ban(ip_addr)
ip_ban.block(ip_addr)
sleep(observations[ip_addr])
return render_template('403.html'), 403
else:
return jsonify(message=result, success=False, server=SERVER_NAME), code
def _proxy():
ip_addr = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
threading.Thread(target=ip_addr_ban, args=[ip_addr, True]).start()
return _error("You're using a proxy or VPN")
def get_all_transactions():
global transactions
global last_transactions_update
if time() - last_transactions_update > SAVE_TIME:
# print(f'fetching transactions from {CONFIG_TRANSACTIONS}')
try:
with sqlconn(CONFIG_TRANSACTIONS, timeout=DB_TIMEOUT) as conn:
datab = conn.cursor()
datab.execute("SELECT * FROM Transactions")
rows = datab.fetchall()
transactions = {}
for row in rows:
transactions[row[4]] = row_to_transaction(row)
last_transactions_update = time()
except Exception as e:
print(traceback.format_exc())
return transactions
def row_to_transaction(row):
return {
'datetime': str(row[0]),
'sender': str(row[1]),
'recipient': str(row[2]),
'amount': float(row[3]),
'hash': str(row[4]),
'memo': str(sub(r"[^A-Za-z0-9 .-:!#_+-]+", ' ', str(row[5]))),
'id': int(row[6])
}
def get_transactions(username: str, limit=10, reverse=True):
try:
order = "DESC"
if reverse:
order = "ASC"
with sqlconn(CONFIG_TRANSACTIONS, timeout=DB_TIMEOUT) as conn:
datab = conn.cursor()
datab.execute("""
SELECT * FROM (
SELECT * FROM Transactions
WHERE username = ?
OR recipient = ?
ORDER BY id DESC
LIMIT ?
) ORDER BY id """ + order,
(username, username, limit))
rows = datab.fetchall()
return [row_to_transaction(row) for row in rows]
except Exception as e:
return str(e)
def get_all_miners():
global last_miners_update
global miners
if time() - last_miners_update > SAVE_TIME:
try:
# print(f'fetching miners from {CONFIG_MINERAPI}')
with sqlconn(CONFIG_MINERAPI, timeout=DB_TIMEOUT) as conn:
datab = conn.cursor()
datab.execute("SELECT * FROM Miners")
rows = datab.fetchall()
last_miners_update = time()
miners = {}
for row in rows:
if not row[1] in miners:
miners[row[1]] = []
miners[row[1]].append(row_to_miner(row))
except Exception as e:
pass
return miners
def row_to_miner(row):
return {
"threadid": str(row[0]),
"username": str(row[1]),
"hashrate": float(row[2]),
"sharetime": float(row[3]),
"accepted": int(row[4]),
"rejected": int(row[5]),
"diff": int(row[6]),
"software": str(row[7]),
"identifier": str(row[8]),
"algorithm": str(row[9]),
"pool": str(row[10]),
"wd": row[11],
"ki": int(row[13])
}
def get_miners(username: str):
with sqlconn(CONFIG_MINERAPI, timeout=DB_TIMEOUT) as conn:
datab = conn.cursor()
datab.execute("SELECT * FROM Miners WHERE username = ?", (username, ))
rows = datab.fetchall()
if len(rows) < 1:
raise Exception("No miners detected")
rows.sort(key=lambda tup: tup[1])
return [row_to_miner(row) for row in rows]
trusted = {}
creation = {}
def get_all_balances():
global balances
global last_balances_update
global balances
global trusted
global creation
if time() - last_balances_update > 30:
try:
# print(f'fetching balances from {DATABASE}')
with sqlconn(DATABASE, timeout=DB_TIMEOUT) as conn:
datab = conn.cursor()
datab.execute("SELECT * FROM Users")
rows = datab.fetchall()
balances = {}
trusted = {}
for row in rows:
balances[row[0]] = row[3]
creation[row[0]] = row[4].lower()
trusted[row[0]] = row[5].lower()
last_balances_update = time()
except Exception as e:
print(traceback.format_exc())
return balances
def get_user_data(username: str):
with sqlconn(DATABASE, timeout=DB_TIMEOUT) as conn:
datab = conn.cursor()
datab.execute("""
SELECT *
FROM Users
WHERE username = ?""",
(username, ))
row = datab.fetchone()
if not row:
raise Exception(f"{username} not found")
try:
stake = str(row[7]).split(",")
stake_date = int(stake[0])
stake_amount = float(stake[1])
except:
stake_date, stake_amount = 0, 0
if stake_date != 0 and stake_date <= time():
print(username, "is elgible for stake rewards!")
unstake(username)
login_date = auth_redis.get(username)
if not login_date:
login_date = 0
else:
login_date = round(float(login_date))
return {
"username": str(username),
"balance": round(row[3], DECIMALS),
"verified": str(row[5]).lower(),
"created": str(row[4]).lower(),
"stake_date": stake_date,
"stake_amount": round(stake_amount, DECIMALS),
"last_login": login_date,
}
def get_email(username):
with sqlconn(DATABASE, timeout=DB_TIMEOUT) as conn:
datab = conn.cursor()
datab.execute("""
SELECT *
FROM Users
WHERE username = ?""",
(username, ))
return datab.fetchone()[2]
def send_stake_email(username, amount, txid):
try:
email = get_email(username)
message = MIMEMultipart("alternative")
message["Subject"] = "🥰 Your DUCO staking has just finished!"
message["From"] = DUCO_EMAIL
message["To"] = email
email_body = html_stake_finished.replace(
"{txid}", str(txid)
).replace(
"{user}", str(username)
).replace(
"{amount}", str(amount)
)
part = MIMEText(email_body, "html")
message.attach(part)
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as smtp:
smtp.login(
DUCO_EMAIL, DUCO_PASS)
smtp.sendmail(
DUCO_EMAIL, email, message.as_string())
except Exception:
print(traceback.format_exc())
def unstake(username: str):
try:
with sqlconn(DATABASE, timeout=DB_TIMEOUT) as conn:
datab = conn.cursor()
datab.execute(
"""SELECT *
FROM Users
WHERE username = ?""",
(username,))
balance = float(datab.fetchone()[3])
stake_data = str(datab.fetchone()[7])
try:
stake_balance = float(stake_data.split(",")[1])
except Exception as e:
return _error("Nothing to unstake")
try:
stake_date = int(stake_data.split(",")[0])
except Exception as e:
return _error("No staking active")
stake_reward = float(stake_balance) * (1 + (STAKING_PERC/100))
balance += round(stake_reward, DECIMALS)
stake_data = 0
while True:
try:
with sqlconn(DATABASE, timeout=DB_TIMEOUT) as conn:
datab = conn.cursor()
datab.execute(
"""UPDATE Users
set balance = ?
where username = ?""",
(balance, username))
datab.execute(
"""UPDATE Users
set stake = ?
where username = ?""",
(stake_data, username))
conn.commit()
break
except:
pass
global_last_block_hash_cp = get_txid()
formatteddatetime = now().strftime("%d/%m/%Y %H:%M:%S")
with sqlconn(CONFIG_TRANSACTIONS,
timeout=DB_TIMEOUT) as conn:
datab = conn.cursor()
datab.execute(
"""INSERT INTO Transactions
(timestamp, username, recipient, amount, hash, memo)
VALUES(?, ?, ?, ?, ?, ?)""",
(formatteddatetime,
"Duino-Coin Masternode",
username,
stake_reward,
global_last_block_hash_cp,
"Staking rewards"))
conn.commit()
dbg(f"Success: unstaked {stake_reward} DUCO from {username}")
threading.Thread(
target=send_stake_email,
args=[username, amount, global_last_block_hash_cp]
).start()
return _success(f"Unstaked,{global_last_block_hash_cp}")
except Exception as e:
print(e)
return _error(e)
def stake(username: str, amount: float, days: int):
try:
stake_end = datetime.date.today() + datetime.timedelta(int(days))
stake_end_unix = int(stake_end.strftime("%s"))
dbg(f"{username}'s stake for {amount} DUCO will end {stake_end}")
if int(days) <= 0:
return _error("Incorrect days")
if (str(amount) == "" or float(amount) < 20):
return _error("Incorrect amount")
with sqlconn(DATABASE, timeout=DB_TIMEOUT) as conn:
datab = conn.cursor()
datab.execute(
"""SELECT *
FROM Users
WHERE username = ?""",
(username,))
row = datab.fetchone()
balance = float(row[3])
stake_data = str(row[7])
try:
stake_balance = float(stake_data.split(",")[1])
except Exception as e:
stake_balance = 0
try:
stake_date_old = int(stake_data.split(",")[0])
except Exception as e:
stake_date_old = 0
if stake_date_old > time() or stake_balance > 0:
return _error(f"You are already staking {stake_balance} DUCO, "
+ "please wait for the current stake to finish")
if (float(balance) <= float(amount)):
return _error("Incorrect amount")
if float(balance) >= float(amount):
balance -= float(amount)
stake_balance += float(amount)
stake_data = f"{stake_end_unix},{stake_balance}"
while True:
try:
with sqlconn(DATABASE,
timeout=DB_TIMEOUT) as conn:
datab = conn.cursor()
datab.execute(
"""UPDATE Users
set balance = ?
where username = ?""",
(balance, username))
datab.execute(
"""UPDATE Users
set stake = ?
where username = ?""",
(stake_data, username))
conn.commit()
break
except:
pass
global_last_block_hash_cp = get_txid()
formatteddatetime = now().strftime("%d/%m/%Y %H:%M:%S")
with sqlconn(CONFIG_TRANSACTIONS,
timeout=DB_TIMEOUT) as conn:
datab = conn.cursor()
datab.execute(
"""INSERT INTO Transactions
(timestamp, username, recipient, amount, hash, memo)
VALUES(?, ?, ?, ?, ?, ?)""",
(formatteddatetime,
username,
"Duino-Coin Masternode",