Kaynağa Gözat

finishing touches, commenting code, and cleaning up code

justtheboss97 4 yıl önce
ebeveyn
işleme
c30eacdd4c
7 değiştirilmiş dosya ile 92 ekleme ve 165 silme
  1. 16 35
      create_keys.py
  2. 0 0
      data/block.json
  3. 8 20
      gui.py
  4. 49 6
      gui/data.py
  5. 14 6
      gui/encyption.py
  6. 5 87
      gui/gui_helpers.py
  7. 0 11
      lib/transaction.py

+ 16 - 35
create_keys.py

@@ -7,74 +7,55 @@ from cryptography.hazmat.primitives import serialization
 from cryptography.fernet import Fernet
 
 def make_keys(contract_name):
-    (public_key,private_key)=rsa.newkeys(2048)
-    # private_key = rsa.generate_private_key(
-    #     public_exponent=65537,
-    #     key_size=2048,
-    #     backend=default_backend()
-    #     )
-    # public_key = private_key.public_key()
 
-    # pem = public_key.public_bytes(
-    #     encoding=serialization.Encoding.PEM,
-    #     format=serialization.PublicFormat.SubjectPublicKeyInfo
-    # )
+    # create pubkey and private key for new contract
+    (public_key,private_key)=rsa.newkeys(2048)
 
-    #path = 'contract_keys\\' + contract_name + '\\'
+    # save them in contract folder
     path = f'contract_keys\\{contract_name}\\'
     os.makedirs(path, exist_ok=True)
     
+    # write pubkey
     with open(path + 'publickey.key','wb') as f:
         f.write(public_key.save_pkcs1('PEM'))
 
-    # pem = private_key.private_bytes(
-    #     encoding=serialization.Encoding.PEM,
-    #     format=serialization.PrivateFormat.PKCS8,
-    #     encryption_algorithm=serialization.NoEncryption()
-    # )
-
+    # write private key
     with open(path + 'privatekey.key','wb') as f:
         f.write(private_key.save_pkcs1('PEM'))    
     
+    # create semmetric key
     symmetric_key = Fernet.generate_key()
-
     with open(path + 'symmetric.key','wb') as f:
         f.write(symmetric_key)
-    
+
+# retrieve public key
 def get_keys(contract_name):
     path = 'contract_keys\\' + contract_name  + '\\publickey.key'
 
-    # with open(path, 'rb') as f:
-    #     public_key = serialization.load_pem_public_key(
-    #         f.read(),
-    #         backend=default_backend()
-    #         )
-    #     return public_key
-
+    # retreive public key form path
     with open(path, 'rb') as f:
         return rsa.PublicKey.load_pkcs1(f.read())
 
+# retrieve symmetric key
 def get_symmetric_key(contract_name):
     path = 'contract_keys\\' + contract_name  + '\\symmetric.key'
 
+    # read semmetric key from file
     with open(path, 'rb') as f:
         return f.read()
 
+# get private key
 def get_private_key(contract_name):
     path = 'contract_keys\\' + contract_name  + '\\privatekey.key'
 
-    # with open(path, "rb") as key_file:
-    #     private_key = serialization.load_pem_private_key(
-    #         key_file.read(),
-    #         password=None,
-    #         backend=default_backend()
-    #     )
-    # return private_key
+    # read private key from file
     with open(path, 'rb') as f:
         return rsa.PrivateKey.load_pkcs1(f.read())
 
-
+# get key in plain text (only public key)
 def get_plain_key(contract_name):
     path = 'contract_keys\\' + contract_name  + '\\publickey.key'
+
+    # read file and remove unnecessary suf 
     with open(path, 'rt') as f:
         return f.read().split('-----')[2].strip().replace('\n', '')

Dosya farkı çok büyük olduğundan ihmal edildi
+ 0 - 0
data/block.json


+ 8 - 20
gui.py

@@ -1,36 +1,24 @@
-from tkinter import *
-from linked_data import Chain, format_dict
 import pprint
-# from gui.gui_helpers import add_contract
-from gui.data import new_contract, find_transaction, add_term, accept_updates
-
-from lib.transaction import Transaction
-from lib.contract import Contract
+from tkinter import *
 
 import rpyc
 from rpyc.utils.server import ThreadPoolServer
 
+from gui.data import accept_updates, add_term, find_transaction, new_contract
+from lib.contract import Contract
+from lib.transaction import Transaction
+from linked_data import Chain, format_dict
 
+# initialize gui
 root = Tk()
 root.title('dsp blockchain')
 
-# view = Entry(root, width=35, borderwidth=5)
-# view.grid(row=0, column=1, columnspan=3, padx=10, pady=10)
-
-# accept_id = Entry(root, width=35, borderwidth=5)
-# accept_id.grid(row=4, column=1, columnspan=3, padx=10, pady=10)
-# accept_id.insert(0, 'contract')
-
-# accept_status = StringVar(root)
-# accept_status.set('False') # default value
-# OptionMenu(root, accept_status, 'False', 'True').grid(row=4, column=4)
-
-
+# create buttons
 Button(root, text="New contract", command=new_contract).grid(row=1, column=0, padx=10, pady=5)
 Button(root, text="Find contract", command=find_transaction).grid(row=1, column=1, padx=10, pady=5)
 Button(root, text="Add term", command=add_term).grid(row=1, column=2, padx=10, pady=5)
 Button(root, text="Accept updates", command=accept_updates).grid(row=1, column=3, padx=10, pady=5)
 
-
+# start
 root.mainloop()
 

+ 49 - 6
gui/data.py

@@ -1,8 +1,8 @@
 import json
 import os
+import pprint
 import time
 from tkinter import *
-import pprint
 
 import rpyc
 from create_keys import get_plain_key, get_private_key, make_keys
@@ -19,8 +19,11 @@ def new_contract():
         name = str(title.get())
 
         if not os.path.isdir('contract_keys\\' + name):
+
+            # get data form gui
             make_keys(name)
             pubkey = get_plain_key(name)
+
             # set discriptors of contract
             contract = {'id':pubkey,
                         'type':'init',
@@ -38,15 +41,22 @@ def new_contract():
                                     }
                         }
 
+            # create transaction and set contract to contents
             t = Transaction()
             t.set_contract(contract)
+
+            # encrypt data
             t.hash(contract=name)
+
+            # push transaction to blockchain
             temp = t.serialize(out_json=True)
             conn = rpyc.connect(host='localhost', port=42069, keepalive=True)
             conn.root.push_transaction(temp)
 
             conn.close()
             newWindow.destroy()
+        
+        # if contract name already exists, print message and try again
         else: 
             print('Contract name already exists, choose another')
             newWindow.destroy()
@@ -88,15 +98,24 @@ def new_contract():
     recipient.insert(0, 'adam')
 
     # create the add contract button
-    Button(newWindow, text = "Create contract", command=add).grid(row=6, column=1)
+    Button(newWindow, text = "Create contract", command=add).grid(row=6, column=1, padx=10, pady=5)
+
 
 def find_transaction():
+
+    # get current state of contract
     def find():
         conn = rpyc.connect(host='localhost', port=42069, keepalive=True)
+
+        # find all transactions of a contract
         iden = get_plain_key(str(key.get()))
         transactions = conn.root.find_transactions(iden)
+
+        # check if contract exists
         if len(transactions) == 0:
             print('No contract found')
+        
+        # build current state of contract and print to console
         else:
             transactions = decrypt_transactions(transactions, str(key.get()))
             print('Current contract state')
@@ -105,26 +124,37 @@ def find_transaction():
         conn.close()
         newWindow.destroy()
 
+    # get current state and all transactions
     def findall():
         conn = rpyc.connect(host='localhost', port=42069, keepalive=True)
+
+        # find all transactions of a contract
         iden = get_plain_key(str(key.get()))
         transactions = conn.root.find_transactions(iden)
+
+        # check if contract exists
         if len(transactions) == 0:
             print('No contract found')
+
+        # build current state of contract and print to console
         else:
             transactions = decrypt_transactions(transactions, str(key.get()))
             print('All updates')
+
+            # show all updates of contract
             for item in transactions:
                 if item['type'] != 'init':
                     pprint.pprint(item)
                     print('\n')
 
+            # show contract
             print('Current contract state')
             pprint.pprint(current_contract_state(transactions, iden=iden))
 
         conn.close()
         newWindow.destroy()
 
+    # gui setup
     newWindow = Tk()
     newWindow.title('Find contract')
 
@@ -133,14 +163,15 @@ def find_transaction():
     key.grid(row=0, column=1, columnspan=3, padx=10, pady=10)
     key.insert(0, 'test')
 
-    Button(newWindow, text='find contracts', command=find).grid(row=2, column=0)
-    Button(newWindow, text='find contracts and updates', command=findall).grid(row=2, column=1)
+    Button(newWindow, text='find contracts', command=find).grid(row=2, column=0, padx=10, pady=5)
+    Button(newWindow, text='find contracts and updates', command=findall).grid(row=2, column=1, padx=10, pady=5)
 
 
 def add_term():
     def add():
         conn = rpyc.connect(host='localhost', port=42069, keepalive=True)
         
+        # retrieve data from gui
         iden = get_plain_key(str(contract.get()))
         attr = str(change.get())
         value = str(values.get())
