data.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. from tkinter import *
  2. from lib.chain import Chain, Block
  3. from lib.transaction import Transaction
  4. from lib.block import CURRENT
  5. import rpyc
  6. import time
  7. import json
  8. from create_keys import make_keys, get_private_key, get_plain_key
  9. import os
  10. from cryptography.hazmat.primitives import hashes
  11. from cryptography.hazmat.primitives.asymmetric import padding
  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. conn = rpyc.connect(host='localhost', port=42069, keepalive=True)
  35. t = Transaction()
  36. t.set_contract(contract)
  37. t.hash(contract=name)
  38. conn.root.push_transaction(t.serialize(out_json=True))
  39. conn.close()
  40. newWindow.destroy()
  41. else:
  42. print('Contract name already exists, choose another')
  43. newWindow.destroy()
  44. new_contract()
  45. newWindow = Tk()
  46. newWindow.title('Add contract')
  47. # create all text boxes
  48. Label(newWindow, text='Title: ').grid(row=0, column=0)
  49. title = Entry(newWindow, width=35, borderwidth=5)
  50. title.grid(row=0, column=1, columnspan=3, padx=10, pady=10)
  51. title.insert(0, 'test')
  52. Label(newWindow, text='Description: ').grid(row=1, column=0)
  53. description = Entry(newWindow, width=35, borderwidth=5)
  54. description.grid(row=1, column=1, columnspan=3, padx=10, pady=10)
  55. description.insert(0, 'test description')
  56. Label(newWindow, text='Deadline: ').grid(row=2, column=0)
  57. deadline = Entry(newWindow, width=35, borderwidth=5)
  58. deadline.grid(row=2, column=1, columnspan=3, padx=10, pady=10)
  59. deadline.insert(0, '1')
  60. Label(newWindow, text='Price: ').grid(row=3, column=0)
  61. price = Entry(newWindow, width=35, borderwidth=5)
  62. price.grid(row=3, column=1, columnspan=3, padx=10, pady=10)
  63. price.insert(0, '69420')
  64. Label(newWindow, text='Sender: ').grid(row=4, column=0)
  65. sender = Entry(newWindow, width=35, borderwidth=5)
  66. sender.grid(row=4, column=1, columnspan=3, padx=10, pady=10)
  67. sender.insert(0, 'justin')
  68. Label(newWindow, text='Recipient: ').grid(row=5, column=0)
  69. recipient = Entry(newWindow, width=35, borderwidth=5)
  70. recipient.grid(row=5, column=1, columnspan=3, padx=10, pady=10)
  71. recipient.insert(0, 'adam')
  72. # create the add contract button
  73. Button(newWindow, text = "Create contract", command=add).grid(row=6, column=1)
  74. def find_transaction():
  75. def find():
  76. conn = rpyc.connect(host='localhost', port=42069, keepalive=True)
  77. iden = get_plain_key(str(key.get()))
  78. transactions = [x.data for x in conn.root.find_transactions(iden)]
  79. transactions = decrypt_transactions(transactions, str(key.get()))
  80. print(current_contract_state(transactions, iden=iden))
  81. conn.close()
  82. newWindow.destroy()
  83. newWindow = Tk()
  84. newWindow.title('Add contract')
  85. Label(newWindow, text='Contract key: ').grid(row=0, column=0)
  86. key = Entry(newWindow, width=35, borderwidth=5)
  87. key.grid(row=0, column=1, columnspan=3, padx=10, pady=10)
  88. key.insert(0, '1')
  89. Button(newWindow, text='find contracts', command=find).grid(row=1, column=1)
  90. def add_term():
  91. def add():
  92. conn = rpyc.connect(host='localhost', port=42069, keepalive=True)
  93. iden = get_plain_key(str(contract.get()))
  94. attr = str(change.get())
  95. value = str(values.get())
  96. comment = str(comments.get())
  97. transactions = [x.data for x in conn.root.find_transactions(iden)]
  98. transactions = decrypt_transactions(transactions, str(contract.get()))
  99. state = current_contract_state(transactions, iden)
  100. if attr in state['data'] or attr in state['terms']:
  101. t = 'modify'
  102. else: t = 'update'
  103. # add new or updated info to block
  104. update = {'id':iden,
  105. 'update id':len(get_updates(transactions, iden=iden)),
  106. 'updated':attr,
  107. 'type':t,
  108. 'last update':time.time(),
  109. 'accepted': True,
  110. 'change':{attr:value}}
  111. # check if comment is passed and add it if necassary
  112. if comment:
  113. update['comment'] = comment
  114. t = Transaction()
  115. t.set_contract(update)
  116. t.hash(contract=iden)
  117. conn.root.push_transaction(t.serialize(out_json=True))
  118. #### TEST CODE PLEASE IGONRE ####
  119. update = {
  120. 'id':iden,
  121. 'update id':0,
  122. 'accept':True,
  123. 'type':'accept',
  124. 'last update':time.time()
  125. }
  126. if comment:
  127. update['comment'] = comment
  128. t = Transaction()
  129. t.set_contract(update)
  130. t.hash(contract=iden)
  131. conn.root.push_transaction(t.serialize(out_json=True))
  132. #### END TEST CODE PLEASE DONT IGONRE ####
  133. conn.close()
  134. newWindow.destroy()
  135. newWindow = Tk()
  136. newWindow.title('Add contract')
  137. # create all text boxes
  138. Label(newWindow, text='Contract: ').grid(row=0, column=0)
  139. contract = Entry(newWindow, width=35, borderwidth=5)
  140. contract.grid(row=0, column=1, columnspan=3, padx=10, pady=10)
  141. contract.insert(0, '1')
  142. Label(newWindow, text='What to change or add: ').grid(row=1, column=0)
  143. change = Entry(newWindow, width=35, borderwidth=5)
  144. change.grid(row=1, column=1, columnspan=3, padx=10, pady=10)
  145. change.insert(0, 'progress')
  146. Label(newWindow, text='New value: ').grid(row=2, column=0)
  147. values = Entry(newWindow, width=35, borderwidth=5)
  148. values.grid(row=2, column=1, columnspan=3, padx=10, pady=10)
  149. values.insert(0, '50%')
  150. Label(newWindow, text='comment (optional): ').grid(row=2, column=0)
  151. comments = Entry(newWindow, width=35, borderwidth=5)
  152. comments.grid(row=3, column=1, columnspan=3, padx=10, pady=10)
  153. comments.insert(0, 'dit is een comment')
  154. Button(newWindow, text='Add term', command=add).grid(row=4, column=1)
  155. def current_contract_state(transactions, iden):
  156. # set up contract state
  157. state = {'id':iden,
  158. 'data':{},
  159. 'terms':{}
  160. }
  161. # save not yet approved updates
  162. updates = {}
  163. # loop over all transaction in block
  164. for item in transactions:
  165. # save data about our project
  166. if item['id'] == iden:
  167. # set state to inital contract state
  168. if item['type'] == 'init':
  169. state = item
  170. continue
  171. # if update is not accept update, save it to updates dict
  172. if item['type'] != 'accept':
  173. # comments are always accepted
  174. if item['updated'] != 'comments':
  175. updates[item['update id']] = item
  176. continue
  177. # if accepted is true, retrieve update form dict and add to contract state
  178. elif item['accept'] == True:
  179. item = updates[item['update id']]
  180. # set attr to whatever has been updated
  181. attr = item['updated']
  182. # check if the update was removal
  183. if item['type'] == 'remove':
  184. # delete item in the right part of the dict
  185. try:
  186. if attr in state['data']:
  187. del state['data'][attr]
  188. else:
  189. del state['terms'][attr]
  190. except:
  191. pass
  192. if item['type'] == 'update':
  193. state['terms'][attr] = item['change'][attr]
  194. # check if updated attr is data or terms
  195. elif attr in state['data']:
  196. state['data'][attr] = item['change'][attr]
  197. elif attr in state['terms']:
  198. # special case for comments
  199. if attr == 'comments' and item['type'] not in ['remove', 'init']:
  200. k = list(item['change'][attr].keys())[0]
  201. state['terms'][attr][k] = item['change'][attr][k]
  202. # case for normal updates
  203. else:
  204. state['terms'][attr] = item['change'][attr]
  205. # special cases for last update and date of initiation
  206. elif 'last update' in item:
  207. state['last update'] = item['last update']
  208. return state
  209. def get_updates(transactions, iden=None, attr=None, accepted=None):
  210. updates = []
  211. # get all blocks and loop over transactions
  212. for item in transactions:
  213. # if attr is '' get updates for all attributes
  214. if attr == None:
  215. # if iden is None, get updates for all contracts
  216. # updates for all contracts and attrs
  217. if iden == None:
  218. if item['type'] != 'init':
  219. updates.append(item)
  220. # updates for specific contracts from all attr
  221. else:
  222. if item['type'] != 'init' and item['id'] == iden:
  223. updates.append(item)
  224. else:
  225. # updates for specific attrs from all contract
  226. if iden == None:
  227. if item['type'] != 'init' and item['updated'] == attr:
  228. updates.append(item)
  229. # updates for specific contract and specific attr
  230. else:
  231. if item['type'] != 'init' and item['updated'] == attr and item['id'] == iden:
  232. updates.append(item)
  233. return updates
  234. def decrypt_transactions(transactions, name):
  235. private_key = get_plain_key(name)
  236. decrypted = []
  237. for encrypted in transactions:
  238. decrypting_message = private_key.decrypt(
  239. encrypted,
  240. padding.OAEP(
  241. mgf=padding.MGF1(algorithm=hashes.SHA256()),
  242. algorithm=hashes.SHA256(),
  243. label=None
  244. )
  245. )
  246. decrypted.append(decrypting_message)
  247. return decrypted