2
0

data.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. import json
  2. import os
  3. import time
  4. from tkinter import *
  5. import rpyc
  6. from create_keys import get_plain_key, get_private_key, make_keys
  7. from lib.block import CURRENT
  8. from lib.chain import Block, Chain
  9. from lib.transaction import Transaction
  10. from gui.encyption import decrypt_data
  11. # from gui.encyption import decrypt
  12. def new_contract():
  13. def add():
  14. name = str(title.get())
  15. if not os.path.isdir('contract_keys\\' + name):
  16. make_keys(name)
  17. pubkey = get_plain_key(name)
  18. # set discriptors of contract
  19. contract = {'id':pubkey,
  20. 'type':'init',
  21. 'date of initiation':time.time(),
  22. 'data': {'client':str(sender.get()),
  23. 'contractor':str(recipient.get()),
  24. 'discription':str(description.get()),
  25. 'name':name},
  26. 'terms' : {'deadline': int(deadline.get()),
  27. 'accepted': False,
  28. 'progress': '0%',
  29. 'price':int(price.get()),
  30. 'Sign time': 'not yet signed',
  31. 'comments':{}
  32. }
  33. }
  34. t = Transaction()
  35. t.set_contract(contract)
  36. t.hash(contract=name)
  37. temp = t.serialize(out_json=True)
  38. conn = rpyc.connect(host='localhost', port=42069, keepalive=True)
  39. conn.root.push_transaction(temp)
  40. conn.close()
  41. newWindow.destroy()
  42. else:
  43. print('Contract name already exists, choose another')
  44. newWindow.destroy()
  45. new_contract()
  46. newWindow = Tk()
  47. newWindow.title('Add contract')
  48. # create all text boxes
  49. Label(newWindow, text='Title: ').grid(row=0, column=0)
  50. title = Entry(newWindow, width=35, borderwidth=5)
  51. title.grid(row=0, column=1, columnspan=3, padx=10, pady=10)
  52. title.insert(0, 'test')
  53. Label(newWindow, text='Description: ').grid(row=1, column=0)
  54. description = Entry(newWindow, width=35, borderwidth=5)
  55. description.grid(row=1, column=1, columnspan=3, padx=10, pady=10)
  56. description.insert(0, 'test description')
  57. Label(newWindow, text='Deadline: ').grid(row=2, column=0)
  58. deadline = Entry(newWindow, width=35, borderwidth=5)
  59. deadline.grid(row=2, column=1, columnspan=3, padx=10, pady=10)
  60. deadline.insert(0, '1')
  61. Label(newWindow, text='Price: ').grid(row=3, column=0)
  62. price = Entry(newWindow, width=35, borderwidth=5)
  63. price.grid(row=3, column=1, columnspan=3, padx=10, pady=10)
  64. price.insert(0, '69420')
  65. Label(newWindow, text='Sender: ').grid(row=4, column=0)
  66. sender = Entry(newWindow, width=35, borderwidth=5)
  67. sender.grid(row=4, column=1, columnspan=3, padx=10, pady=10)
  68. sender.insert(0, 'justin')
  69. Label(newWindow, text='Recipient: ').grid(row=5, column=0)
  70. recipient = Entry(newWindow, width=35, borderwidth=5)
  71. recipient.grid(row=5, column=1, columnspan=3, padx=10, pady=10)
  72. recipient.insert(0, 'adam')
  73. # create the add contract button
  74. Button(newWindow, text = "Create contract", command=add).grid(row=6, column=1)
  75. def find_transaction():
  76. def find():
  77. conn = rpyc.connect(host='localhost', port=42069, keepalive=True)
  78. iden = get_plain_key(str(key.get()))
  79. transactions = conn.root.find_transactions(iden)
  80. transactions = decrypt_transactions(transactions, str(key.get()))
  81. print(current_contract_state(transactions, iden=iden))
  82. conn.close()
  83. newWindow.destroy()
  84. newWindow = Tk()
  85. newWindow.title('Add contract')
  86. Label(newWindow, text='Contract key: ').grid(row=0, column=0)
  87. key = Entry(newWindow, width=35, borderwidth=5)
  88. key.grid(row=0, column=1, columnspan=3, padx=10, pady=10)
  89. key.insert(0, 'test')
  90. Button(newWindow, text='find contracts', command=find).grid(row=1, column=1)
  91. def add_term():
  92. def add():
  93. conn = rpyc.connect(host='localhost', port=42069, keepalive=True)
  94. iden = get_plain_key(str(contract.get()))
  95. attr = str(change.get())
  96. value = str(values.get())
  97. comment = str(comments.get())
  98. transactions = conn.root.find_transactions(iden)
  99. transactions = decrypt_transactions(transactions, str(contract.get()))
  100. state = current_contract_state(transactions, iden)
  101. if attr in state['data'] or attr in state['terms']:
  102. t = 'modify'
  103. else: t = 'update'
  104. # add new or updated info to block
  105. update = {'id':iden,
  106. 'update id':len(get_updates(transactions, iden=iden)),
  107. 'updated':attr,
  108. 'type':t,
  109. 'last update':time.time(),
  110. 'accepted': False,
  111. 'change':{attr:value}}
  112. # check if comment is passed and add it if necassary
  113. if comment:
  114. update['comment'] = comment
  115. t = Transaction()
  116. t.set_contract(update)
  117. t.hash(contract=str(contract.get()))
  118. conn.root.push_transaction(t.serialize(out_json=True))
  119. #### TEST CODE PLEASE IGONRE ####
  120. # update = {
  121. # 'id':iden,
  122. # 'update id':0,
  123. # 'accept':True,
  124. # 'type':'accept',
  125. # 'last update':time.time()
  126. # }
  127. # if comment:
  128. # update['comment'] = comment
  129. # t = Transaction()
  130. # t.set_contract(update)
  131. # t.hash(contract=str(contract.get()))
  132. # conn.root.push_transaction(t.serialize(out_json=True))
  133. #### END TEST CODE PLEASE DONT IGONRE ####
  134. conn.close()
  135. newWindow.destroy()
  136. newWindow = Tk()
  137. newWindow.title('Add contract')
  138. # create all text boxes
  139. Label(newWindow, text='Contract: ').grid(row=0, column=0)
  140. contract = Entry(newWindow, width=35, borderwidth=5)
  141. contract.grid(row=0, column=1, columnspan=3, padx=10, pady=10)
  142. contract.insert(0, 'test')
  143. Label(newWindow, text='What to change or add: ').grid(row=1, column=0)
  144. change = Entry(newWindow, width=35, borderwidth=5)
  145. change.grid(row=1, column=1, columnspan=3, padx=10, pady=10)
  146. change.insert(0, 'progress')
  147. Label(newWindow, text='New value: ').grid(row=2, column=0)
  148. values = Entry(newWindow, width=35, borderwidth=5)
  149. values.grid(row=2, column=1, columnspan=3, padx=10, pady=10)
  150. values.insert(0, '50%')
  151. Label(newWindow, text='comment (optional): ').grid(row=3, column=0)
  152. comments = Entry(newWindow, width=35, borderwidth=5)
  153. comments.grid(row=3, column=1, columnspan=3, padx=10, pady=10)
  154. comments.insert(0, 'dit is een comment')
  155. Button(newWindow, text='Add term', command=add).grid(row=4, column=1)
  156. def accept_updates():
  157. def show():
  158. conn = rpyc.connect(host='localhost', port=42069, keepalive=True)
  159. name = str(contract.get())
  160. transactions = conn.root.find_transactions(get_plain_key(name))
  161. transactions = decrypt_transactions(transactions, name)
  162. updates = retrieve_updates(transactions, name, accepted=False)
  163. conn.close()
  164. if len(updates) == 0:
  165. print('No updates to accept')
  166. else:
  167. print('Updates that still need to be accepted: \n')
  168. for update in updates:
  169. print(update, '\n')
  170. def accept():
  171. conn = rpyc.connect(host='localhost', port=42069, keepalive=True)
  172. name = str(contract.get())
  173. update_id = int(change.get())
  174. answer = accept_status.get()
  175. if answer == 'True':
  176. answer = True
  177. else: answer = False
  178. print(answer)
  179. comment_text = str(comment.get())
  180. print(answer)
  181. update = {
  182. 'id':get_plain_key(name),
  183. 'update id':update_id,
  184. 'accept':answer,
  185. 'type':'accept',
  186. 'last update':time.time()
  187. }
  188. if comment_text:
  189. update['comment'] = comment_text
  190. t = Transaction()
  191. t.set_contract(update)
  192. t.hash(contract=str(contract.get()))
  193. conn.root.push_transaction(t.serialize(out_json=True))
  194. conn.close()
  195. newWindow.destroy()
  196. newWindow = Tk()
  197. newWindow.title('Accept updates')
  198. Label(newWindow, text='Contract: ').grid(row=0, column=0)
  199. contract = Entry(newWindow, width=35, borderwidth=5)
  200. contract.grid(row=0, column=1, columnspan=3, padx=10, pady=10)
  201. contract.insert(0, 'test')
  202. Label(newWindow, text='Id of update: ').grid(row=1, column=0)
  203. change = Entry(newWindow, width=35, borderwidth=5)
  204. change.grid(row=1, column=1, columnspan=3, padx=10, pady=10)
  205. change.insert(0, '0')
  206. Label(newWindow, text='Awnser: ').grid(row=2, column=0)
  207. accept_status = StringVar(newWindow)
  208. accept_status.set('False') # default value
  209. OptionMenu(newWindow, accept_status, 'False', 'True').grid(row=2, column=1)
  210. Label(newWindow, text='Comment (optional): ').grid(row=3, column=0)
  211. comment = Entry(newWindow, width=35, borderwidth=5)
  212. comment.grid(row=3, column=1, columnspan=3, padx=10, pady=10)
  213. comment.insert(0, 'test test')
  214. Button(newWindow, text='Show updates to accept', command=show).grid(row=4, column=0, padx=10, pady=5)
  215. Button(newWindow, text='Accept', command=accept).grid(row=4, column=1, padx=10, pady=5)
  216. def current_contract_state(transactions, iden):
  217. # set up contract state
  218. state = {'id':iden,
  219. 'data':{},
  220. 'terms':{}
  221. }
  222. # save not yet approved updates
  223. updates = {}
  224. # loop over all transaction in block
  225. for item in transactions:
  226. # save data about our project
  227. if item['id'] == iden:
  228. # set state to inital contract state
  229. if item['type'] == 'init':
  230. state = item
  231. continue
  232. # if update is not accept update, save it to updates dict
  233. if item['type'] != 'accept':
  234. # comments are always accepted
  235. if item['updated'] != 'comments':
  236. updates[item['update id']] = item
  237. continue
  238. # if accepted is true, retrieve update form dict and add to contract state
  239. elif item['accept'] == True:
  240. item = updates[item['update id']]
  241. # set attr to whatever has been updated
  242. print(item)
  243. attr = item['updated']
  244. # check if the update was removal
  245. if item['type'] == 'remove':
  246. # delete item in the right part of the dict
  247. try:
  248. if attr in state['data']:
  249. del state['data'][attr]
  250. else:
  251. del state['terms'][attr]
  252. except:
  253. pass
  254. if item['type'] == 'update':
  255. state['terms'][attr] = item['change'][attr]
  256. # check if updated attr is data or terms
  257. elif attr in state['data']:
  258. state['data'][attr] = item['change'][attr]
  259. elif attr in state['terms']:
  260. # special case for comments
  261. if attr == 'comments' and item['type'] not in ['remove', 'init']:
  262. k = list(item['change'][attr].keys())[0]
  263. state['terms'][attr][k] = item['change'][attr][k]
  264. # case for normal updates
  265. else:
  266. state['terms'][attr] = item['change'][attr]
  267. # special cases for last update and date of initiation
  268. elif 'last update' in item:
  269. state['last update'] = item['last update']
  270. return state
  271. def get_updates(transactions, iden=None, attr=None, accepted=None):
  272. updates = []
  273. # get all blocks and loop over transactions
  274. for item in transactions:
  275. # if attr is '' get updates for all attributes
  276. if attr == None:
  277. # if iden is None, get updates for all contracts
  278. # updates for all contracts and attrs
  279. if iden == None:
  280. if item['type'] != 'init':
  281. updates.append(item)
  282. # updates for specific contracts from all attr
  283. else:
  284. if item['type'] != 'init' and item['id'] == iden:
  285. updates.append(item)
  286. else:
  287. # updates for specific attrs from all contract
  288. if iden == None:
  289. if item['type'] != 'init' and item['updated'] == attr:
  290. updates.append(item)
  291. # updates for specific contract and specific attr
  292. else:
  293. if item['type'] != 'init' and item['updated'] == attr and item['id'] == iden:
  294. updates.append(item)
  295. return updates
  296. def retrieve_updates(all_updates, iden, accepted=None):
  297. updates = {}
  298. for item in all_updates:
  299. print(item)
  300. if item['type'] == 'init':
  301. continue
  302. if item['type'] != 'accept' and item['updated'] != 'comments':
  303. updates[item['update id']] = item
  304. else:
  305. try:
  306. updates[item['update id']]['accepted'] = item['accept']
  307. except:
  308. pass
  309. if accepted == None:
  310. return updates
  311. return [updates[x] for x in list(updates.keys()) if updates[x]['accepted'] == accepted]
  312. def decrypt_transactions(transactions, name):
  313. return [json.loads(decrypt_data(name, x)) for x in transactions]