-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcoinapi.py
2410 lines (2307 loc) · 107 KB
/
coinapi.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
from fastapi import FastAPI, Response, Header, Query, Request
from fastapi.concurrency import run_in_threadpool
from contextlib import asynccontextmanager
from pydantic import BaseModel
import asyncio
from hashlib import sha256
import aiohttp
import time
from datetime import datetime
import traceback, sys
import uvicorn
import os
from typing import Union, List, Dict
import random
import redis
import pickle
import json
import uuid
import aiomysql
import math
from aiomysql.cursors import DictCursor
from cachetools import TTLCache
from discord_webhook import AsyncDiscordWebhook
from config import load_config
app = FastAPI(
title="CoinAPI",
version="0.0.1",
contact={
"name": "Pluton",
"url": "http://chat.wrkz.work/",
"email": "[email protected]",
},
docs_url="/manual"
)
config = load_config()
pool = None
api_ttlcache = TTLCache(maxsize=1024, ttl=10.0)
def round_amount(amount: float, places: int):
return math.floor(amount *10**places)/10**places
async def log_to_discord(content: str, webhook: str=None) -> None:
try:
if webhook is None:
url = config['log']['discord_webhook_default']
else:
url = webhook
webhook = AsyncDiscordWebhook(
url=url,
content=content[:1000],
)
await webhook.execute()
except Exception as e:
traceback.print_exc(file=sys.stdout)
async def open_connection():
global pool
try:
if pool is None:
pool = await aiomysql.create_pool(
host=config['mysql']['host'], port=3306, minsize=4, maxsize=8,
user=config['mysql']['user'], password=config['mysql']['password'],
db=config['mysql']['db'], cursorclass=DictCursor, autocommit=True
)
except:
print("ERROR: Unexpected error: Could not connect to MySql instance.")
traceback.print_exc(file=sys.stdout)
async def get_coin_setting():
global pool
try:
await open_connection()
async with pool.acquire() as conn:
async with conn.cursor() as cur:
coin_list = {}
sql = """
SELECT * FROM `coin_settings`
WHERE `enable`=1
"""
await cur.execute(sql, ())
result = await cur.fetchall()
if result and len(result) > 0:
for each in result:
coin_list[each['coin_name']] = each
return coin_list
except Exception:
traceback.print_exc(file=sys.stdout)
return None
async def get_coin_deposits():
global pool
try:
await open_connection()
async with pool.acquire() as conn:
async with conn.cursor() as cur:
coin_addresses = []
coin_list_key = {}
sql = """
SELECT * FROM `deposit_addresses`
"""
await cur.execute(sql,)
result = await cur.fetchall()
if result and len(result) > 0:
for each in result:
coin_list_key["{}_{}".format(each['coin_name'], each['address'])] = each
coin_addresses.append(each['address'])
return {"by_key": coin_list_key, "addresses": coin_addresses}
except Exception:
traceback.print_exc(file=sys.stdout)
return None
async def get_api_by_key(key: str):
global pool
try:
await open_connection()
async with pool.acquire() as conn:
async with conn.cursor() as cur:
sql = """
SELECT * FROM `api_users`
WHERE `api_key`=%s
"""
await cur.execute(sql, key)
result = await cur.fetchone()
if result:
return result
except Exception:
traceback.print_exc(file=sys.stdout)
return None
async def update_top_block(coin_name: str, height: int):
global pool
try:
await open_connection()
async with pool.acquire() as conn:
async with conn.cursor() as cur:
sql = """
UPDATE `coin_settings` SET `chain_height`=%s, `chain_height_set_time`=%s
WHERE `coin_name`=%s LIMIT 1;
"""
await cur.execute(sql, (height, int(time.time()), coin_name))
await conn.commit()
except Exception:
traceback.print_exc(file=sys.stdout)
return None
async def insert_address(
api_id: int, coin_name: str, address: str, extra: str, priv_key: str, tag: str, second_tag: str = None
):
global pool
try:
await open_connection()
async with pool.acquire() as conn:
async with conn.cursor() as cur:
sql = """
INSERT INTO `deposit_addresses` (`api_id`, `coin_name`, `created_date`, `address`, `address_extra`, `private_key`, `tag`, `second_tag`)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
"""
await cur.execute(sql, (api_id, coin_name, int(time.time()), address, extra, priv_key, tag, second_tag))
await conn.commit()
return cur.lastrowid
except Exception:
traceback.print_exc(file=sys.stdout)
return None
async def get_balance_coin_address(
api_id: int, coin_name: str, address: str
):
global pool
try:
await open_connection()
async with pool.acquire() as conn:
async with conn.cursor() as cur:
sql = """
SELECT * FROM `deposit_addresses`
WHERE `api_id`=%s AND `coin_name`=%s AND `address`=%s LIMIT 1;
"""
await cur.execute(sql, (api_id, coin_name, address))
result = await cur.fetchone()
if result:
return result
except Exception as e:
traceback.print_exc(file=sys.stdout)
return None
async def transfer_records(
records
):
global pool
try:
await open_connection()
async with pool.acquire() as conn:
async with conn.cursor() as cur:
sql = """
INSERT INTO `transfer_records` (`api_id`, `from_address`, `to_address`, `amount`, `coin_name`, `purpose`, `timestamp`, `ref_uuid`)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
"""
await cur.executemany(sql, records)
await conn.commit()
return True
except Exception:
traceback.print_exc(file=sys.stdout)
return False
async def insert_api_log(api_id: int, method: str, data: str, result: str):
global pool
try:
await open_connection()
async with pool.acquire() as conn:
async with conn.cursor() as cur:
sql = """
INSERT INTO `api_logs` (`api_id`, `method`, `data`, `result`, `time`)
VALUES (%s, %s, %s, %s, %s)
"""
await cur.execute(sql, (api_id, method, data, result, int(time.time())))
await conn.commit()
return True
except Exception:
traceback.print_exc(file=sys.stdout)
return False
async def insert_api_failed_log(api_id: int, method: str, data: str, result: str):
global pool
try:
await open_connection()
async with pool.acquire() as conn:
async with conn.cursor() as cur:
sql = """
INSERT INTO `api_logs_failed` (`api_id`, `method`, `data`, `result`, `time`)
VALUES (%s, %s, %s, %s, %s)
"""
await cur.execute(sql, (api_id, method, data, result, int(time.time())))
await conn.commit()
return True
except Exception:
traceback.print_exc(file=sys.stdout)
return False
async def find_tx_coin(
coin_name: str, tx: str, api_id: int
):
global pool
try:
await open_connection()
async with pool.acquire() as conn:
async with conn.cursor() as cur:
sql = """
SELECT * FROM `deposits`
WHERE `api_id`=%s AND `coin_name`=%s AND `txid`=%s LIMIT 1;
"""
await cur.execute(sql, (api_id, coin_name, tx))
result = await cur.fetchone()
if result:
return result
except Exception as e:
traceback.print_exc(file=sys.stdout)
return None
async def note_tx_coin(
coin_name: str, tx: str, api_id: int, depost_id: int
):
global pool
try:
await open_connection()
async with pool.acquire() as conn:
async with conn.cursor() as cur:
sql = """
UPDATE `deposits`
SET `already_noted`=%s, `noted_time`=%s
WHERE `api_id`=%s AND `coin_name`=%s AND `txid`=%s AND `depost_id`=%s LIMIT 1;
"""
await cur.execute(sql, (1, int(time.time()), api_id, coin_name, tx, depost_id))
await conn.commit()
return True
except Exception as e:
traceback.print_exc(file=sys.stdout)
return False
async def update_second_tag(
coin_name: str, dep_id: int, second_tag: str
):
global pool
try:
if second_tag is None:
return False
await open_connection()
async with pool.acquire() as conn:
async with conn.cursor() as cur:
sql = """
UPDATE `deposit_addresses`
SET `second_tag`=%s
WHERE `coin_name`=%s AND `id`=%s LIMIT 1;
"""
await cur.execute(sql, (second_tag, coin_name, dep_id))
await conn.commit()
return True
except Exception as e:
traceback.print_exc(file=sys.stdout)
return False
async def find_address_coin_tag(
coin_name: str, tag: str, api_id: int
):
global pool
try:
await open_connection()
async with pool.acquire() as conn:
async with conn.cursor() as cur:
sql = """
SELECT * FROM `deposit_addresses`
WHERE `api_id`=%s AND `coin_name`=%s AND `tag`=%s LIMIT 1;
"""
await cur.execute(sql, (api_id, coin_name, tag))
result = await cur.fetchone()
if result:
return result
except Exception as e:
traceback.print_exc(file=sys.stdout)
return None
async def get_addresses_coin_api(
coin_name: str, api_id: int
):
global pool
try:
await open_connection()
async with pool.acquire() as conn:
async with conn.cursor() as cur:
sql = """
SELECT `coin_name`, `created_date`, `address`, `address_extra`, `tag`, `total_deposited`, `numb_deposit`,
`total_received`, `numb_received`, `total_sent`, `numb_sent`, `total_withdrew`, `numb_withdrew` FROM `deposit_addresses`
WHERE `api_id`=%s AND `coin_name`=%s
"""
await cur.execute(sql, (api_id, coin_name))
result = await cur.fetchall()
if result:
return result
except Exception as e:
traceback.print_exc(file=sys.stdout)
return []
async def get_txes_address_coin_api(
coin_name: str, api_id: int, address: str = None, limit: int = 1000
):
global pool
try:
await open_connection()
async with pool.acquire() as conn:
async with conn.cursor() as cur:
sql_addr = ""
data_rows = [api_id, coin_name]
if address is not None:
sql_addr = " AND `deposits`.`address`=%s"
data_rows.append(address)
sql = """
SELECT `deposits`.*, `deposit_addresses`.`tag`, `deposit_addresses`.`second_tag` FROM `deposits`
INNER JOIN `deposit_addresses` ON `deposit_addresses`.`id`=`deposits`.`depost_id`
WHERE `deposits`.`api_id`=%s AND `deposits`.`coin_name`=%s
""" +sql_addr+ """
ORDER BY `deposits`.`time_insert` DESC
LIMIT %s
"""
data_rows.append(limit)
await cur.execute(sql, tuple(data_rows))
result = await cur.fetchall()
if result:
return result
except Exception as e:
traceback.print_exc(file=sys.stdout)
return []
async def insert_withdraw_success(
api_id: int, coin_name: str, from_address: str, amount: float, fee_and_tax: float, from_deposit_id: int,
to_address: str, txid: str, tx_key: str, remark: str, ref_uuid: str
):
global pool
try:
await open_connection()
async with pool.acquire() as conn:
async with conn.cursor() as cur:
sql = """
INSERT INTO `withdraws` (`api_id`, `coin_name`, `from_address`, `amount`, `fee_and_tax`, `from_deposit_id`,
`to_address`, `txid`, `tx_key`, `timestamp`, `remark`, `ref_uuid`)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
"""
await cur.execute(sql, (
api_id, coin_name, from_address, amount, fee_and_tax, from_deposit_id, to_address,
txid, tx_key, int(time.time()), remark, ref_uuid
))
await conn.commit()
return True
except Exception:
traceback.print_exc(file=sys.stdout)
return False
# End of database
async def xmr_make_integrate(
url: str, main_address: str
):
try:
headers = {
'Content-Type': 'application/json'
}
json_data = {
"jsonrpc": "2.0",
"id":"0",
"method":"make_integrated_address",
"params":{
"standard_address": main_address
}
}
async with aiohttp.ClientSession() as session:
async with session.post(url, json=json_data, headers=headers, timeout=15) as response:
if response.status == 200:
res_data = await response.read()
return json.loads(res_data.decode('utf-8'))
except Exception:
traceback.print_exc(file=sys.stdout)
return None
async def call_doge(url: str, method_name: str, coin: str, payload: str = None) -> Dict:
timeout = 150
coin_name = coin.upper()
if payload is None:
data = '{"jsonrpc": "1.0", "id":"' + str(
uuid.uuid4()) + '", "method": "' + method_name + '", "params": [] }'
else:
data = '{"jsonrpc": "1.0", "id":"' + str(
uuid.uuid4()) + '", "method": "' + method_name + '", "params": [' + payload + '] }'
try:
async with aiohttp.ClientSession() as session:
async with session.post(url, data=data, timeout=timeout) as response:
if response.status == 200:
res_data = await response.read()
res_data = res_data.decode('utf-8')
decoded_data = json.loads(res_data)
return decoded_data['result']
else:
print(f'Call {coin_name} returns {str(response.status)} with method {method_name}')
print(data)
except (aiohttp.client_exceptions.ServerDisconnectedError, aiohttp.client_exceptions.ClientOSError):
print("call_doge: got disconnected for coin: {}".format(coin_name))
except asyncio.TimeoutError:
print('TIMEOUT: method_name: {} - COIN: {} - timeout {}'.format(method_name, coin.upper(), timeout))
except Exception:
traceback.print_exc(file=sys.stdout)
async def send_external_doge(
url: str, coment_from: str, amount: float, to_address: str, coin: str, has_pos: int = 0
):
coin_name = coin.upper()
try:
comment_to = to_address
payload = f'"{to_address}", {amount}, "{coment_from}", "{comment_to}", false'
if has_pos == 1:
payload = f'"{to_address}", {amount}, "{coment_from}", "{comment_to}"'
tx_hash = await call_doge(url, 'sendtoaddress', coin_name, payload=payload)
if tx_hash:
return tx_hash
except Exception:
traceback.print_exc(file=sys.stdout)
return None
async def send_external_xmr(
runner_app, type_coin: str, from_address: str, amount: float, to_address: str,
coin: str, coin_decimal: int, tx_fee: float, is_fee_per_byte: int,
get_mixin: int, wallet_api_url: str, wallet_api_header: str
):
coin_name = coin.upper()
time_out = 150
if coin_name == "DEGO":
time_out = 300
try:
if type_coin == "XMR":
acc_index = 0
payload = {
"destinations": [{'amount': int(amount * 10 ** coin_decimal), 'address': to_address}],
"account_index": acc_index,
"subaddr_indices": [],
"priority": 1,
"unlock_time": 0,
"get_tx_key": True,
"get_tx_hex": False,
"get_tx_metadata": False
}
if coin_name == "UPX":
payload = {
"destinations": [{'amount': int(amount * 10 ** coin_decimal), 'address': to_address}],
"account_index": acc_index,
"subaddr_indices": [],
"ring_size": 11,
"get_tx_key": True,
"get_tx_hex": False,
"get_tx_metadata": False
}
result = await runner_app.call_aiohttp_wallet_xmr_bcn(
runner_app.coin_list[coin_name]['wallet_address'], 'transfer', runner_app.coin_list[coin_name]['type'], coin_name, payload=payload
)
if result and 'tx_hash' in result and 'tx_key' in result:
return {"hash": result['tx_hash'], "key": result['tx_key']}
elif type_coin == "TRTL-SERVICE" or type_coin == "BCN":
if is_fee_per_byte != 1:
payload = {
'addresses': [from_address],
'transfers': [{
"amount": int(amount * 10 ** coin_decimal),
"address": to_address
}],
'fee': int(tx_fee * 10 ** coin_decimal),
'anonymity': get_mixin
}
else:
payload = {
'addresses': [from_address],
'transfers': [{
"amount": int(amount * 10 ** coin_decimal),
"address": to_address
}],
'anonymity': get_mixin
}
result = await runner_app.call_aiohttp_wallet_xmr_bcn(
runner_app.coin_list[coin_name]['wallet_address'], 'sendTransaction', runner_app.coin_list[coin_name]['type'], coin_name, payload=payload
)
if result and 'transactionHash' in result:
return {"hash": result['transactionHash'], "key": None}
elif type_coin == "TRTL-API":
if is_fee_per_byte != 1:
json_data = {
"destinations": [{"address": to_address, "amount": int(amount * 10 ** coin_decimal)}],
"mixin": get_mixin,
"fee": int(tx_fee * 10 ** coin_decimal),
"sourceAddresses": [
from_address
],
"paymentID": "",
"changeAddress": from_address
}
else:
json_data = {
"destinations": [{"address": to_address, "amount": int(amount * 10 ** coin_decimal)}],
"mixin": get_mixin,
"sourceAddresses": [
from_address
],
"paymentID": "",
"changeAddress": from_address
}
method = "/transactions/send/advanced"
try:
headers = {
'X-API-KEY': wallet_api_header,
'Content-Type': 'application/json'
}
async with aiohttp.ClientSession() as session:
async with session.post(
wallet_api_url + method,
headers=headers,
json=json_data,
timeout=time_out
) as response:
json_resp = await response.json()
if response.status == 200 or response.status == 201:
return {"hash": json_resp['transactionHash'], "key": None}
except Exception:
traceback.print_exc(file=sys.stdout)
except Exception:
traceback.print_exc(file=sys.stdout)
return None
def print_color(prt, color: str):
if color == "red":
print(f"\033[91m{prt}\033[00m")
elif color == "green":
print(f"\033[92m{prt}\033[00m")
elif color == "yellow":
print(f"\033[93m{prt}\033[00m")
elif color == "lightpurple":
print(f"\033[94m{prt}\033[00m")
elif color == "purple":
print(f"\033[95m{prt}\033[00m")
elif color == "cyan":
print(f"\033[96m{prt}\033[00m")
elif color == "lightgray":
print(f"\033[97m{prt}\033[00m")
elif color == "black":
print(f"\033[98m{prt}\033[00m")
else:
print(f"\033[0m{prt}\033[00m")
# start of background
class BackgroundRunner:
def __init__(self, app_main):
self.app_main = app_main
self.pool = pool
self.config = config
async def open_connection(self):
try:
if self.pool is None:
self.pool = await aiomysql.create_pool(
host=config['mysql']['host'], port=3306, minsize=4, maxsize=8,
user=config['mysql']['user'], password=config['mysql']['password'],
db=config['mysql']['db'], cursorclass=DictCursor, autocommit=True
)
except:
print("ERROR: Unexpected error: Could not connect to MySql instance.")
traceback.print_exc(file=sys.stdout)
async def get_userwallet_by_extra(self, paymentid: str, coin: str, coin_family: str):
coin_name = coin.upper()
try:
await self.open_connection()
async with self.pool.acquire() as conn:
async with conn.cursor() as cur:
result = None
if coin_family in ["TRTL-API", "TRTL-SERVICE", "BCN", "XMR"]:
sql = """
SELECT * FROM `deposit_addresses`
WHERE `address_extra`=%s AND `coin_name`=%s LIMIT 1;
"""
await cur.execute(sql, (paymentid, coin_name))
result = await cur.fetchone()
elif coin_family in ["BTC", "NANO"]:
# if doge family, address is paymentid
sql = """
SELECT * FROM `deposit_addresses`
WHERE `address`=%s AND `coin_name`=%s LIMIT 1;
"""
await cur.execute(sql, (paymentid, coin_name))
result = await cur.fetchone()
return result
except Exception as e:
traceback.print_exc(file=sys.stdout)
return None
async def gettopblock(self, daemon_url: str, coin_type: str, coin: str, time_out: int = 15):
coin_name = coin.upper()
if coin_type in ["BCN", "TRTL-API", "TRTL-SERVICE"]:
method_name = "getblockcount"
full_payload = {
'params': {},
'jsonrpc': '2.0',
'id': str(uuid.uuid4()),
'method': f'{method_name}'
}
try:
async with aiohttp.ClientSession() as session:
async with session.post(
daemon_url + '/json_rpc',
json=full_payload,
timeout=time_out
) as response:
if response.status == 200:
res_data = await response.json()
result = None
if res_data and 'result' in res_data:
result = res_data['result']
else:
result = res_data
if result:
full_payload = {
'jsonrpc': '2.0',
'method': 'getblockheaderbyheight',
'params': {'height': result['count'] - 1}
}
try:
async with aiohttp.ClientSession() as session:
async with session.post(
daemon_url + '/json_rpc',
json=full_payload,
timeout=time_out
) as response:
if response.status == 200:
res_data = await response.json()
if 'result' in res_data:
return res_data['result']
else:
print("Couldn't get result for coin: {}".format(coin_name))
else:
print("Coin {} got response status: {}".format(coin_name, response.status))
except asyncio.TimeoutError:
traceback.print_exc(file=sys.stdout)
except Exception:
traceback.print_exc(file=sys.stdout)
return None
except Exception:
traceback.print_exc(file=sys.stdout)
return None
elif coin_type == "XMR":
method_name = "get_block_count"
full_payload = {
'params': {},
'jsonrpc': '2.0',
'id': str(uuid.uuid4()),
'method': f'{method_name}'
}
try:
async with aiohttp.ClientSession() as session:
async with session.post(
daemon_url + '/json_rpc',
json=full_payload,
timeout=time_out
) as response:
if response.status == 200:
try:
res_data = await response.json()
except Exception:
res_data = await response.read()
res_data = res_data.decode('utf-8')
res_data = json.loads(res_data)
result = None
if res_data and 'result' in res_data:
result = res_data['result']
else:
result = res_data
if result:
full_payload = {
'jsonrpc': '2.0',
'method': 'get_block_header_by_height',
'params': {'height': result['count'] - 1}
}
try:
async with aiohttp.ClientSession() as session:
async with session.post(
daemon_url + '/json_rpc',
json=full_payload,
timeout=time_out
) as response:
if response.status == 200:
res_data = await response.json()
if res_data and 'result' in res_data:
return res_data['result']
else:
return res_data
except Exception:
traceback.print_exc(file=sys.stdout)
return None
except Exception:
traceback.print_exc(file=sys.stdout)
return None
async def call_aiohttp_wallet_xmr_bcn(
self, wallet_url: str, method_name: str, coin_type: str, coin: str,
payload: Dict = None
) -> Dict:
coin_name = coin.upper()
full_payload = {
'params': payload or {},
'jsonrpc': '2.0',
'id': str(uuid.uuid4()),
'method': f'{method_name}'
}
timeout = 30
if method_name == "save" or method_name == "store":
timeout = 300
elif method_name == "sendTransaction":
timeout = 180
elif method_name == "createAddress" or method_name == "getSpendKeys":
timeout = 60
try:
if coin_type == "XMR":
try:
async with aiohttp.ClientSession(headers={'Content-Type': 'application/json'}) as session:
async with session.post(wallet_url, json=full_payload, timeout=timeout) as response:
# sometimes => "message": "Not enough unlocked money" for checking fee
if method_name == "transfer":
print('{} - transfer'.format(coin_name))
# print(full_payload)
if response.status == 200:
res_data = await response.read()
res_data = res_data.decode('utf-8')
if method_name == "transfer":
print(res_data)
decoded_data = json.loads(res_data)
if 'result' in decoded_data:
return decoded_data['result']
else:
return None
except asyncio.TimeoutError:
print('TIMEOUT: {} coin_name {} - timeout {}'.format(method_name, coin_name, timeout))
return None
except Exception:
traceback.print_exc(file=sys.stdout)
return None
elif coin_type in ["TRTL-SERVICE", "BCN"]:
try:
async with aiohttp.ClientSession() as session:
async with session.post(wallet_url, json=full_payload, timeout=timeout) as response:
if response.status == 200 or response.status == 201:
res_data = await response.read()
res_data = res_data.decode('utf-8')
decoded_data = json.loads(res_data)
if 'result' in decoded_data:
return decoded_data['result']
return None
except asyncio.TimeoutError:
print('TIMEOUT: {} coin_name {} - timeout {}'.format(method_name, coin_name, timeout))
return None
except Exception:
traceback.print_exc(file=sys.stdout)
return None
except asyncio.TimeoutError:
print('TIMEOUT: method_name: {} - coin_family: {} - timeout {}'.format(method_name, coin_type, timeout))
except Exception:
traceback.print_exc(file=sys.stdout)
async def update_balance_xmr(self, timer: float=10.0):
while True:
try:
if len(config['coinapi']['list_bcn_xmr']) > 0:
tasks = []
for coin_name in config['coinapi']['list_bcn_xmr']:
if runner.coin_list.get(coin_name) is not None:
tasks.append(self.update_balance_tasks_xmr(coin_name, False))
completed = 0
for task in asyncio.as_completed(tasks):
fetch_updates = await task
if fetch_updates is True:
completed += 1
except Exception:
traceback.print_exc(file=sys.stdout)
await asyncio.sleep(timer)
# To use with update_balance_xmr()
async def update_balance_tasks_xmr(self, coin_name: str, debug: bool):
if debug is True:
print_color(f"{datetime.now():%Y-%m-%d %H:%M:%S} Check balance {coin_name}", color="yellow")
gettopblock = await self.gettopblock(self.coin_list[coin_name]['daemon_address'], self.coin_list[coin_name]['type'], coin_name, time_out=60)
if gettopblock is None:
print_color(f"{datetime.now():%Y-%m-%d %H:%M:%S} Got None for top block {coin_name}", color="yellow")
return
height = int(gettopblock['block_header']['height'])
try:
set_cache_kv(
self.app_main,
"block",
self.config['coinapi']['kv_prefix'] + coin_name,
height
)
await update_top_block(
coin_name, height
)
except Exception:
traceback.print_exc(file=sys.stdout)
get_confirm_depth = self.coin_list[coin_name]['confirmation_depth']
min_deposit = self.coin_list[coin_name]['min_deposit']
coin_decimal = self.coin_list[coin_name]['decimal']
payload = {
"in": True,
"out": True,
"pending": False,
"failed": False,
"pool": False,
"filter_by_height": True,
"min_height": height - 2000,
"max_height": height
}
get_transfers = await self.call_aiohttp_wallet_xmr_bcn(
self.coin_list[coin_name]['wallet_address'], 'get_transfers', self.coin_list[coin_name]['type'], coin_name, payload=payload
)
if get_transfers and len(get_transfers) >= 1 and 'in' in get_transfers:
try:
await self.open_connection()
async with self.pool.acquire() as conn:
async with conn.cursor() as cur:
sql = """ SELECT * FROM `deposits` WHERE `coin_name`=%s """
await cur.execute(sql, (coin_name,))
result = await cur.fetchall()
d = [i['txid'] for i in result]
# print('=================='+coin_name+'===========')
# print(d)
# print('=================='+coin_name+'===========')
list_balance_user = {}
for tx in get_transfers['in']:
# add to balance only confirmation depth meet
if height >= int(tx['height']) + get_confirm_depth and tx['amount'] >= int(min_deposit * 10 ** coin_decimal) and 'payment_id' in tx:
if 'payment_id' in tx and tx['payment_id'] in list_balance_user:
list_balance_user[tx['payment_id']] += tx['amount']
elif 'payment_id' in tx and tx['payment_id'] not in list_balance_user:
list_balance_user[tx['payment_id']] = tx['amount']
try:
if tx['txid'] not in d:
user_paymentId = await self.get_userwallet_by_extra(
tx['payment_id'], coin_name,
self.coin_list[coin_name]['type']
)
app_id = None
if user_paymentId:
app_id = user_paymentId['api_id']
if app_id is None:
# Skipped for None
continue
sql = """
INSERT IGNORE INTO `deposits`
(`coin_name`, `api_id`, `depost_id`, `txid`, `blockhash`, `address`, `extra`, `height`, `amount`, `confirmations`, `time_insert`)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
"""
await cur.execute(sql, (
coin_name, app_id, user_paymentId['id'], tx['txid'], None, user_paymentId['address'], tx['payment_id'], tx['height'],
float(tx['amount'] / 10 ** coin_decimal), height - tx['height'], int(time.time())
))
await conn.commit()
try:
await log_to_discord(
"API: {} / ⏳ PENDING DEPOSIT {} {} to {}. Height: {}".format(app_id, float(tx['amount'] / 10 ** coin_decimal), coin_name, user_paymentId['address'], tx['height']),
config['log']['discord_webhook_default']
)
except Exception:
traceback.print_exc(file=sys.stdout)
except Exception:
traceback.print_exc(file=sys.stdout)
except Exception:
traceback.print_exc(file=sys.stdout)
if debug is True:
print_color(f"{datetime.now():%Y-%m-%d %H:%M:%S} End check balance {coin_name}", color="green")
return True
async def update_balance_btc(self, timer: float=10.0):
while True:
if len(config['coinapi']['list_btc']) > 0:
try:
tasks = []
for coin_name in config['coinapi']['list_btc']:
tasks.append(self.update_balance_tasks_btc(coin_name, False))
completed = 0
for task in asyncio.as_completed(tasks):
fetch_updates = await task
if fetch_updates is True:
completed += 1
except Exception:
traceback.print_exc(file=sys.stdout)
await asyncio.sleep(timer)
# to use with update_balance_btc()
async def update_balance_tasks_btc(self, coin_name: str, debug: bool):
if debug is True:
print_color(f"{datetime.now():%Y-%m-%d %H:%M:%S} Check balance {coin_name}", color="yellow")
url = self.coin_list[coin_name]['daemon_address']
method_info = "getblockchaininfo"
if runner.coin_list[coin_name]['use_getinfo_btc'] == 1:
method_info = "getinfo"
gettopblock = await call_doge(url, method_info, coin_name)
if gettopblock is None:
return False
height = int(gettopblock['blocks'])
try:
set_cache_kv(
self.app_main,
"block",
self.config['coinapi']['kv_prefix'] + coin_name,
height
)
await update_top_block(
coin_name, height
)
except Exception:
traceback.print_exc(file=sys.stdout)
await asyncio.sleep(1.0)
return False
get_confirm_depth = self.coin_list[coin_name]['confirmation_depth']
coin_decimal = self.coin_list[coin_name]['decimal']
min_deposit = self.coin_list[coin_name]['min_deposit']
payload = '"*", 100, 0'
get_transfers = await call_doge(url, 'listtransactions', coin_name, payload=payload)
if get_transfers and len(get_transfers) >= 1:
try:
await self.open_connection()
async with self.pool.acquire() as conn:
async with conn.cursor() as cur:
sql = """
SELECT * FROM `deposits`
WHERE `coin_name`=%s
"""
await cur.execute(sql, (coin_name))
result = await cur.fetchall()
d = ["{}_{}".format(i['txid'], i['address']) for i in result]
# print('=================='+coin_name+'===========')
# print(d)
# print('=================='+coin_name+'===========')
list_balance_user = {}
for tx in get_transfers:
# add to balance only confirmation depth meet
if get_confirm_depth <= int(tx['confirmations']) and tx['amount'] >= min_deposit:
if 'address' in tx and tx['address'] in list_balance_user and tx['amount'] > 0:
list_balance_user[tx['address']] += tx['amount']
elif 'address' in tx and tx['address'] not in list_balance_user and tx['amount'] > 0:
list_balance_user[tx['address']] = tx['amount']
try: