-
Notifications
You must be signed in to change notification settings - Fork 9
/
distribution.py
214 lines (177 loc) · 6.15 KB
/
distribution.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
"""
(c) 2017 Elias / Vanissoft
"""
from time import sleep
import datetime
import pickle
from bitsharesbase import (
transactions,
memo,
account,
operations,
objects
)
from config import Redisdb, Bitshares
Developing = True
def enqueue(dat, q):
q.empty()
if not Developing:
q.enqueue_call(func=do_distribution, args=[dat], timeout=0)
else:
do_distribution(dat)
def batch_enqueue(dat, q):
if not Developing:
q.enqueue_call(func=do_batch, args=[dat], timeout=0)
else:
do_batch(dat)
def endcheck_enqueue(q):
if not Developing:
q.enqueue_call(func=end_check, args=[], timeout=0)
else:
end_check()
def do_batch(dat):
"""
Make a batch of transfers
:param dat:
:return:
"""
import config
snap_info = pickle.loads(Redisdb.get("snapshot_info"))
try:
Bitshares = config.BitShares(node=config.WSS_NODE, wif=dat['form']['key'])
oaccount = Bitshares.wallet.getAccounts()[0]
except Exception as err:
print(err.__repr__())
Redisdb.rpush("messages", "*|launch_error|key not found")
print(0)
return False
for job in dat['job']:
try:
wif = dat['key']
pub = format(account.PrivateKey(wif).pubkey, config.PREFIX)
to_account_id = job[0].decode('utf8')
amount = 10
asset_id = dat['asset']['id']
message = "abcdefgABCDEFG0123456789"
nonce = "5862723643998573708"
fee = objects.Asset(amount=0, asset_id="1.3.0")
amount = objects.Asset(amount=int(amount), asset_id=asset_id)
encrypted_memo = memo.encode_memo(account.PrivateKey(wif), account.PublicKey(pub, prefix=config.PREFIX), nonce,
message)
memoStruct = {"from": pub, "to": pub, "nonce": nonce, "message": encrypted_memo, }
memoObj = objects.Memo(**memoStruct)
tmp = operations.Transfer(
**{"fee": fee, "from": dat['from'], "to": to_account_id, "amount": amount, "memo": memoObj,
"prefix": config.PREFIX})
print()
#test = Bitshares.transfer(job[0].decode('utf8'), float(job[1]), dat['asset'], "", dat['from'])
except Exception as err:
print(err.__repr__())
print(0)
Redisdb.decr("batch_jobs", int(1))
Redisdb.rpush("messages", datetime.datetime.now().isoformat() + " Jobs queue: {}".format(int(Redisdb.get("batch_jobs"))))
def end_check():
"""
Check for the finalization of snapshot tasks
:param dat:
:param q:
:return:
"""
while True:
print("snap_end", Redisdb.get("batch_jobs"))
if int(Redisdb.get("batch_jobs")) == 0:
# persist db to disk
Redisdb.rpush("operations", pickle.dumps({'operation': 'db_save'}))
Redisdb.rpush("messages", datetime.datetime.now().isoformat() + " Distribution end")
Redisdb.rpush("messages", "--------------")
break
sleep(2)
def distribution_setup():
"""
Makes a preview of the distribution
:return:
"""
snap_info = pickle.loads(Redisdb.get("snapshot_info"))
holders = Redisdb.hgetall("balance:"+snap_info['asset_hold_id'])
lst = []
cnt = 0
balance = 0
for h in holders:
hdata = pickle.loads(holders[h])
lst.append([hdata['account'], hdata['datetime'], hdata['amount'], 0])
balance += hdata['amount']
cnt += 1
if cnt % 1000 == 0:
Redisdb.rpush("messages", datetime.datetime.now().isoformat() + " CSV list "+str(cnt))
# refresh snapshot info
snap_info['total_balance'] = balance
snap_info['total_owners'] = int(Redisdb.get("total_owners:"+snap_info['asset_hold_id']))
Redisdb.set("snapshot_info", pickle.dumps(snap_info))
msg = "|".join([datetime.datetime.now().isoformat(), str(int(snap_info['total_balance'])), \
str(int(snap_info['total_owners'])), str(int(snap_info['total_owners']*snap_info['transfer_fee']))])
Redisdb.rpush("messages", "*|snapshot_end|" + msg)
# The list is sorted from more to less holding
Redisdb.rpush("messages", datetime.datetime.now().isoformat() + " CSV list sorting")
lst.sort(key=lambda x: x[2], reverse=True)
Redisdb.rpush("messages", datetime.datetime.now().isoformat() + " CSV list sorting OK")
# calculus of the distribution
tmplt_distr = "{0:."+str(snap_info['asset_distribute']['precision'])+"f}"
tmplt_hold = "{0:."+str(snap_info['asset_hold']['precision'])+"f}"
total_distr_amount = 0
for l in enumerate(lst):
if snap_info['distribution_amount'] > 0:
amount = round(l[1][2] / balance * snap_info['distribution_amount'], snap_info['asset_distribute']['precision'])
elif snap_info['distribution_ratio'] > 0:
amount = round(l[1][2] * snap_info['distribution_ratio'], snap_info['asset_distribute']['precision'])
if amount < snap_info['distribution_minimum']:
# truncate the list
lst = lst[:l[0]]
break
total_distr_amount += amount
lst[l[0]][3] = tmplt_distr.format(amount)
lst[l[0]][2] = tmplt_hold.format(l[1][2])
# feed the distribution container
for l in lst:
Redisdb.hset("distribute:" + snap_info['asset_hold_id'], l[0], l[3])
if snap_info['distribution_amount'] > 0:
rest = snap_info['distribution_amount'] - total_distr_amount
else:
rest = 0
# TODO: what to do with the rest?
return lst
def do_distribution(dat):
"""
Makes the actual transfer of tokens.
The snapshoting step have to be done before this.
:return:
"""
import config
try:
Bitshares = config.BitShares(node=config.WSS_NODE, wif=dat['form']['key'])
from_account_id = Bitshares.wallet.getAccounts()[0]['account'].identifier
except Exception as err:
print(err.__repr__())
Redisdb.rpush("messages", "*|launch_error|key not found")
print(0)
return False
snap_info = pickle.loads(Redisdb.get("snapshot_info"))
Redisdb.rpush("messages", "--------------")
Redisdb.rpush("messages", datetime.datetime.now().isoformat() + "Distribution started")
batch_count = 0
batch = []
lst = list(Redisdb.hgetall("distribute:"+snap_info['asset_hold_id']).items())
while True:
distr = lst.pop(0)
batch_count += 1
batch.append(distr)
if batch_count > 100 or len(lst) == 0:
op_dat = {'operation': 'distribution_batch', 'job': batch, 'key': dat['form']['key'],
'asset': snap_info['asset_distribute'], 'from': from_account_id}
Redisdb.rpush("operations", pickle.dumps(op_dat))
Redisdb.incr("batch_jobs", 1)
if len(lst) == 0:
break
Redisdb.rpush("messages", datetime.datetime.now().isoformat() + "Jobs generated")
Redisdb.rpush("operations", pickle.dumps({'operation': 'distribution_check'}))
if __name__ == "__main__":
print()