@@ -149,6 +180,7 @@ def add_term():
         transactions = decrypt_transactions(transactions, str(contract.get()))
         state = current_contract_state(transactions, iden)
 
+        # check type of transaction
         if value == '':
             t = 'remove'
         elif attr in state['data'] or attr in state['terms']:
@@ -170,6 +202,7 @@ def add_term():
         if comment:
             update['comment'] = comment
 
+        # create transacion, hash it and push to blockchain
         t = Transaction()
         t.set_contract(update)
         t.hash(contract=str(contract.get()))
@@ -202,16 +235,20 @@ def add_term():
     comments.grid(row=3, column=1, columnspan=3, padx=10, pady=10)
     comments.insert(0, 'dit is een comment')
 
-    Button(newWindow, text='Add term', command=add).grid(row=4, column=1)
+    Button(newWindow, text='Add term', command=add).grid(row=4, column=1, padx=10, pady=5)
 
 def accept_updates():
     def show():
         conn = rpyc.connect(host='localhost', port=42069, keepalive=True)
+
+        # find all transactions based on given contract
         name = str(contract.get())
         transactions = conn.root.find_transactions(get_plain_key(name))
         transactions = decrypt_transactions(transactions, name)
         updates = retrieve_updates(transactions, name, accepted=False)
         conn.close()
+
+        # show updates to accept
         if len(updates) == 0:
             print('No updates to accept')
         else:
@@ -221,6 +258,8 @@ def accept_updates():
 
     def accept():
         conn = rpyc.connect(host='localhost', port=42069, keepalive=True)
+
+        # get data from gui
         name = str(contract.get())
         update_id = int(change.get())
         answer = accept_status.get()
@@ -230,6 +269,7 @@ def accept_updates():
 
         comment_text = str(comment.get())
 
