-
Notifications
You must be signed in to change notification settings - Fork 0
/
vote.py
405 lines (281 loc) · 12.2 KB
/
vote.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
#####
# Part of `SmartCashVoting`
#
#
# Copyright 2018 dustinface
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#####
import os, sys
import time
import json
import threading
import getpass
import requests
from smartcash.rpc import SmartCashRPC
if sys.version_info < (3, 0):
input = raw_input
URL_SMARTCASH = 'https://vote.smartcash.cc/api/v1'
API_PROPOSAL_LIST = '/voteproposals'
API_CAST_VOTE = '/voteproposals/castvote'
STATE_COLLECT = 0
STATE_WALLETLOCK = 1
STATE_LOAD_PROPOSALS = 2
STATE_ASK_PROPOSAL = 3
STATE_ASK_VOTE_TYPE = 4
STATE_CAST_VOTES = 5
STATE_DONE = 6
STATE_CANCELED = 7
def clear():
print("\033[H\033[J")
def error(msg):
print("\n[ERROR] {}\n".format(msg))
def exit(msg = ''):
return input("{}\n[ENTER to continue{}]: ".format(msg, ' / X + ENTER to Exit' if exit else '')).upper().find('X') != -1
class SmartCashVoting(object):
def __init__(self, rpcConfig):
self.rpc = SmartCashRPC(rpcConfig)
self.state = STATE_COLLECT
self.password = None
self.unlockedBefore = False
self.addresses = None
self.proposals = None
self.activeProposal = None
self.success = 0
self.failed = 0
def unlock(self, password):
unlock = self.rpc.unlockWallet(password)
if unlock.error:
clear()
error("Could not unlock wallet: {}".format(unlock.error.message))
return False
else:
self.password = password
self.unlockedBefore = False
return True
def collectAddresses(self):
self.addresses = {}
print("\n** Collect addresses **")
addressGroupings = self.rpc.getAddressGroupings()
if addressGroupings.error:
error("Could not fetch addresses: {}".format(str(addressGroupings.error)))
print("Please verify that your wallet is running and the rpc server is enabled.")
print("Look here: https://github.com/xdustinface/SmartCashVoting#configuration-of-your-wallet")
return False
for addressGroup in addressGroupings.data:
for address in addressGroup:
if float(address[1]) > 0:
self.addresses[address[0]] = address[1]
self.timeout = len(self.addresses) * 30
if not len(self.addresses):
error("No address with voting power detected!")
return False
print(" => {} addresses with overall {} SMART detected.\n".format(len(self.addresses), sum(self.addresses.values())))
return True
def checkWalletLock(self):
print("\n** Check if the wallet is unlocked already **")
# First check if the wallet is locked or not.
unlockCheck = self.rpc.signMessage(list(self.addresses.keys())[0], "LOCKED?")
if unlockCheck.error:
print(" => Its locked!\n")
print("To sign the voting messagges your wallet needs to be unlocked.")
print("Once the voting is done your wallet will become locked again!!\n")
print(("If you feel more comforable by unlocking inside of your wallet "
"you can also cancel this script, run:\n\n"
" walletpassphrase \"yourpassword\" 1000\n\nfrom the wallet's debug console"
"and come back afterwards. If you manually unlock"
" your wallet this script also wont't trigger the lock at the end.\n"))
password = getpass.getpass("Enter your wallet password: ")
if not password:
clear()
error("Could not unlock wallet: Make sure you entered a password!")
return False
return self.unlock(password)
else:
self.unlockedBefore = True
print(" => Its unlocked!\n")
return True
def loadProposals(self):
print("\n** Loading open proposals from the portal **")
self.proposals = None
try:
response = requests.get(URL_SMARTCASH + API_PROPOSAL_LIST)
except Exception as e:
error("Exception while loading the proposals: {}".format(str(e)))
else:
if response.status_code != 200:
error("Could not fetch proposals from the portal: {} - {}".format(response.status_code, response.reason))
else:
try:
parsed = json.loads(response.text)
if 'status' in parsed and parsed['status'] == 'OK'\
and 'result' in parsed:
if not len(parsed['result']):
error("Looks like there are currently no proposals opened for vote?!")
else:
self.proposals = parsed['result']
else:
error("Invalid response from the voting portal.")
except Exception as e:
error("Exception while loading the proposals from the portal: {}".format(str(e)))
if not self.proposals:
return False
return True
def askProposal(self):
clear()
print("** Select the proposal you want to vote **\n")
self.activeProposal = None
numError = "Your input needs no be a number from 1 to {}".format(len(self.proposals))
idx = 0
for proposal in self.proposals:
idx += 1
print("\n[{}] {}".format(idx, proposal['title'].encode('utf-8')))
print(" Requested - {} USD | {} SMART".format(proposal['amountUSD'],proposal['amountSmart']))
print(" Votes - Yes {:.2f}% | No {:.2f}% | Abstain {:.2f}%".format(proposal['percentYes'],proposal['percentNo'], proposal['percentAbstain']))
print(" Ends at - {}".format(proposal['votingDeadline']))
idx = input("\nSelect any number from 1 to {}: ".format(len(self.proposals)))
try:
idx = int(idx) - 1
except:
error(numError)
return False
else:
if idx < 0 or idx > len(self.proposals) - 1:
error(numError)
return False
else:
self.activeProposal = self.proposals[idx]
return True
def askVoteType(self):
clear()
print("** How do you want to vote the proposal? **\n")
self.voteType = None
ret = {'voteType' : None, 'result' : False }
print("Selected proposal: {}\n".format(self.activeProposal['title'].encode('utf-8')))
voteType = input(("How do you want to vote?\n\n"
"[y] - YES\n"
"[a] - ABSTAIN\n"
"[n] - NO\n\n"
"Type y/a/n and hit enter: "))
if voteType.upper() == 'Y':
self.voteType = 'YES'
elif voteType.upper() == 'A':
self.voteType = 'Abstain'
elif voteType.upper() == 'N':
self.voteType = 'NO'
else:
error("You need to select one of the following: \n\n"
"y - to vote YES\n"
"a - to vote ABSTAIN\n"
"n - to vote NO")
return False
return True
def castVotes(self):
clear()
print("** Start voting {} for - {}**\n".format(self.voteType, self.activeProposal['title'].encode('utf-8')))
self.success = 0
self.failed = 0
proposalId = self.activeProposal['proposalId']
proposalUrl = self.activeProposal['url']
# If the wallet was unlocked before entering the
# script leave it...
if not self.unlockedBefore:
self.rpc.unlockWallet(self.password)
for address, power in self.addresses.items():
signed = self.rpc.signMessage(address, proposalUrl)
if signed.error:
error("Could not sign message: {}".format(signed.error))
return False
postData = {
'proposalId': proposalId,
'smartAddress': address,
'signature': signed.data,
'url' : proposalUrl,
'voteType' : self.voteType
}
response = requests.post(URL_SMARTCASH + API_CAST_VOTE, data=postData )
if response.status_code == 200:
self.success += power
result = "PASSED"
message = "Voted with {} - Power {} SMART".format(address, power)
else:
self.failed += power
result = "FAILED"
message = "Could not vote with {} - {}:{}".format(address,response.status_code,response.reason)
print("[{}] - {}".format(result, message))
# If the wallet was unlocked before entering the
# script leave it...
if not self.unlockedBefore:
self.rpc.lockWallet()
if self.success:
print("\nVoted with {} SMART!".format(self.success))
if self.failed:
print("\nVotes with {} SMART failed. Try it again!".format(self.failed))
return True
def run(self):
while self.state < STATE_DONE:
if self.state == STATE_COLLECT:
if self.collectAddresses():
self.state = STATE_WALLETLOCK
else:
self.state = STATE_CANCELED
elif self.state == STATE_WALLETLOCK:
if self.checkWalletLock():
self.state = STATE_LOAD_PROPOSALS
else:
if exit():
self.state = STATE_CANCELED
else:
clear()
continue
elif self.state == STATE_LOAD_PROPOSALS:
if self.loadProposals():
self.state = STATE_ASK_PROPOSAL
else:
if exit("Do you want to try it again?"):
self.state = STATE_CANCELED
else:
clear()
elif self.state == STATE_ASK_PROPOSAL:
if self.askProposal():
self.state = STATE_ASK_VOTE_TYPE
else:
if exit():
self.state = STATE_CANCELED
elif self.state == STATE_ASK_VOTE_TYPE:
if self.askVoteType():
self.state = STATE_CAST_VOTES
else:
if exit():
self.state = STATE_CANCELED
elif self.state == STATE_CAST_VOTES:
if self.castVotes():
if exit("\nDo you want to vote again?\n"):
# If the wallet was unlocked before entering the
# script leave it up to the user to lock it again.
if not self.unlockedBefore:
self.rpc.lockWallet()
self.state = STATE_DONE
else:
# Jump back and load the proposals again
self.state = STATE_LOAD_PROPOSALS
else:
error("Something went wrong during the voting process.")
self.state = STATE_CANCELED
return self.state == STATE_DONE