forked from krruzic/trtlbotplusplus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
168 lines (138 loc) · 5.59 KB
/
utils.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
import random
import sys
import binascii
import json
from collections import deque
from jsonrpc_requests import Server
from models import Transaction, TipJar
config = json.load(open('config.json'))
ADDRS = []
class TrtlServer(Server):
def dumps(self, data):
data['password'] = config['rpc_password']
return json.dumps(data)
rpc = TrtlServer("http://{}:{}/json_rpc".format(config['rpc_host'], config['rpc_port']))
daemon = TrtlServer("http://{}:{}/json_rpc".format(config['daemon_host'], config['daemon_port']))
CONFIRMED_TXS = []
def get_supply():
try:
lastblock = daemon.getlastblockheader()
bo = daemon.f_block_json(hash=lastblock["block_header"]["hash"])
except:
return 0.00
return float(bo["block"]["alreadyGeneratedCoins"])/100
def format_hash(hashrate):
i = 0
byteUnits = [" H", " KH", " MH", " GH", " TH", " PH"]
while (hashrate > 1000):
hashrate = hashrate / 1000
i = i+1
return "{0:,.2f} {1}".format(hashrate, byteUnits[i])
def gen_paymentid(address):
rng = random.Random(address+config['token'])
length = 32
chunk_size = 65535
chunks = []
while length >= chunk_size:
chunks.append(rng.getrandbits(chunk_size * 8).to_bytes(chunk_size, sys.byteorder))
length -= chunk_size
if length:
chunks.append(rng.getrandbits(length * 8).to_bytes(length, sys.byteorder))
result = b''.join(chunks)
return "".join(map(chr, binascii.hexlify(result)))
def get_deposits(starting_height, session):
global ADDRS
print("scanning deposits at block: ", starting_height)
try:
ADDRS = rpc.getAddresses()['addresses']
transactionData = rpc.getTransactions(firstBlockIndex=starting_height, blockCount=1000)
except:
return
for item in transactionData['items']:
for tx in item['transactions']:
if tx['paymentId'] == '':
continue
if tx['transactionHash'] in CONFIRMED_TXS:
continue
if tx['unlockTime'] <= 3:
CONFIRMED_TXS.append({'transactionHash': tx['transactionHash'],'ready':True, 'pid': tx['paymentId']})
elif tx['unlockTime'] > 3:
CONFIRMED_TXS.append({'transactionHash': tx['transactionHash'],'ready':False, 'pid': tx['paymentId']})
for i,trs in enumerate(CONFIRMED_TXS):
processed = session.query(Transaction).filter(Transaction.tx == trs['transactionHash']).first()
amount = 0
print("Looking at tx: " + trs['transactionHash'])
if processed:
print("already processed: " + trs['transactionHash'])
CONFIRMED_TXS.pop(i)
continue
try:
data = rpc.getTransaction(transactionHash=trs['transactionHash'])
except:
print("RPC failed to return data for valid hash: " + trs['transactionHash'])
continue
if not trs['ready']:
if data['unlockTime'] != 0:
continue
else:
trs['ready'] = True
likestring = data['transaction']['paymentId'][0:58]
balance = session.query(TipJar).filter(TipJar.paymentid.contains(likestring)).first()
print("Balance for pid {} is: {}".format(likestring,balance))
if not balance:
print("user does not exist!")
continue
og_balance = balance.amount
for transfer in data['transaction']['transfers']:
print("updating user balance!")
address = transfer['address']
amount = transfer['amount']
change = 0
if address in ADDRS:
if trs['pid']==balance.paymentid: # money entering tipjar, add to user balance
print("deposit of {}".format(amount))
print("Depositing to: {}".format(balance.paymentid))
change += amount
elif address != "" and trs['pid'] == (balance.paymentid[0:58] + balance.withdraw): # money leaving tipjar, remove from user's balance
print("withdrawal of {}".format(amount))
change -= (amount+data['transaction']['fee'])
try:
balance.amount += change
except:
print("no balance, setting balance to: {}".format(change))
balance.amount = change
print("new balance: {}".format(balance.amount))
session.commit()
if balance:
nt = Transaction(trs['transactionHash'], balance.amount-og_balance, trs['pid'])
CONFIRMED_TXS.pop(i)
yield nt
def get_fee(amount):
return 10
def build_transfer(amount, transfers, balance):
global ADDRS
print("SEND PID: {}".format(balance.paymentid[0:58] + balance.withdraw))
params = {
'addresses': [ADDRS[0]],
'fee': get_fee(amount),
'paymentId': balance.paymentid[0:58] + balance.withdraw,
'anonymity': 3,
'transfers': transfers
}
return params
REACTION_AMP_CACHE = deque([], 500)
def reaction_tip_lookup(message):
for x in REACTION_AMP_CACHE:
if x['msg'] == message:
return x
def reaction_tip_register(message, user):
msg = reaction_tip_lookup(message)
if not msg:
msg = {'msg': message, 'tips': []}
REACTION_AMP_CACHE.append(msg)
msg['tips'].append(user)
return msg
def reaction_tipped_already(message, user):
msg = reaction_tip_lookup(message)
if msg:
return user in msg['tips']