data.py 13 KB

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