+        # set transaction data
         update = {
             'id':get_plain_key(name),
             'update id':update_id,
@@ -240,6 +280,7 @@ def accept_updates():
         if comment_text:
             update['comment'] = comment_text
 
+        # create transacion, hash it and push to blockchain
         t = Transaction()
         t.set_contract(update)
         t.hash(contract=str(contract.get()))
@@ -388,6 +429,7 @@ def retrieve_updates(all_updates, iden, accepted=None):
 
     updates = {}
     
+    # for all updates, only find modify and remove updates
     for item in all_updates:
         if item['type'] == 'init':
             continue
@@ -402,8 +444,9 @@ def retrieve_updates(all_updates, iden, accepted=None):
     if accepted == None:
         return updates 
     
+    # only return updates based on accepted argument
     return [updates[x] for x in list(updates.keys()) if updates[x]['accepted'] == accepted]
 
-
+# creates list of all decrypted transactions
 def decrypt_transactions(transactions, name):
     return [json.loads(decrypt_data(name, x)) for x in transactions]

+ 14 - 6
gui/encyption.py

@@ -6,26 +6,34 @@ from cryptography.hazmat.backends import default_backend
 from cryptography.hazmat.primitives import hashes, serialization
 from cryptography.hazmat.primitives.asymmetric import padding
 
-
+# encrypt blockstring with name from contract
 def encrypt_data(contract, block_string): 
+
+    # create symmetric key for transaction and retrieve pubkey from contract
     symmetric_key = get_symmetric_key(contract)
     pubkey = get_keys(contract)
 
+    # create chiper and encrypt data using symmetric key
     chiper = Fernet(symmetric_key)
-
     data = str(chiper.encrypt(block_string))[2:-1]
 
+    # encrypt semmetric key with pubkey and cast to string
     encrypted_key = str(rsa.encrypt(symmetric_key,pubkey))[2:-1]
-    # encrypted_key = rsa.encrypt(symmetric_key,pubkey)
-    print('ENCRYPTED KEY: ', type(encrypted_key), encrypted_key)
     return data, encrypted_key
 
-
+# decrypt t form contract name
 def decrypt_data(name, t):
+
+    # retrieve private key
     private_key = get_private_key(name)
+
+    # decript symmetric key
     en_key = encode(t.encrypted_key.encode().decode('unicode_escape'),"raw_unicode_escape")
     key = rsa.decrypt(en_key, private_key)
+
+    # decrypt data with decrypted semmetric key
     cipher = Fernet(key)
     decrypted_data = cipher.decrypt(bytes(t.data, 'utf-8'))
-    # print(decrypted_data)
+
+    # decode and retrun data
     return decrypted_data.decode('utf8').replace("'", '"')

+ 5 - 87
gui/gui_helpers.py

@@ -8,6 +8,10 @@ import rpyc
 import time
 import json
 
+###########################
+# OLD CODE PLEASE IGONORE #
+###########################
+
 def add_contract():
 
     # add contract to the blockchain
@@ -118,90 +122,4 @@ def add_contract():
     recipient.grid(row=5, column=1, columnspan=3, padx=10, pady=10)
 
     # create the add contract button
-    Button(newWindow, text = "Create contract", command=add).grid(row=6, column=1)
-
-
-
-## old code used for checking sytax of Tkinter 
-
-# def update():
-
-#     def up():
-#         chain.update_contract(int(iden.get()), term.get(), update_value.get(), name.get())
-
-#         newWindow.destroy()
-#         print('update pending approval')
-
-#     newWindow = Toplevel(root)
-#     newWindow.title('Update terms')
-
-#     Label(newWindow, text='Contract id: ').grid(row=0, column=0)
-#     iden =  Entry(newWindow, width=35, borderwidth=5)
-#     iden.grid(row=0, column=1, columnspan=3, padx=10, pady=10)
-
-#     Label(newWindow, text='Term: ').grid(row=1, column=0)
-#     term =  Entry(newWindow, width=35, borderwidth=5)
-#     term.grid(row=1, column=1, columnspan=3, padx=10, pady=10)
-
-#     Label(newWindow, text='New value: ').grid(row=2, column=0)
-#     update_value =  Entry(newWindow, width=35, borderwidth=5)
-#     update_value.grid(row=2, column=1, columnspan=3, padx=10, pady=10)
-
-#     Label(newWindow, text='Name: ').grid(row=3, column=0)
-#     name =  Entry(newWindow, width=35, borderwidth=5)
-#     name.grid(row=3, column=1, columnspan=3, padx=10, pady=10)
-    
-#     Button(newWindow, text='Update', command=up).grid(row=4, column=0)
-
-
-# def accept_update():
-#     def accept_up():
-#         c = comment.get()
-#         ans = awnser.get()
-#         if ans == 'False':
-#             ans = False
-#         else: ans = True
-
-#         if c == '':
-#             chain.accept_update(int(iden.get()), int(update_id.get()), ans, name.get())
-#         else:
-#             chain.accept_update(int(iden.get()), int(update_id.get()), ans, name.get(), c)
-
-#         newWindow.destroy()
-
-
-#     newWindow = Toplevel(root)
-#     newWindow.title('Update terms')
-
-#     Label(newWindow, text='Contract id: ').grid(row=0, column=0)
-#     iden =  Entry(newWindow, width=35, borderwidth=5)
-#     iden.grid(row=0, column=1, columnspan=3, padx=10, pady=10)
-
-#     Label(newWindow, text='Update id: ').grid(row=1, column=0)
-#     update_id =  Entry(newWindow, width=35, borderwidth=5)
-#     update_id.grid(row=1, column=1, columnspan=3, padx=10, pady=10)
-
-#     Label(newWindow, text='Awnser ').grid(row=2, column=0)
-#     awnser =  Entry(newWindow, width=35, borderwidth=5)
-#     awnser.grid(row=2, column=1, columnspan=3, padx=10, pady=10)
-
-#     Label(newWindow, text='Name: ').grid(row=3, column=0)
-#     name =  Entry(newWindow, width=35, borderwidth=5)
-#     name.grid(row=3, column=1, columnspan=3, padx=10, pady=10)
-
-#     Label(newWindow, text='Comment optional: ').grid(row=3, column=0)
-#     comment =  Entry(newWindow, width=35, borderwidth=5)
-#     comment.grid(row=3, column=1, columnspan=3, padx=10, pady=10)
-    
-#     Button(newWindow, text='Update', command=accept_up).grid(row=4, column=0)
-    
-# def view_updates():
-#     status =accept_status.get()
-#     if status == 'False':
-#         status = False
-#     else: status = True
-#     iden = int(accept_id.get())
-#     if status == None:
-#         pprint.pprint(chain.retrieve_updates(iden))
-#     else:
-#         pprint.pprint(chain.retrieve_updates(iden, status))
+    Button(newWindow, text = "Create contract", command=add).grid(row=6, column=1)

+ 0 - 11
lib/transaction.py

@@ -78,17 +78,6 @@ class Transaction:
 
         self.data, self.encrypted_key = encrypt_data(contract, block_string)
 
-
-        # open the public key file
-         # we need an extra field in the transaction
-        # encrypted_data = pubkey.encrypt(
-        #     block_string,
-        #     padding.OAEP(
-        #         mgf=padding.MGF1(algorithm=hashes.SHA256()),
-        #         algorithm=hashes.SHA256(),
-        #         label=None
-        #     )
-        # )
         self.log(f'Hashed: {self.hash_value}')
 
 

Bu fark içinde çok fazla dosya değişikliği olduğu için bazı dosyalar gösterilmiyor