Advertisement
arfin97

Untitled

Feb 15th, 2019
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.62 KB | None | 0 0
  1. import json
  2. from django.shortcuts import render, HttpResponse
  3.  
  4. # Create your views here.
  5. from django.http import Http404
  6. from rest_framework.views import APIView
  7. from rest_framework.response import Response
  8. from rest_framework import status
  9.  
  10. import hashlib
  11. import os
  12.  
  13. # import sys
  14. # sys.path.append("..")
  15.  
  16.  
  17. class BlockChain:
  18. previousHash = None
  19. pres = []
  20. vp = []
  21. sec = []
  22. pres_nom = []
  23. vp_nom = []
  24. sec_nom = []
  25. pres_final_cnt = []
  26. vp_final_cnt = []
  27. sec_final_cnt = []
  28.  
  29. # def __init__(self):
  30. # self.previousHash = None
  31. # self.pres = []
  32. # self.vp = []
  33. # self.sec = []
  34. # self.pres_nom = []
  35. # self.vp_nom = []
  36. # self.sec_nom = []
  37. # self.pres_final_cnt = []
  38. # self.vp_final_cnt = []
  39. # self.sec_final_cnt = []
  40.  
  41. def hash_block(self, electionID, voterID, block_type, data):
  42. """
  43. Send the data received from the post request into this function to generate a JSON file
  44. which will be saved to a file. This function will perform the hashing required for block chain.
  45. """
  46. vote_data = {
  47. "elec_id": electionID,
  48. "voter_id": voterID,
  49. "block_type": block_type,
  50. block_type + "_data": data,
  51. "prev_hash": self.previousHash
  52. }
  53.  
  54. vote_serialized = json.dumps(vote_data).encode('utf-8')
  55. vote_hashed = hashlib.sha256(vote_serialized).hexdigest()
  56. if vote_hashed == None:
  57. print('VALUE IS NULL!!!!')
  58. self.previousHash = vote_hashed
  59. return vote_serialized
  60.  
  61. def add_vote_block(self, elec_id, voter_id, vote_data):
  62. file_name = elec_id + '.json'
  63.  
  64. if os.path.exists(file_name):
  65. print("yes")
  66. else:
  67. f = open(file_name, 'w+')
  68. f.write('[]')
  69. f.close()
  70.  
  71. hash_data = self.hash_block(elec_id, voter_id, "vote", vote_data).decode("utf-8")
  72. hash_data_json = json.loads(hash_data)
  73.  
  74. file = open(file_name, 'r')
  75. file_data = file.read()
  76. file_data_json = json.loads(file_data)
  77. file.close()
  78.  
  79. data = file_data_json + [hash_data_json]
  80. file = open(file_name, 'w')
  81. file.write(json.dumps(data))
  82. file.close()
  83.  
  84. file = open(file_name, 'r')
  85. new_file_data = file.read()
  86. new_file_data_json = json.loads(new_file_data)
  87. file.close()
  88. # print(new_file_data_json)
  89.  
  90. for i in range(0, len(new_file_data_json)):
  91. tmp = new_file_data_json[i]['vote_data']
  92. n = len(tmp)
  93.  
  94. for j in range(0, n):
  95. print(tmp[j])
  96.  
  97. # print(" he ")
  98. temp = tmp[j][1]
  99.  
  100. print("voted ", tmp[j][0], type(tmp[j][0]))
  101.  
  102. if tmp[j][0] == "-1":
  103. continue
  104.  
  105. if temp == "pres":
  106. self.pres.append(tmp[j][0])
  107.  
  108. elif temp == "vice":
  109. self.vp.append(tmp[j][0])
  110.  
  111. elif temp == "sec":
  112. self.sec.append(tmp[j][0])
  113.  
  114. print("\n")
  115. print(self.pres, self.vp, self.sec)
  116. print("\n")
  117.  
  118. pres_cnt = []
  119. vp_cnt = []
  120. sec_cnt = []
  121.  
  122. myset = set(self.pres)
  123. print(myset)
  124. for i in myset:
  125. # print('i = ', i)
  126. val = self.pres.count(i)
  127. pres_cnt.append(tuple((i, val)))
  128.  
  129. print("pres-cnt = ", pres_cnt)
  130.  
  131. myset = set(self.vp)
  132. for i in myset:
  133. val = self.vp.count(i)
  134. vp_cnt.append(tuple((i, val)))
  135.  
  136. print("vp-cnt = ", vp_cnt)
  137.  
  138. myset = set(self.sec)
  139. for i in myset:
  140. val = self.sec.count(i)
  141. sec_cnt.append(tuple((i, val)))
  142.  
  143. print("sec-cnt = ", sec_cnt)
  144.  
  145. pres_final_cnt = pres_cnt
  146. vp_final_cnt = vp_cnt
  147. sec_final_cnt = sec_cnt
  148.  
  149. return True
  150.  
  151. file_name = elec_id + 'nom.json'
  152.  
  153. if os.path.exists('voting/' + file_name):
  154. print("yes")
  155. else:
  156. f = open('voting/' + str(file_name), 'w+')
  157. f.write('[]')
  158. f.close()
  159.  
  160. hash_data = self.hash_block(elec_id, voter_id, "nom", nom_data).decode("utf-8")
  161. hash_data_json = json.loads(hash_data)
  162.  
  163. file = open('voting/' + str(file_name), 'r')
  164. file_data = file.read()
  165. file_data_json = json.loads(file_data)
  166. file.close()
  167.  
  168. data = file_data_json + [hash_data_json]
  169. file = open('voting/' + file_name, 'w')
  170. file.write(json.dumps(data))
  171. file.close()
  172.  
  173. file = open('voting/' + file_name, 'r')
  174. new_file_data = file.read()
  175. new_file_data_json = json.loads(new_file_data)
  176. file.close()
  177.  
  178.  
  179.  
  180. print(new_file_data_json)
  181.  
  182. print(" new_file_data_json length = ",len(new_file_data_json))
  183.  
  184. for i in range(0, len(new_file_data_json)):
  185. tmp = new_file_data_json[i]['nom_data']
  186. print("ZZZZZZZZZZZZZZZZZZZZZZZZZZ")
  187. for j in range(0, len(tmp)):
  188. temp = tmp[j][1]
  189.  
  190. print("hello ", i, j)
  191.  
  192. print(temp)
  193.  
  194. print(tmp[j][0])
  195.  
  196. print(self.pres_nom, self.vp_nom, self.sec_nom)
  197.  
  198.  
  199.  
  200. if tmp[j][0] == "-1":
  201. print("hello 111111111111111111", i, j)
  202. continue
  203.  
  204. if temp == "pre" and tmp[j][0] not in self.pres_nom:
  205. self.pres_nom.append(tmp[j][0])
  206.  
  207. print("=====================", j, self.pres_nom )
  208.  
  209. elif temp == "vice" and tmp[j][0] not in self.vp_nom:
  210. self.vp_nom.append(tmp[j][0])
  211.  
  212. print("!!!!!!!!!!!!!!",j, self.vp_nom )
  213.  
  214. elif temp == "sec" and tmp[j][0] not in self.sec_nom:
  215. self.sec_nom.append(tmp[j][0])
  216.  
  217. print("+++++++++++++++++++===", j, self.sec_nom )
  218.  
  219. print("\n")
  220. print(self.pres_nom, self.vp_nom, self.sec_nom)
  221.  
  222. return True
  223. def add_nom_block(self, elec_id, voter_id, nom_data):
  224.  
  225.  
  226. blockchain = BlockChain()
  227.  
  228.  
  229. def check_nominee(inputList, elec_id, voter_id):
  230. # print(len(inputList))
  231. print("-" * 30)
  232. missing = True
  233. for record in inputList:
  234. # print(record)
  235. if record["elec_id"] != elec_id:
  236. continue
  237. elif record["voter_id"] != voter_id:
  238. continue
  239. else:
  240. missing = False
  241. break
  242. return missing
  243.  
  244.  
  245. def check_voter(inputList, inputRecord):
  246. missing = True
  247. for record in inputList:
  248. if record["elec_id"] != inputRecord["elec_id"]:
  249. continue
  250. elif record["voter_id"] != inputRecord["voter_id"]:
  251. continue
  252. else:
  253. missing = False
  254. break
  255. return missing
  256.  
  257.  
  258. class CheckNom(APIView):
  259. """
  260. List all snippets, or create a new snippet.
  261. """
  262.  
  263. def get(self, request, election_id, voter_id, format=None):
  264. input_data = request.data
  265.  
  266. file_name = '' + election_id + 'nom.json'
  267.  
  268. if os.path.exists('voting/' + file_name):
  269. with open('voting/' + file_name, 'r') as f:
  270. print('voting/' + file_name)
  271. txt_data = json.load(f)
  272.  
  273. check = check_nominee(txt_data, election_id, voter_id)
  274. return Response({'success': check})
  275. else:
  276. f = open('voting/' + file_name, 'w+')
  277. f.write('[]')
  278. # txt_data = json.load(f)
  279. # check = check_nominee(txt_data,election_id,voter_id)
  280. return Response({'success': True})
  281.  
  282. def post(self, request, election_id, voter_id, format=None):
  283. # nom_data = request.data
  284. if request.POST:
  285. myDict = dict(request.data)
  286. # print("1----------------")
  287. # print(type(request))
  288. # print(request.data)
  289. # print("2----------------")
  290. # print(type(myDict))
  291. # print("3----------------")
  292. # for key, value in myDict.items() :
  293. # print('Key: ', key)
  294. # print('Value: ', value)
  295. # print("4-------------------------------------")
  296. # print(type(list(next(iter(myDict.keys())))))
  297. got_list = json.loads(next(iter(myDict.keys())))
  298. # print(len(got_list))
  299. # print(got_list[0])
  300. # print(type(got_list))
  301. # print("5-------------------------------------")
  302. elect = dict(got_list[0])
  303. voter = dict(got_list[1])
  304. nom1 = dict(got_list[2])
  305. nom2 = dict(got_list[3])
  306. nom3 = dict(got_list[4])
  307.  
  308. elec_id = elect["value"]
  309. voter_id = voter["value"]
  310. nom_data1 = [nom1["value"], nom1["name"]]
  311. nom_data2 = [nom2["value"], nom2["name"]]
  312. nom_data3 = [nom3["value"], nom3["name"]]
  313. nom_data_full = [nom_data1, nom_data2, nom_data3]
  314.  
  315. # print(elec_id)
  316. # print(voter_id)
  317. # print(nom_data_full)
  318.  
  319. blockchain.add_nom_block(elec_id, voter_id, nom_data_full)
  320. # i = 0
  321. # for elem in got_list:
  322. # print(i,elem)
  323. # ddccii = dict(elem)
  324. # print(i,dict(elem))
  325. # print(ddccii['name'])
  326. # #----------------------------- elec_id, voter_id, nom_data
  327. # elec_id =
  328.  
  329. # i = i + 1
  330. # print("END-------------------------------------")
  331.  
  332. # add_nom_block(election_id,voter_id,nom_data)
  333. return Response({'success': True})
  334.  
  335.  
  336. def json_check(request):
  337. with open('voting/data.json', 'r') as f:
  338. data = json.load(f)
  339. print(data)
  340. return HttpResponse("Checked")
  341. # To send nominee result after voting
  342.  
  343.  
  344. class GetNomResult(APIView):
  345. def get(self, request, format=None):
  346. print(blockchain.pres_nom)
  347. return Response({'pres': blockchain.pres_nom, 'vp': blockchain.vp_nom, 'sec': blockchain.sec_nom})
  348.  
  349.  
  350. # To send voter results after voting
  351. class GetVoterResult(APIView):
  352. def get(self, request, format=None):
  353. # from golbal variable send data as JSON
  354. return Response({'pres_final_cnt': pres_final_cnt, 'vp_final_cnt': vp_final_cnt, 'sec_final_cnt': sec_final_cnt})
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement